Fri Jul 15 2011 11:57:42

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: 325277 $")
00211 
00212 #include <ctype.h>
00213 #include <sys/ioctl.h>
00214 #include <fcntl.h>
00215 #include <signal.h>
00216 #include <sys/signal.h>
00217 #include <regex.h>
00218 #include <time.h>
00219 
00220 #include "asterisk/network.h"
00221 #include "asterisk/paths.h"   /* need ast_config_AST_SYSTEM_NAME */
00222 
00223 #include "asterisk/lock.h"
00224 #include "asterisk/channel.h"
00225 #include "asterisk/config.h"
00226 #include "asterisk/module.h"
00227 #include "asterisk/pbx.h"
00228 #include "asterisk/sched.h"
00229 #include "asterisk/io.h"
00230 #include "asterisk/rtp.h"
00231 #include "asterisk/udptl.h"
00232 #include "asterisk/acl.h"
00233 #include "asterisk/manager.h"
00234 #include "asterisk/callerid.h"
00235 #include "asterisk/cli.h"
00236 #include "asterisk/app.h"
00237 #include "asterisk/musiconhold.h"
00238 #include "asterisk/dsp.h"
00239 #include "asterisk/features.h"
00240 #include "asterisk/srv.h"
00241 #include "asterisk/astdb.h"
00242 #include "asterisk/causes.h"
00243 #include "asterisk/utils.h"
00244 #include "asterisk/file.h"
00245 #include "asterisk/astobj.h"
00246 /* 
00247    Uncomment the define below,  if you are having refcount related memory leaks.
00248    With this uncommented, this module will generate a file, /tmp/refs, which contains
00249    a history of the ao2_ref() calls. To be useful, all calls to ao2_* functions should
00250    be modified to ao2_t_* calls, and include a tag describing what is happening with 
00251    enough detail, to make pairing up a reference count increment with its corresponding decrement.
00252    The refcounter program in utils/ can be invaluable in highlighting objects that are not
00253    balanced, along with the complete history for that object.
00254    In normal operation, the macros defined will throw away the tags, so they do not 
00255    affect the speed of the program at all. They can be considered to be documentation.
00256 */
00257 /* #define  REF_DEBUG 1 */
00258 #include "asterisk/astobj2.h"
00259 #include "asterisk/dnsmgr.h"
00260 #include "asterisk/devicestate.h"
00261 #include "asterisk/linkedlists.h"
00262 #include "asterisk/stringfields.h"
00263 #include "asterisk/monitor.h"
00264 #include "asterisk/netsock.h"
00265 #include "asterisk/localtime.h"
00266 #include "asterisk/abstract_jb.h"
00267 #include "asterisk/threadstorage.h"
00268 #include "asterisk/translate.h"
00269 #include "asterisk/ast_version.h"
00270 #include "asterisk/event.h"
00271 #include "asterisk/tcptls.h"
00272 #include "asterisk/strings.h"
00273 
00274 /*** DOCUMENTATION
00275    <application name="SIPDtmfMode" language="en_US">
00276       <synopsis>
00277          Change the dtmfmode for a SIP call.
00278       </synopsis>
00279       <syntax>
00280          <parameter name="mode" required="true">
00281             <enumlist>
00282                <enum name="inband" />
00283                <enum name="info" />
00284                <enum name="rfc2833" />
00285             </enumlist>
00286          </parameter>
00287       </syntax>
00288       <description>
00289          <para>Changes the dtmfmode for a SIP call.</para>
00290       </description>
00291    </application>
00292    <application name="SIPAddHeader" language="en_US">
00293       <synopsis>
00294          Add a SIP header to the outbound call.
00295       </synopsis>
00296       <syntax argsep=":">
00297          <parameter name="Header" required="true" />
00298          <parameter name="Content" required="true" />
00299       </syntax>
00300       <description>
00301          <para>Adds a header to a SIP call placed with DIAL.</para>
00302          <para>Remember to use the X-header if you are adding non-standard SIP
00303          headers, like <literal>X-Asterisk-Accountcode:</literal>. Use this with care.
00304          Adding the wrong headers may jeopardize the SIP dialog.</para>
00305          <para>Always returns <literal>0</literal>.</para>
00306       </description>
00307    </application>
00308    <application name="SIPRemoveHeader" language="en_US">
00309       <synopsis>
00310          Remove SIP headers previously added with SIPAddHeader
00311       </synopsis>
00312       <syntax>
00313          <parameter name="Header" required="false" />
00314       </syntax>
00315       <description>
00316          <para>SIPRemoveHeader() allows you to remove headers which were previously 
00317          added with SIPAddHeader(). If no parameter is supplied, all previously added 
00318          headers will be removed. If a parameter is supplied, only the matching headers 
00319          will be removed.</para>
00320          <para>For example you have added these 2 headers:</para>
00321          <para>SIPAddHeader(P-Asserted-Identity: sip:foo@bar);</para>
00322          <para>SIPAddHeader(P-Preferred-Identity: sip:bar@foo);</para>
00323          <para></para>
00324          <para>// remove all headers</para>
00325          <para>SIPRemoveHeader();</para>
00326          <para>// remove all P- headers</para>
00327          <para>SIPRemoveHeader(P-);</para>
00328          <para>// remove only the PAI header (note the : at the end)</para>
00329          <para>SIPRemoveHeader(P-Asserted-Identity:);</para>
00330          <para></para>
00331          <para>Always returns <literal>0</literal>.</para>
00332       </description>
00333    </application>
00334    <function name="SIP_HEADER" language="en_US">
00335       <synopsis>
00336          Gets the specified SIP header.
00337       </synopsis>
00338       <syntax>
00339          <parameter name="name" required="true" />
00340          <parameter name="number">
00341             <para>If not specified, defaults to <literal>1</literal>.</para>
00342          </parameter>
00343       </syntax>
00344       <description>
00345          <para>Since there are several headers (such as Via) which can occur multiple
00346          times, SIP_HEADER takes an optional second argument to specify which header with
00347          that name to retrieve. Headers start at offset <literal>1</literal>.</para>
00348       </description>
00349    </function>
00350    <function name="SIPPEER" language="en_US">
00351       <synopsis>
00352          Gets SIP peer information.
00353       </synopsis>
00354       <syntax>
00355          <parameter name="peername" required="true" />
00356          <parameter name="item">
00357             <enumlist>
00358                <enum name="ip">
00359                   <para>(default) The ip address.</para>
00360                </enum>
00361                <enum name="port">
00362                   <para>The port number.</para>
00363                </enum>
00364                <enum name="mailbox">
00365                   <para>The configured mailbox.</para>
00366                </enum>
00367                <enum name="context">
00368                   <para>The configured context.</para>
00369                </enum>
00370                <enum name="expire">
00371                   <para>The epoch time of the next expire.</para>
00372                </enum>
00373                <enum name="dynamic">
00374                   <para>Is it dynamic? (yes/no).</para>
00375                </enum>
00376                <enum name="callerid_name">
00377                   <para>The configured Caller ID name.</para>
00378                </enum>
00379                <enum name="callerid_num">
00380                   <para>The configured Caller ID number.</para>
00381                </enum>
00382                <enum name="callgroup">
00383                   <para>The configured Callgroup.</para>
00384                </enum>
00385                <enum name="pickupgroup">
00386                   <para>The configured Pickupgroup.</para>
00387                </enum>
00388                <enum name="codecs">
00389                   <para>The configured codecs.</para>
00390                </enum>
00391                <enum name="status">
00392                   <para>Status (if qualify=yes).</para>
00393                </enum>
00394                <enum name="regexten">
00395                   <para>Registration extension.</para>
00396                </enum>
00397                <enum name="limit">
00398                   <para>Call limit (call-limit).</para>
00399                </enum>
00400                <enum name="busylevel">
00401                   <para>Configured call level for signalling busy.</para>
00402                </enum>
00403                <enum name="curcalls">
00404                   <para>Current amount of calls. Only available if call-limit is set.</para>
00405                </enum>
00406                <enum name="language">
00407                   <para>Default language for peer.</para>
00408                </enum>
00409                <enum name="accountcode">
00410                   <para>Account code for this peer.</para>
00411                </enum>
00412                <enum name="useragent">
00413                   <para>Current user agent id for peer.</para>
00414                </enum>
00415                <enum name="chanvar[name]">
00416                   <para>A channel variable configured with setvar for this peer.</para>
00417                </enum>
00418                <enum name="codec[x]">
00419                   <para>Preferred codec index number <replaceable>x</replaceable> (beginning with zero).</para>
00420                </enum>
00421             </enumlist>
00422          </parameter>
00423       </syntax>
00424       <description></description>
00425    </function>
00426    <function name="SIPCHANINFO" language="en_US">
00427       <synopsis>
00428          Gets the specified SIP parameter from the current channel.
00429       </synopsis>
00430       <syntax>
00431          <parameter name="item" required="true">
00432             <enumlist>
00433                <enum name="peerip">
00434                   <para>The IP address of the peer.</para>
00435                </enum>
00436                <enum name="recvip">
00437                   <para>The source IP address of the peer.</para>
00438                </enum>
00439                <enum name="from">
00440                   <para>The URI from the <literal>From:</literal> header.</para>
00441                </enum>
00442                <enum name="uri">
00443                   <para>The URI from the <literal>Contact:</literal> header.</para>
00444                </enum>
00445                <enum name="useragent">
00446                   <para>The useragent.</para>
00447                </enum>
00448                <enum name="peername">
00449                   <para>The name of the peer.</para>
00450                </enum>
00451                <enum name="t38passthrough">
00452                   <para><literal>1</literal> if T38 is offered or enabled in this channel,
00453                   otherwise <literal>0</literal>.</para>
00454                </enum>
00455             </enumlist>
00456          </parameter>
00457       </syntax>
00458       <description></description>
00459    </function>
00460    <function name="CHECKSIPDOMAIN" language="en_US">
00461       <synopsis>
00462          Checks if domain is a local domain.
00463       </synopsis>
00464       <syntax>
00465          <parameter name="domain" required="true" />
00466       </syntax>
00467       <description>
00468          <para>This function checks if the <replaceable>domain</replaceable> in the argument is configured
00469          as a local SIP domain that this Asterisk server is configured to handle.
00470          Returns the domain name if it is locally handled, otherwise an empty string.
00471          Check the <literal>domain=</literal> configuration in <filename>sip.conf</filename>.</para>
00472       </description>
00473    </function>
00474  ***/
00475 
00476 #ifndef FALSE
00477 #define FALSE    0
00478 #endif
00479 
00480 #ifndef TRUE
00481 #define TRUE     1
00482 #endif
00483 
00484 /* Arguments for find_peer */
00485 #define FINDUSERS (1 << 0)
00486 #define FINDPEERS (1 << 1)
00487 #define FINDALLDEVICES (FINDUSERS | FINDPEERS)
00488 
00489 #define  SIPBUFSIZE     512      /*!< Buffer size for many operations */
00490 
00491 #define XMIT_ERROR      -2
00492 
00493 #define SIP_RESERVED ";/?:@&=+$,# "    /*!< Reserved characters in the username part of the URI */
00494 
00495 /* #define VOCAL_DATA_HACK */
00496 
00497 #define DEFAULT_DEFAULT_EXPIRY  120
00498 #define DEFAULT_MIN_EXPIRY      60
00499 #define DEFAULT_MAX_EXPIRY      3600
00500 #define DEFAULT_MWI_EXPIRY      3600
00501 #define DEFAULT_REGISTRATION_TIMEOUT 20
00502 #define DEFAULT_MAX_FORWARDS    "70"
00503 #define DEFAULT_AUTHLIMIT       100
00504 #define DEFAULT_AUTHTIMEOUT     30
00505 
00506 /* guard limit must be larger than guard secs */
00507 /* guard min must be < 1000, and should be >= 250 */
00508 #define EXPIRY_GUARD_SECS       15                /*!< How long before expiry do we reregister */
00509 #define EXPIRY_GUARD_LIMIT      30                /*!< Below here, we use EXPIRY_GUARD_PCT instead of 
00510                                                     EXPIRY_GUARD_SECS */
00511 #define EXPIRY_GUARD_MIN        500                /*!< This is the minimum guard time applied. If 
00512                                                    GUARD_PCT turns out to be lower than this, it 
00513                                                    will use this time instead.
00514                                                    This is in milliseconds. */
00515 #define EXPIRY_GUARD_PCT        0.20                /*!< Percentage of expires timeout to use when 
00516                                                     below EXPIRY_GUARD_LIMIT */
00517 #define DEFAULT_EXPIRY 900                          /*!< Expire slowly */
00518 
00519 static int min_expiry = DEFAULT_MIN_EXPIRY;        /*!< Minimum accepted registration time */
00520 static int max_expiry = DEFAULT_MAX_EXPIRY;        /*!< Maximum accepted registration time */
00521 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
00522 static int mwi_expiry = DEFAULT_MWI_EXPIRY;
00523 
00524 #define DEFAULT_QUALIFY_GAP   100
00525 #define DEFAULT_QUALIFY_PEERS 1
00526 
00527 
00528 #define CALLERID_UNKNOWN             "Anonymous"
00529 #define FROMDOMAIN_INVALID           "anonymous.invalid"
00530 
00531 #define DEFAULT_MAXMS                2000             /*!< Qualification: Must be faster than 2 seconds by default */
00532 #define DEFAULT_QUALIFYFREQ          60 * 1000        /*!< Qualification: How often to check for the host to be up */
00533 #define DEFAULT_FREQ_NOTOK           10 * 1000        /*!< Qualification: How often to check, if the host is down... */
00534 
00535 #define DEFAULT_RETRANS              1000             /*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
00536 #define MAX_RETRANS                  6                /*!< Try only 6 times for retransmissions, a total of 7 transmissions */
00537 #define DEFAULT_TIMER_T1                 500              /*!< SIP timer T1 (according to RFC 3261) */
00538 #define SIP_TRANS_TIMEOUT            64 * DEFAULT_TIMER_T1 /*!< SIP request timeout (rfc 3261) 64*T1 
00539                                                       \todo Use known T1 for timeout (peerpoke)
00540                                                       */
00541 #define DEFAULT_TRANS_TIMEOUT        -1               /*!< Use default SIP transaction timeout */
00542 #define PROVIS_KEEPALIVE_TIMEOUT     60000            /*!< How long to wait before retransmitting a provisional response (rfc 3261 13.3.1.1) */
00543 #define MAX_AUTHTRIES                3                /*!< Try authentication three times, then fail */
00544 
00545 #define SIP_MAX_HEADERS              64               /*!< Max amount of SIP headers to read */
00546 #define SIP_MAX_LINES                256              /*!< Max amount of lines in SIP attachment (like SDP) */
00547 #define SIP_MIN_PACKET               4096             /*!< Initialize size of memory to allocate for packets */
00548 #define MAX_HISTORY_ENTRIES        50                /*!< Max entires in the history list for a sip_pvt */
00549 
00550 #define INITIAL_CSEQ                 101              /*!< Our initial sip sequence number */
00551 
00552 #define DEFAULT_MAX_SE               1800             /*!< Session-Timer Default Session-Expires period (RFC 4028) */
00553 #define DEFAULT_MIN_SE               90               /*!< Session-Timer Default Min-SE period (RFC 4028) */
00554 
00555 #define SDP_MAX_RTPMAP_CODECS        32               /*!< Maximum number of codecs allowed in received SDP */
00556 
00557 static int unauth_sessions = 0;
00558 static int authlimit = DEFAULT_AUTHLIMIT;
00559 static int authtimeout = DEFAULT_AUTHTIMEOUT;
00560 
00561 /*! \brief Global jitterbuffer configuration - by default, jb is disabled */
00562 static struct ast_jb_conf default_jbconf =
00563 {
00564    .flags = 0,
00565    .max_size = -1,
00566    .resync_threshold = -1,
00567    .impl = "",
00568    .target_extra = -1,
00569 };
00570 static struct ast_jb_conf global_jbconf;     /*!< Global jitterbuffer configuration */
00571 
00572 static const char config[] = "sip.conf";     /*!< Main configuration file */
00573 static const char notify_config[] = "sip_notify.conf";   /*!< Configuration file for sending Notify with CLI commands to reconfigure or reboot phones */
00574 
00575 #define RTP    1
00576 #define NO_RTP 0
00577 
00578 /*! \brief Authorization scheme for call transfers 
00579 
00580 \note Not a bitfield flag, since there are plans for other modes,
00581    like "only allow transfers for authenticated devices" */
00582 enum transfermodes {
00583    TRANSFER_OPENFORALL,            /*!< Allow all SIP transfers */
00584    TRANSFER_CLOSED,                /*!< Allow no SIP transfers */
00585 };
00586 
00587 
00588 /*! \brief The result of a lot of functions */
00589 enum sip_result {
00590    AST_SUCCESS = 0,     /*!< FALSE means success, funny enough */
00591    AST_FAILURE = -1,    /*!< Failure code */
00592 };
00593 
00594 /*! \brief States for the INVITE transaction, not the dialog 
00595    \note this is for the INVITE that sets up the dialog
00596 */
00597 enum invitestates {
00598    INV_NONE = 0,          /*!< No state at all, maybe not an INVITE dialog */
00599    INV_CALLING = 1,  /*!< Invite sent, no answer */
00600    INV_PROCEEDING = 2,  /*!< We got/sent 1xx message */
00601    INV_EARLY_MEDIA = 3,    /*!< We got 18x message with to-tag back */
00602    INV_COMPLETED = 4,   /*!< Got final response with error. Wait for ACK, then CONFIRMED */
00603    INV_CONFIRMED = 5,   /*!< Confirmed response - we've got an ack (Incoming calls only) */
00604    INV_TERMINATED = 6,  /*!< Transaction done - either successful (AST_STATE_UP) or failed, but done 
00605                  The only way out of this is a BYE from one side */
00606    INV_CANCELLED = 7,   /*!< Transaction cancelled by client or server in non-terminated state */
00607 };
00608 
00609 /*! \brief Readable descriptions of device states.
00610        \note Should be aligned to above table as index */
00611 static const struct invstate2stringtable {
00612    const enum invitestates state;
00613    const char *desc;
00614 } invitestate2string[] = {
00615    {INV_NONE,              "None"  },
00616    {INV_CALLING,           "Calling (Trying)"},
00617    {INV_PROCEEDING,        "Proceeding "},
00618    {INV_EARLY_MEDIA,       "Early media"},
00619    {INV_COMPLETED,         "Completed (done)"},
00620    {INV_CONFIRMED,         "Confirmed (up)"},
00621    {INV_TERMINATED,        "Done"},
00622    {INV_CANCELLED,         "Cancelled"}
00623 };
00624 
00625 /*! \brief When sending a SIP message, we can send with a few options, depending on
00626    type of SIP request. UNRELIABLE is moslty used for responses to repeated requests,
00627    where the original response would be sent RELIABLE in an INVITE transaction */
00628 enum xmittype {
00629    XMIT_CRITICAL = 2,              /*!< Transmit critical SIP message reliably, with re-transmits.
00630                                               If it fails, it's critical and will cause a teardown of the session */
00631    XMIT_RELIABLE = 1,              /*!< Transmit SIP message reliably, with re-transmits */
00632    XMIT_UNRELIABLE = 0,            /*!< Transmit SIP message without bothering with re-transmits */
00633 };
00634 
00635 /*! \brief Results from the parse_register() function */
00636 enum parse_register_result {
00637    PARSE_REGISTER_DENIED,
00638    PARSE_REGISTER_FAILED,
00639    PARSE_REGISTER_UPDATE,
00640    PARSE_REGISTER_QUERY,
00641 };
00642 
00643 /*! \brief Type of subscription, based on the packages we do support, see \ref subscription_types */
00644 enum subscriptiontype { 
00645    NONE = 0,
00646    XPIDF_XML,
00647    DIALOG_INFO_XML,
00648    CPIM_PIDF_XML,
00649    PIDF_XML,
00650    MWI_NOTIFICATION
00651 };
00652 
00653 /*! \brief Subscription types that we support. We support
00654    - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
00655    - SIMPLE presence used for device status
00656    - Voicemail notification subscriptions
00657 */
00658 static const struct cfsubscription_types {
00659    enum subscriptiontype type;
00660    const char * const event;
00661    const char * const mediatype;
00662    const char * const text;
00663 } subscription_types[] = {
00664    { NONE,        "-",        "unknown",               "unknown" },
00665    /* RFC 4235: SIP Dialog event package */
00666    { DIALOG_INFO_XML, "dialog",   "application/dialog-info+xml", "dialog-info+xml" },
00667    { CPIM_PIDF_XML,   "presence", "application/cpim-pidf+xml",   "cpim-pidf+xml" },  /* RFC 3863 */
00668    { PIDF_XML,        "presence", "application/pidf+xml",        "pidf+xml" },       /* RFC 3863 */
00669    { XPIDF_XML,       "presence", "application/xpidf+xml",       "xpidf+xml" },       /* Pre-RFC 3863 with MS additions */
00670    { MWI_NOTIFICATION,  "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
00671 };
00672 
00673 
00674 /*! \brief Authentication types - proxy or www authentication 
00675    \note Endpoints, like Asterisk, should always use WWW authentication to
00676    allow multiple authentications in the same call - to the proxy and
00677    to the end point.
00678 */
00679 enum sip_auth_type {
00680    PROXY_AUTH = 407,
00681    WWW_AUTH = 401,
00682 };
00683 
00684 /*! \brief Authentication result from check_auth* functions */
00685 enum check_auth_result {
00686    AUTH_DONT_KNOW = -100,  /*!< no result, need to check further */
00687       /* XXX maybe this is the same as AUTH_NOT_FOUND */
00688 
00689    AUTH_SUCCESSFUL = 0,
00690    AUTH_CHALLENGE_SENT = 1,
00691    AUTH_SECRET_FAILED = -1,
00692    AUTH_USERNAME_MISMATCH = -2,
00693    AUTH_NOT_FOUND = -3, /*!< returned by register_verify */
00694    AUTH_FAKE_AUTH = -4,
00695    AUTH_UNKNOWN_DOMAIN = -5,
00696    AUTH_PEER_NOT_DYNAMIC = -6,
00697    AUTH_ACL_FAILED = -7,
00698    AUTH_BAD_TRANSPORT = -8,
00699 };
00700 
00701 /*! \brief States for outbound registrations (with register= lines in sip.conf */
00702 enum sipregistrystate {
00703    REG_STATE_UNREGISTERED = 0,   /*!< We are not registered 
00704        *  \note Initial state. We should have a timeout scheduled for the initial
00705        * (or next) registration transmission, calling sip_reregister
00706        */
00707 
00708    REG_STATE_REGSENT,   /*!< Registration request sent 
00709        * \note sent initial request, waiting for an ack or a timeout to
00710        * retransmit the initial request.
00711       */
00712 
00713    REG_STATE_AUTHSENT,  /*!< We have tried to authenticate 
00714        * \note entered after transmit_register with auth info,
00715        * waiting for an ack.
00716        */
00717 
00718    REG_STATE_REGISTERED,   /*!< Registered and done */
00719 
00720    REG_STATE_REJECTED,  /*!< Registration rejected *
00721        * \note only used when the remote party has an expire larger than
00722        * our max-expire. This is a final state from which we do not
00723        * recover (not sure how correctly).
00724        */
00725 
00726    REG_STATE_TIMEOUT,   /*!< Registration timed out *
00727       * \note XXX unused */
00728 
00729    REG_STATE_NOAUTH, /*!< We have no accepted credentials
00730        * \note fatal - no chance to proceed */
00731 
00732    REG_STATE_FAILED, /*!< Registration failed after several tries
00733        * \note fatal - no chance to proceed */
00734 };
00735 
00736 /*! \brief Modes in which Asterisk can be configured to run SIP Session-Timers */
00737 enum st_mode {
00738         SESSION_TIMER_MODE_INVALID = 0, /*!< Invalid value */ 
00739         SESSION_TIMER_MODE_ACCEPT,      /*!< Honor inbound Session-Timer requests */
00740         SESSION_TIMER_MODE_ORIGINATE,   /*!< Originate outbound and honor inbound requests */
00741         SESSION_TIMER_MODE_REFUSE       /*!< Ignore inbound Session-Timers requests */
00742 };
00743 
00744 /*! \brief The entity playing the refresher role for Session-Timers */
00745 enum st_refresher {
00746         SESSION_TIMER_REFRESHER_AUTO,    /*!< Negotiated                      */
00747         SESSION_TIMER_REFRESHER_UAC,     /*!< Session is refreshed by the UAC */
00748         SESSION_TIMER_REFRESHER_UAS      /*!< Session is refreshed by the UAS */
00749 };
00750 
00751 /*! \brief Define some implemented SIP transports 
00752    \note Asterisk does not support SCTP or UDP/DTLS 
00753 */
00754 enum sip_transport {
00755    SIP_TRANSPORT_UDP = 1,     /*!< Unreliable transport for SIP, needs retransmissions */
00756    SIP_TRANSPORT_TCP = 1 << 1,   /*!< Reliable, but unsecure */
00757    SIP_TRANSPORT_TLS = 1 << 2,   /*!< TCP/TLS - reliable and secure transport for signalling */
00758 };
00759 
00760 /*! \brief definition of a sip proxy server
00761  *
00762  * For outbound proxies, a sip_peer will contain a reference to a 
00763  * dynamically allocated instance of a sip_proxy. A sip_pvt may also
00764  * contain a reference to a peer's outboundproxy, or it may contain
00765  * a reference to the sip_cfg.outboundproxy.
00766  */
00767 struct sip_proxy {
00768    char name[MAXHOSTNAMELEN];      /*!< DNS name of domain/host or IP */
00769    struct sockaddr_in ip;          /*!< Currently used IP address and port */
00770    time_t last_dnsupdate;          /*!< When this was resolved */
00771    enum sip_transport transport; 
00772    int force;                      /*!< If it's an outbound proxy, Force use of this outbound proxy for all outbound requests */
00773    /* Room for a SRV record chain based on the name */
00774 };
00775 
00776 /*! \brief argument for the 'show channels|subscriptions' callback. */
00777 struct __show_chan_arg { 
00778    int fd;
00779    int subscriptions;
00780    int numchans;   /* return value */
00781 };
00782 
00783 
00784 /*! \brief States whether a SIP message can create a dialog in Asterisk. */
00785 enum can_create_dialog {
00786    CAN_NOT_CREATE_DIALOG,
00787    CAN_CREATE_DIALOG,
00788    CAN_CREATE_DIALOG_UNSUPPORTED_METHOD,
00789 };
00790 
00791 /*! \brief SIP Request methods known by Asterisk 
00792 
00793    \note Do _NOT_ make any changes to this enum, or the array following it;
00794    if you think you are doing the right thing, you are probably
00795    not doing the right thing. If you think there are changes
00796    needed, get someone else to review them first _before_
00797    submitting a patch. If these two lists do not match properly
00798    bad things will happen.
00799 */
00800 
00801 enum sipmethod {
00802    SIP_UNKNOWN,      /*!< Unknown response */
00803    SIP_RESPONSE,     /*!< Not request, response to outbound request */
00804    SIP_REGISTER,     /*!< Registration to the mothership, tell us where you are located */
00805    SIP_OPTIONS,      /*!< Check capabilities of a device, used for "ping" too */
00806    SIP_NOTIFY,    /*!< Status update, Part of the event package standard, result of a SUBSCRIBE or a REFER */
00807    SIP_INVITE,    /*!< Set up a session */
00808    SIP_ACK,    /*!< End of a three-way handshake started with INVITE. */
00809    SIP_PRACK,     /*!< Reliable pre-call signalling. Not supported in Asterisk. */
00810    SIP_BYE,    /*!< End of a session */
00811    SIP_REFER,     /*!< Refer to another URI (transfer) */
00812    SIP_SUBSCRIBE,    /*!< Subscribe for updates (voicemail, session status, device status, presence) */
00813    SIP_MESSAGE,      /*!< Text messaging */
00814    SIP_UPDATE,    /*!< Update a dialog. We can send UPDATE; but not accept it */
00815    SIP_INFO,      /*!< Information updates during a session */
00816    SIP_CANCEL,    /*!< Cancel an INVITE */
00817    SIP_PUBLISH,      /*!< Not supported in Asterisk */
00818    SIP_PING,      /*!< Not supported at all, no standard but still implemented out there */
00819 };
00820 
00821 /*! \brief Settings for the 'notifycid' option, see sip.conf.sample for details. */
00822 enum notifycid_setting {
00823    DISABLED       = 0,
00824    ENABLED        = 1,
00825    IGNORE_CONTEXT = 2,
00826 };
00827 
00828 /*! \brief The core structure to setup dialogs. We parse incoming messages by using
00829    structure and then route the messages according to the type.
00830 
00831       \note Note that sip_methods[i].id == i must hold or the code breaks */
00832 static const struct  cfsip_methods { 
00833    enum sipmethod id;
00834    int need_rtp;     /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
00835    char * const text;
00836    enum can_create_dialog can_create;
00837 } sip_methods[] = {
00838    { SIP_UNKNOWN,  RTP,    "-UNKNOWN-",   CAN_CREATE_DIALOG },
00839    { SIP_RESPONSE,    NO_RTP, "SIP/2.0",  CAN_NOT_CREATE_DIALOG },
00840    { SIP_REGISTER,    NO_RTP, "REGISTER",    CAN_CREATE_DIALOG },
00841    { SIP_OPTIONS,  NO_RTP, "OPTIONS",  CAN_CREATE_DIALOG },
00842    { SIP_NOTIFY,   NO_RTP, "NOTIFY",   CAN_CREATE_DIALOG },
00843    { SIP_INVITE,   RTP,    "INVITE",   CAN_CREATE_DIALOG },
00844    { SIP_ACK,   NO_RTP, "ACK",   CAN_NOT_CREATE_DIALOG },
00845    { SIP_PRACK,    NO_RTP, "PRACK",    CAN_NOT_CREATE_DIALOG },
00846    { SIP_BYE,   NO_RTP, "BYE",   CAN_NOT_CREATE_DIALOG },
00847    { SIP_REFER,    NO_RTP, "REFER",    CAN_CREATE_DIALOG },
00848    { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",  CAN_CREATE_DIALOG },
00849    { SIP_MESSAGE,  NO_RTP, "MESSAGE",  CAN_CREATE_DIALOG },
00850    { SIP_UPDATE,   NO_RTP, "UPDATE",   CAN_NOT_CREATE_DIALOG },
00851    { SIP_INFO,  NO_RTP, "INFO",  CAN_NOT_CREATE_DIALOG },
00852    { SIP_CANCEL,   NO_RTP, "CANCEL",   CAN_NOT_CREATE_DIALOG },
00853    { SIP_PUBLISH,  NO_RTP, "PUBLISH",  CAN_CREATE_DIALOG_UNSUPPORTED_METHOD },
00854    { SIP_PING,  NO_RTP, "PING",  CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
00855 };
00856 
00857 static unsigned int chan_idx;
00858 
00859 /*!  Define SIP option tags, used in Require: and Supported: headers 
00860    We need to be aware of these properties in the phones to use 
00861    the replace: header. We should not do that without knowing
00862    that the other end supports it... 
00863    This is nothing we can configure, we learn by the dialog
00864    Supported: header on the REGISTER (peer) or the INVITE
00865    (other devices)
00866    We are not using many of these today, but will in the future.
00867    This is documented in RFC 3261
00868 */
00869 #define SUPPORTED    1
00870 #define NOT_SUPPORTED      0
00871 
00872 /* SIP options */
00873 #define SIP_OPT_REPLACES   (1 << 0)
00874 #define SIP_OPT_100REL     (1 << 1)
00875 #define SIP_OPT_TIMER      (1 << 2)
00876 #define SIP_OPT_EARLY_SESSION (1 << 3)
00877 #define SIP_OPT_JOIN    (1 << 4)
00878 #define SIP_OPT_PATH    (1 << 5)
00879 #define SIP_OPT_PREF    (1 << 6)
00880 #define SIP_OPT_PRECONDITION  (1 << 7)
00881 #define SIP_OPT_PRIVACY    (1 << 8)
00882 #define SIP_OPT_SDP_ANAT   (1 << 9)
00883 #define SIP_OPT_SEC_AGREE  (1 << 10)
00884 #define SIP_OPT_EVENTLIST  (1 << 11)
00885 #define SIP_OPT_GRUU    (1 << 12)
00886 #define SIP_OPT_TARGET_DIALOG (1 << 13)
00887 #define SIP_OPT_NOREFERSUB (1 << 14)
00888 #define SIP_OPT_HISTINFO   (1 << 15)
00889 #define SIP_OPT_RESPRIORITY   (1 << 16)
00890 #define SIP_OPT_FROMCHANGE (1 << 17)
00891 #define SIP_OPT_RECLISTINV (1 << 18)
00892 #define SIP_OPT_RECLISTSUB (1 << 19)
00893 #define SIP_OPT_OUTBOUND   (1 << 20)
00894 #define SIP_OPT_UNKNOWN    (1 << 21)
00895 
00896 
00897 /*! \brief List of well-known SIP options. If we get this in a require,
00898    we should check the list and answer accordingly. */
00899 static const struct cfsip_options {
00900    int id;        /*!< Bitmap ID */
00901    int supported;    /*!< Supported by Asterisk ? */
00902    char * const text;   /*!< Text id, as in standard */
00903 } sip_options[] = {  /* XXX used in 3 places */
00904    /* RFC3262: PRACK 100% reliability */
00905    { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" }, 
00906    /* RFC3959: SIP Early session support */
00907    { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED,   "early-session" },
00908    /* SIMPLE events:  RFC4662 */
00909    { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
00910    /* RFC 4916- Connected line ID updates */
00911    { SIP_OPT_FROMCHANGE,   NOT_SUPPORTED, "from-change" },
00912    /* GRUU: Globally Routable User Agent URI's */
00913    { SIP_OPT_GRUU,      NOT_SUPPORTED, "gruu" },
00914    /* RFC4244 History info */
00915    { SIP_OPT_HISTINFO,  NOT_SUPPORTED, "histinfo" },
00916    /* RFC3911: SIP Join header support */
00917    { SIP_OPT_JOIN,      NOT_SUPPORTED, "join" },
00918    /* Disable the REFER subscription, RFC 4488 */
00919    { SIP_OPT_NOREFERSUB,   NOT_SUPPORTED, "norefersub" },
00920    /* SIP outbound - the final NAT battle - draft-sip-outbound */
00921    { SIP_OPT_OUTBOUND,  NOT_SUPPORTED, "outbound" },
00922    /* RFC3327: Path support */
00923    { SIP_OPT_PATH,      NOT_SUPPORTED, "path" },
00924    /* RFC3840: Callee preferences */
00925    { SIP_OPT_PREF,      NOT_SUPPORTED, "pref" },
00926    /* RFC3312: Precondition support */
00927    { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
00928    /* RFC3323: Privacy with proxies*/
00929    { SIP_OPT_PRIVACY,   NOT_SUPPORTED, "privacy" },
00930    /* RFC-ietf-sip-uri-list-conferencing-02.txt conference invite lists */
00931    { SIP_OPT_RECLISTINV,   NOT_SUPPORTED, "recipient-list-invite" },
00932    /* RFC-ietf-sip-uri-list-subscribe-02.txt - subscription lists */
00933    { SIP_OPT_RECLISTSUB,   NOT_SUPPORTED, "recipient-list-subscribe" },
00934    /* RFC3891: Replaces: header for transfer */
00935    { SIP_OPT_REPLACES,  SUPPORTED,  "replaces" },  
00936    /* One version of Polycom firmware has the wrong label */
00937    { SIP_OPT_REPLACES,  SUPPORTED,  "replace" },   
00938    /* RFC4412 Resource priorities */
00939    { SIP_OPT_RESPRIORITY,  NOT_SUPPORTED, "resource-priority" },
00940    /* RFC3329: Security agreement mechanism */
00941    { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
00942    /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
00943    { SIP_OPT_SDP_ANAT,  NOT_SUPPORTED, "sdp-anat" },
00944    /* RFC4028: SIP Session-Timers */
00945    { SIP_OPT_TIMER,  SUPPORTED,  "timer" },
00946    /* RFC4538: Target-dialog */
00947    { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "tdialog" },
00948 };
00949 
00950 
00951 /*! \brief SIP Methods we support 
00952    \todo This string should be set dynamically. We only support REFER and SUBSCRIBE if we have
00953    allowsubscribe and allowrefer on in sip.conf.
00954 */
00955 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY, INFO"
00956 
00957 /*! \brief Standard SIP unsecure port for UDP and TCP from RFC 3261. DO NOT CHANGE THIS */
00958 #define STANDARD_SIP_PORT  5060
00959 /*! \brief Standard SIP TLS port from RFC 3261. DO NOT CHANGE THIS */
00960 #define STANDARD_TLS_PORT  5061
00961 
00962 /*! \note in many SIP headers, absence of a port number implies port 5060,
00963  * and this is why we cannot change the above constant.
00964  * There is a limited number of places in asterisk where we could,
00965  * in principle, use a different "default" port number, but
00966  * we do not support this feature at the moment.
00967  * You can run Asterisk with SIP on a different port with a configuration
00968  * option. If you change this value, the signalling will be incorrect.
00969  */
00970 
00971 /*! \name DefaultValues Default values, set and reset in reload_config before reading configuration 
00972 
00973    These are default values in the source. There are other recommended values in the
00974    sip.conf.sample for new installations. These may differ to keep backwards compatibility,
00975    yet encouraging new behaviour on new installations 
00976  */
00977 /*@{*/ 
00978 #define DEFAULT_CONTEXT    "default"   /*!< The default context for [general] section as well as devices */
00979 #define DEFAULT_MOHINTERPRET    "default" /*!< The default music class */
00980 #define DEFAULT_MOHSUGGEST      ""
00981 #define DEFAULT_VMEXTEN    "asterisk"  /*!< Default voicemail extension */
00982 #define DEFAULT_CALLERID   "asterisk"  /*!< Default caller ID */
00983 #define DEFAULT_NOTIFYMIME    "application/simple-message-summary"
00984 #define DEFAULT_ALLOWGUEST TRUE
00985 #define DEFAULT_RTPKEEPALIVE  0     /*!< Default RTPkeepalive setting */
00986 #define DEFAULT_CALLCOUNTER   FALSE
00987 #define DEFAULT_SRVLOOKUP  TRUE     /*!< Recommended setting is ON */
00988 #define DEFAULT_COMPACTHEADERS   FALSE    /*!< Send compact (one-character) SIP headers. Default off */
00989 #define DEFAULT_TOS_SIP         0               /*!< Call signalling packets should be marked as DSCP CS3, but the default is 0 to be compatible with previous versions. */
00990 #define DEFAULT_TOS_AUDIO       0               /*!< Audio packets should be marked as DSCP EF (Expedited Forwarding), but the default is 0 to be compatible with previous versions. */
00991 #define DEFAULT_TOS_VIDEO       0               /*!< Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions. */
00992 #define DEFAULT_TOS_TEXT        0               /*!< Text packets should be marked as XXXX XXXX, but the default is 0 to be compatible with previous versions. */
00993 #define DEFAULT_COS_SIP         4      /*!< Level 2 class of service for SIP signalling */
00994 #define DEFAULT_COS_AUDIO       5      /*!< Level 2 class of service for audio media  */
00995 #define DEFAULT_COS_VIDEO       6      /*!< Level 2 class of service for video media */
00996 #define DEFAULT_COS_TEXT        5      /*!< Level 2 class of service for text media (T.140) */
00997 #define DEFAULT_ALLOW_EXT_DOM TRUE     /*!< Allow external domains */
00998 #define DEFAULT_REALM      "asterisk"  /*!< Realm for HTTP digest authentication */
00999 #define DEFAULT_NOTIFYRINGING TRUE     /*!< Notify devicestate system on ringing state */
01000 #define DEFAULT_NOTIFYCID     DISABLED /*!< Include CID with ringing notifications */
01001 #define DEFAULT_PEDANTIC   FALSE    /*!< Avoid following SIP standards for dialog matching */
01002 #define DEFAULT_AUTOCREATEPEER   FALSE    /*!< Don't create peers automagically */
01003 #define  DEFAULT_MATCHEXTERNIPLOCALLY FALSE  /*!< Match extern IP locally default setting */
01004 #define DEFAULT_QUALIFY    FALSE    /*!< Don't monitor devices */
01005 #define DEFAULT_CALLEVENTS FALSE    /*!< Extra manager SIP call events */
01006 #define DEFAULT_ALWAYSAUTHREJECT FALSE /*!< Don't reject authentication requests always */
01007 #define DEFAULT_REGEXTENONQUALIFY FALSE
01008 #define DEFAULT_T1MIN      100      /*!< 100 MS for minimal roundtrip time */
01009 #define DEFAULT_MAX_CALL_BITRATE (384)    /*!< Max bitrate for video */
01010 #ifndef DEFAULT_USERAGENT
01011 #define DEFAULT_USERAGENT "Asterisk PBX"  /*!< Default Useragent: header unless re-defined in sip.conf */
01012 #define DEFAULT_SDPSESSION "Asterisk PBX" /*!< Default SDP session name, (s=) header unless re-defined in sip.conf */
01013 #define DEFAULT_SDPOWNER "root"        /*!< Default SDP username field in (o=) header unless re-defined in sip.conf */
01014 #endif
01015 /*@}*/ 
01016 
01017 /*! \name DefaultSettings
01018    Default setttings are used as a channel setting and as a default when
01019    configuring devices 
01020 */
01021 /*@{*/ 
01022 static char default_language[MAX_LANGUAGE];
01023 static char default_callerid[AST_MAX_EXTENSION];
01024 static char default_fromdomain[AST_MAX_EXTENSION];
01025 static char default_notifymime[AST_MAX_EXTENSION];
01026 static int default_qualify;      /*!< Default Qualify= setting */
01027 static char default_vmexten[AST_MAX_EXTENSION];
01028 static char default_mohinterpret[MAX_MUSICCLASS];  /*!< Global setting for moh class to use when put on hold */
01029 static char default_mohsuggest[MAX_MUSICCLASS];    /*!< Global setting for moh class to suggest when putting 
01030                                                     *   a bridged channel on hold */
01031 static char default_parkinglot[AST_MAX_CONTEXT]; /*!< Parkinglot */
01032 static int default_maxcallbitrate;  /*!< Maximum bitrate for call */
01033 static struct ast_codec_pref default_prefs;     /*!< Default codec prefs */
01034 static unsigned int default_transports;         /*!< Default Transports (enum sip_transport) that are acceptable */
01035 static unsigned int default_primary_transport;     /*!< Default primary Transport (enum sip_transport) for outbound connections to devices */
01036 
01037 /*@}*/ 
01038 
01039 /*! \name GlobalSettings
01040    Global settings apply to the channel (often settings you can change in the general section
01041    of sip.conf
01042 */
01043 /*@{*/ 
01044 /*! \brief a place to store all global settings for the sip channel driver 
01045    These are settings that will be possibly to apply on a group level later on.
01046    \note Do not add settings that only apply to the channel itself and can't
01047          be applied to devices (trunks, services, phones)
01048 */
01049 struct sip_settings {
01050    int peer_rtupdate;      /*!< G: Update database with registration data for peer? */
01051    int rtsave_sysname;     /*!< G: Save system name at registration? */
01052    int ignore_regexpire;      /*!< G: Ignore expiration of peer  */
01053    int rtautoclear;     /*!< Realtime ?? */
01054    int directrtpsetup;     /*!< Enable support for Direct RTP setup (no re-invites) */
01055    int pedanticsipchecking;   /*!< Extra checking ?  Default off */
01056    int autocreatepeer;     /*!< Auto creation of peers at registration? Default off. */
01057    int srvlookup;       /*!< SRV Lookup on or off. Default is on */
01058    int allowguest;         /*!< allow unauthenticated peers to connect? */
01059    int alwaysauthreject;      /*!< Send 401 Unauthorized for all failing requests */
01060    int compactheaders;     /*!< send compact sip headers */
01061    int allow_external_domains;   /*!< Accept calls to external SIP domains? */
01062    int callevents;         /*!< Whether we send manager events or not */
01063    int regextenonqualify;     /*!< Whether to add/remove regexten when qualifying peers */
01064    int matchexterniplocally;  /*!< Match externip/externhost setting against localnet setting */
01065    int notifyringing;      /*!< Send notifications on ringing */
01066    int notifyhold;         /*!< Send notifications on hold */
01067    enum notifycid_setting notifycid; /*!< Send CID with ringing notifications */
01068    enum transfermodes allowtransfer;   /*!< SIP Refer restriction scheme */
01069    int allowsubscribe;          /*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE 
01070                    the global setting is in globals_flags[1] */
01071    char realm[MAXHOSTNAMELEN];      /*!< Default realm */
01072    struct sip_proxy outboundproxy;  /*!< Outbound proxy */
01073    char default_context[AST_MAX_CONTEXT];
01074    char default_subscribecontext[AST_MAX_CONTEXT];
01075 };
01076 
01077 static struct sip_settings sip_cfg;
01078 
01079 static int global_match_auth_username;    /*!< Match auth username if available instead of From: Default off. */
01080 
01081 static int global_relaxdtmf;     /*!< Relax DTMF */
01082 static int global_prematuremediafilter;   /*!< Enable/disable premature frames in a call (causing 183 early media) */
01083 static int global_relaxdtmf;        /*!< Relax DTMF */
01084 static int global_rtptimeout;    /*!< Time out call if no RTP */
01085 static int global_rtpholdtimeout;   /*!< Time out call if no RTP during hold */
01086 static int global_rtpkeepalive;     /*!< Send RTP keepalives */
01087 static int global_reg_timeout;
01088 static int global_regattempts_max;  /*!< Registration attempts before giving up */
01089 static int global_shrinkcallerid;   /*!< enable or disable shrinking of caller id  */
01090 static int global_callcounter;      /*!< Enable call counters for all devices. This is currently enabled by setting the peer
01091                   call-limit to INT_MAX. When we remove the call-limit from the code, we can make it
01092                   with just a boolean flag in the device structure */
01093 static unsigned int global_tos_sip;    /*!< IP type of service for SIP packets */
01094 static unsigned int global_tos_audio;     /*!< IP type of service for audio RTP packets */
01095 static unsigned int global_tos_video;     /*!< IP type of service for video RTP packets */
01096 static unsigned int global_tos_text;      /*!< IP type of service for text RTP packets */
01097 static unsigned int global_cos_sip;    /*!< 802.1p class of service for SIP packets */
01098 static unsigned int global_cos_audio;     /*!< 802.1p class of service for audio RTP packets */
01099 static unsigned int global_cos_video;     /*!< 802.1p class of service for video RTP packets */
01100 static unsigned int global_cos_text;      /*!< 802.1p class of service for text RTP packets */
01101 static int recordhistory;     /*!< Record SIP history. Off by default */
01102 static int dumphistory;       /*!< Dump history to verbose before destroying SIP dialog */
01103 static char global_regcontext[AST_MAX_CONTEXT];    /*!< Context for auto-extensions */
01104 static char global_useragent[AST_MAX_EXTENSION];   /*!< Useragent for the SIP channel */
01105 static char global_sdpsession[AST_MAX_EXTENSION];  /*!< SDP session name for the SIP channel */
01106 static char global_sdpowner[AST_MAX_EXTENSION]; /*!< SDP owner name for the SIP channel */
01107 static int global_authfailureevents;      /*!< Whether we send authentication failure manager events or not. Default no. */
01108 static int global_t1;         /*!< T1 time */
01109 static int global_t1min;      /*!< T1 roundtrip time minimum */
01110 static int global_timer_b;             /*!< Timer B - RFC 3261 Section 17.1.1.2 */
01111 static int global_autoframing;            /*!< Turn autoframing on or off. */
01112 static int global_qualifyfreq;         /*!< Qualify frequency */
01113 static int global_qualify_gap;              /*!< Time between our group of peer pokes */
01114 static int global_qualify_peers;          /*!< Number of peers to poke at a given time */
01115 
01116 
01117 /*! \brief Codecs that we support by default: */
01118 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
01119 
01120 static enum st_mode global_st_mode;           /*!< Mode of operation for Session-Timers           */
01121 static enum st_refresher global_st_refresher; /*!< Session-Timer refresher                        */
01122 static int global_min_se;                     /*!< Lowest threshold for session refresh interval  */
01123 static int global_max_se;                     /*!< Highest threshold for session refresh interval */
01124 
01125 static int global_dynamic_exclude_static = 0;   /*!< Exclude static peers from contact registrations */
01126 /*@}*/
01127 
01128 /*! \brief Global list of addresses dynamic peers are not allowed to use */
01129 static struct ast_ha *global_contact_ha = NULL;
01130 
01131 /*! \name Object counters @{
01132  * \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
01133  * should be used to modify these values. */
01134 static int speerobjs = 0;                /*!< Static peers */
01135 static int rpeerobjs = 0;                /*!< Realtime peers */
01136 static int apeerobjs = 0;                /*!< Autocreated peer objects */
01137 static int regobjs = 0;                  /*!< Registry objects */
01138 /* }@ */
01139 
01140 static struct ast_flags global_flags[2] = {{0}};        /*!< global SIP_ flags */
01141 static int global_t38_maxdatagram;        /*!< global T.38 FaxMaxDatagram override */
01142 
01143 static char used_context[AST_MAX_CONTEXT];      /*!< name of automatically created context for unloading */
01144 
01145 
01146 AST_MUTEX_DEFINE_STATIC(netlock);
01147 
01148 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
01149    when it's doing something critical. */
01150 AST_MUTEX_DEFINE_STATIC(monlock);
01151 
01152 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
01153 
01154 /*! \brief This is the thread for the monitor which checks for input on the channels
01155    which are not currently in use.  */
01156 static pthread_t monitor_thread = AST_PTHREADT_NULL;
01157 
01158 static int sip_reloading = FALSE;                       /*!< Flag for avoiding multiple reloads at the same time */
01159 static enum channelreloadreason sip_reloadreason;       /*!< Reason for last reload/load of configuration */
01160 
01161 static struct sched_context *sched;     /*!< The scheduling context */
01162 static struct io_context *io;           /*!< The IO context */
01163 static int *sipsock_read_id;            /*!< ID of IO entry for sipsock FD */
01164 
01165 #define DEC_CALL_LIMIT  0
01166 #define INC_CALL_LIMIT  1
01167 #define DEC_CALL_RINGING 2
01168 #define INC_CALL_RINGING 3
01169 
01170 /*! \brief The SIP socket definition */
01171 struct sip_socket {
01172    enum sip_transport type;   /*!< UDP, TCP or TLS */
01173    int fd;           /*!< Filed descriptor, the actual socket */
01174    uint16_t port;
01175    struct ast_tcptls_session_instance *tcptls_session;   /* If tcp or tls, a socket manager */
01176 };
01177 
01178 /*! \brief sip_request: The data grabbed from the UDP socket
01179  *
01180  * \verbatim
01181  * Incoming messages: we first store the data from the socket in data[],
01182  * adding a trailing \0 to make string parsing routines happy.
01183  * Then call parse_request() and req.method = find_sip_method();
01184  * to initialize the other fields. The \r\n at the end of each line is   
01185  * replaced by \0, so that data[] is not a conforming SIP message anymore.
01186  * After this processing, rlPart1 is set to non-NULL to remember
01187  * that we can run get_header() on this kind of packet.
01188  *
01189  * parse_request() splits the first line as follows:
01190  * Requests have in the first line      method uri SIP/2.0
01191  *      rlPart1 = method; rlPart2 = uri;
01192  * Responses have in the first line     SIP/2.0 NNN description
01193  *      rlPart1 = SIP/2.0; rlPart2 = NNN + description;
01194  *
01195  * For outgoing packets, we initialize the fields with init_req() or init_resp()
01196  * (which fills the first line to "METHOD uri SIP/2.0" or "SIP/2.0 code text"),
01197  * and then fill the rest with add_header() and add_content().
01198  * The \r\n at the end of the line are still there, so the get_header()
01199  * and similar functions don't work on these packets. 
01200  * \endverbatim
01201  */
01202 struct sip_request {
01203    ptrdiff_t rlPart1;           /*!< Offset of the SIP Method Name or "SIP/2.0" protocol version */
01204    ptrdiff_t rlPart2;           /*!< Offset of the Request URI or Response Status */
01205    int len;                /*!< bytes used in data[], excluding trailing null terminator. Rarely used. */
01206    int headers;            /*!< # of SIP Headers */
01207    int method;             /*!< Method of this request */
01208    int lines;              /*!< Body Content */
01209    unsigned int sdp_start; /*!< the line number where the SDP begins */
01210    unsigned int sdp_count; /*!< the number of lines of SDP */
01211    char debug;    /*!< print extra debugging if non zero */
01212    char has_to_tag;  /*!< non-zero if packet has To: tag */
01213    char ignore;      /*!< if non-zero This is a re-transmit, ignore it */
01214    char authenticated;     /*!< non-zero if this request was authenticated */
01215    /* Array of offsets into the request string of each SIP header*/
01216    ptrdiff_t header[SIP_MAX_HEADERS];
01217    /* Array of offsets into the request string of each SDP line*/
01218    ptrdiff_t line[SIP_MAX_LINES];
01219    struct ast_str *data;   
01220    struct ast_str *content;
01221    /* XXX Do we need to unref socket.ser when the request goes away? */
01222    struct sip_socket socket;  /*!< The socket used for this request */
01223    AST_LIST_ENTRY(sip_request) next;
01224 };
01225 
01226 /* \brief given a sip_request and an offset, return the char * that resides there
01227  *
01228  * It used to be that rlPart1, rlPart2, and the header and line arrays were character
01229  * pointers. They are now offsets into the ast_str portion of the sip_request structure.
01230  * To avoid adding a bunch of redundant pointer arithmetic to the code, this macro is
01231  * provided to retrieve the string at a particular offset within the request's buffer
01232  */
01233 #define REQ_OFFSET_TO_STR(req,offset) (ast_str_buffer((req)->data) + ((req)->offset))
01234 
01235 /*! \brief structure used in transfers */
01236 struct sip_dual {
01237    struct ast_channel *chan1; /*!< First channel involved */
01238    struct ast_channel *chan2; /*!< Second channel involved */
01239    struct sip_request req;    /*!< Request that caused the transfer (REFER) */
01240    int seqno;        /*!< Sequence number */
01241 };
01242 
01243 struct sip_pkt;
01244 
01245 /*! \brief Parameters to the transmit_invite function */
01246 struct sip_invite_param {
01247    int addsipheaders;      /*!< Add extra SIP headers */
01248    const char *uri_options;   /*!< URI options to add to the URI */
01249    const char *vxml_url;      /*!< VXML url for Cisco phones */
01250    char *auth;       /*!< Authentication */
01251    char *authheader;    /*!< Auth header */
01252    enum sip_auth_type auth_type; /*!< Authentication type */
01253    const char *replaces;      /*!< Replaces header for call transfers */
01254    int transfer;        /*!< Flag - is this Invite part of a SIP transfer? (invite/replaces) */
01255 };
01256 
01257 /*! \brief Structure to save routing information for a SIP session */
01258 struct sip_route {
01259    struct sip_route *next;
01260    char hop[0];
01261 };
01262 
01263 /*! \brief Structure to store Via information */
01264 struct sip_via {
01265    char *via;
01266    const char *protocol;
01267    const char *sent_by;
01268    const char *branch;
01269    const char *maddr;
01270    unsigned int port;
01271    unsigned char ttl;
01272 };
01273 
01274 /*! \brief Modes for SIP domain handling in the PBX */
01275 enum domain_mode {
01276    SIP_DOMAIN_AUTO,     /*!< This domain is auto-configured */
01277    SIP_DOMAIN_CONFIG,      /*!< This domain is from configuration */
01278 };
01279 
01280 /*! \brief Domain data structure. 
01281    \note In the future, we will connect this to a configuration tree specific
01282    for this domain
01283 */
01284 struct domain {
01285    char domain[MAXHOSTNAMELEN];     /*!< SIP domain we are responsible for */
01286    char context[AST_MAX_EXTENSION]; /*!< Incoming context for this domain */
01287    enum domain_mode mode;        /*!< How did we find this domain? */
01288    AST_LIST_ENTRY(domain) list;     /*!< List mechanics */
01289 };
01290 
01291 static AST_LIST_HEAD_STATIC(domain_list, domain);  /*!< The SIP domain list */
01292 
01293 
01294 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
01295 struct sip_history {
01296    AST_LIST_ENTRY(sip_history) list;
01297    char event[0]; /* actually more, depending on needs */
01298 };
01299 
01300 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
01301 
01302 /*! \brief sip_auth: Credentials for authentication to other SIP services */
01303 struct sip_auth {
01304    char realm[AST_MAX_EXTENSION];  /*!< Realm in which these credentials are valid */
01305    char username[256];             /*!< Username */
01306    char secret[256];               /*!< Secret */
01307    char md5secret[256];            /*!< MD5Secret */
01308    struct sip_auth *next;          /*!< Next auth structure in list */
01309 };
01310 
01311 /*! \name SIPflags
01312    Various flags for the flags field in the pvt structure 
01313    Trying to sort these up (one or more of the following):
01314    D: Dialog
01315    P: Peer/user
01316    G: Global flag
01317    When flags are used by multiple structures, it is important that
01318    they have a common layout so it is easy to copy them.
01319 */
01320 /*@{*/ 
01321 #define SIP_OUTGOING    (1 << 0) /*!< D: Direction of the last transaction in this dialog */
01322 #define SIP_RINGING     (1 << 2) /*!< D: Have sent 180 ringing */
01323 #define SIP_PROGRESS_SENT  (1 << 3) /*!< D: Have sent 183 message progress */
01324 #define SIP_NEEDREINVITE   (1 << 4) /*!< D: Do we need to send another reinvite? */
01325 #define SIP_PENDINGBYE     (1 << 5) /*!< D: Need to send bye after we ack? */
01326 #define SIP_GOTREFER    (1 << 6) /*!< D: Got a refer? */
01327 #define SIP_CALL_LIMIT     (1 << 7) /*!< D: Call limit enforced for this call */
01328 #define SIP_INC_COUNT      (1 << 8) /*!< D: Did this dialog increment the counter of in-use calls? */
01329 #define SIP_INC_RINGING    (1 << 9) /*!< D: Did this connection increment the counter of in-use calls? */
01330 #define SIP_DEFER_BYE_ON_TRANSFER   (1 << 10)   /*!< D: Do not hangup at first ast_hangup */
01331 
01332 #define SIP_PROMISCREDIR   (1 << 11)   /*!< DP: Promiscuous redirection */
01333 #define SIP_TRUSTRPID      (1 << 12)   /*!< DP: Trust RPID headers? */
01334 #define SIP_USEREQPHONE    (1 << 13)   /*!< DP: Add user=phone to numeric URI. Default off */
01335 #define SIP_USECLIENTCODE  (1 << 14)   /*!< DP: Trust X-ClientCode info message */
01336 
01337 /* DTMF flags - see str2dtmfmode() and dtmfmode2str() */
01338 #define SIP_DTMF     (7 << 15)   /*!< DP: DTMF Support: five settings, uses three bits */
01339 #define SIP_DTMF_RFC2833   (0 << 15)   /*!< DP: DTMF Support: RTP DTMF - "rfc2833" */
01340 #define SIP_DTMF_INBAND    (1 << 15)   /*!< DP: DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
01341 #define SIP_DTMF_INFO      (2 << 15)   /*!< DP: DTMF Support: SIP Info messages - "info" */
01342 #define SIP_DTMF_AUTO      (3 << 15)   /*!< DP: DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
01343 #define SIP_DTMF_SHORTINFO      (4 << 15)       /*!< DP: DTMF Support: SIP Info messages - "info" - short variant */
01344 
01345 /* NAT settings - see nat2str() */
01346 #define SIP_NAT         (3 << 18)   /*!< DP: four settings, uses two bits */
01347 #define SIP_NAT_NEVER      (0 << 18)   /*!< DP: No nat support */
01348 #define SIP_NAT_RFC3581    (1 << 18)   /*!< DP: NAT RFC3581 */
01349 #define SIP_NAT_ROUTE      (2 << 18)   /*!< DP: NAT Only ROUTE */
01350 #define SIP_NAT_ALWAYS     (3 << 18)   /*!< DP: NAT Both ROUTE and RFC3581 */
01351 
01352 /* re-INVITE related settings */
01353 #define SIP_REINVITE    (7 << 20)   /*!< DP: four settings, uses three bits */
01354 #define SIP_REINVITE_NONE  (0 << 20)   /*!< DP: no reinvite allowed */
01355 #define SIP_DIRECT_MEDIA   (1 << 20)   /*!< DP: allow peers to be reinvited to send media directly p2p */
01356 #define SIP_DIRECT_MEDIA_NAT  (2 << 20)   /*!< DP: allow media reinvite when new peer is behind NAT */
01357 #define SIP_REINVITE_UPDATE   (4 << 20)   /*!< DP: use UPDATE (RFC3311) when reinviting this peer */
01358 
01359 /* "insecure" settings - see insecure2str() */
01360 #define SIP_INSECURE    (3 << 23)   /*!< DP: three settings, uses two bits */
01361 #define SIP_INSECURE_NONE  (0 << 23)   /*!< DP: secure mode */
01362 #define SIP_INSECURE_PORT  (1 << 23)   /*!< DP: don't require matching port for incoming requests */
01363 #define SIP_INSECURE_INVITE   (1 << 24)   /*!< DP: don't require authentication for incoming INVITEs */
01364 
01365 /* Sending PROGRESS in-band settings */
01366 #define SIP_PROG_INBAND    (3 << 25)   /*!< DP: three settings, uses two bits */
01367 #define SIP_PROG_INBAND_NEVER (0 << 25)
01368 #define SIP_PROG_INBAND_NO (1 << 25)
01369 #define SIP_PROG_INBAND_YES   (2 << 25)
01370 
01371 #define SIP_SENDRPID    (1 << 29)   /*!< DP: Remote Party-ID Support */
01372 #define SIP_G726_NONSTANDARD  (1 << 31)   /*!< DP: Use non-standard packing for G726-32 data */
01373 
01374 /*! \brief Flags to copy from peer/user to dialog */
01375 #define SIP_FLAGS_TO_COPY \
01376    (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
01377     SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
01378     SIP_USEREQPHONE | SIP_INSECURE)
01379 /*@}*/ 
01380 
01381 /*! \name SIPflags2
01382    a second page of flags (for flags[1] */
01383 /*@{*/ 
01384 /* realtime flags */
01385 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0) /*!< GP: Should we keep RT objects in memory for extended time? */
01386 #define SIP_PAGE2_RTAUTOCLEAR    (1 << 2) /*!< GP: Should we clean memory from peers after expiry? */
01387 #define SIP_PAGE2_HAVEPEERCONTEXT   (1 << 3) /*< Are we associated with a configured peer context? */
01388 /* Space for addition of other realtime flags in the future */
01389 #define SIP_PAGE2_FORWARD_LOOP_DETECTED (1 << 8)/*!< 31: Do call forward when receiving 482 Loop Detected */
01390 #define SIP_PAGE2_STATECHANGEQUEUE  (1 << 9) /*!< D: Unsent state pending change exists */
01391 
01392 #define SIP_PAGE2_RPORT_PRESENT         (1 << 10)       /*!< Was rport received in the Via header? */
01393 #define SIP_PAGE2_VIDEOSUPPORT      (1 << 14)   /*!< DP: Video supported if offered? */
01394 #define SIP_PAGE2_TEXTSUPPORT    (1 << 15)   /*!< GDP: Global text enable */
01395 #define SIP_PAGE2_ALLOWSUBSCRIBE (1 << 16)   /*!< GP: Allow subscriptions from this peer? */
01396 #define SIP_PAGE2_ALLOWOVERLAP      (1 << 17)   /*!< DP: Allow overlap dialing ? */
01397 #define SIP_PAGE2_SUBSCRIBEMWIONLY  (1 << 18)   /*!< GP: Only issue MWI notification if subscribed to */
01398 #define SIP_PAGE2_IGNORESDPVERSION  (1 << 19)   /*!< GDP: Ignore the SDP session version number we receive and treat all sessions as new */
01399 
01400 #define SIP_PAGE2_T38SUPPORT             (3 << 20) /*!< GDP: T.38 Fax Support */
01401 #define SIP_PAGE2_T38SUPPORT_UDPTL          (1 << 20) /*!< GDP: T.38 Fax Support (no error correction) */
01402 #define SIP_PAGE2_T38SUPPORT_UDPTL_FEC         (2 << 20) /*!< GDP: T.38 Fax Support (FEC error correction) */
01403 #define SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY   (3 << 20)   /*!< GDP: T.38 Fax Support (redundancy error correction) */
01404 
01405 #define SIP_PAGE2_CALL_ONHOLD    (3 << 23)   /*!< D: Call hold states: */
01406 #define SIP_PAGE2_CALL_ONHOLD_ACTIVE    (1 << 23)       /*!< D: Active hold */
01407 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR   (2 << 23)   /*!< D: One directional hold */
01408 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE (3 << 23)   /*!< D: Inactive hold */
01409 
01410 #define SIP_PAGE2_RFC2833_COMPENSATE    (1 << 25)  /*!< DP: Compensate for buggy RFC2833 implementations */
01411 #define SIP_PAGE2_BUGGY_MWI      (1 << 26)   /*!< DP: Buggy CISCO MWI fix */
01412 #define SIP_PAGE2_DIALOG_ESTABLISHED    (1 << 27)       /*!< 29: Has a dialog been established? */
01413 #define SIP_PAGE2_FAX_DETECT     (3 << 28)   /*!< DP: Fax Detection support */
01414 #define SIP_PAGE2_FAX_DETECT_CNG (1 << 28)   /*!< DP: Fax Detection support - detect CNG in audio */
01415 #define SIP_PAGE2_FAX_DETECT_T38 (2 << 28)   /*!< DP: Fax Detection support - detect T.38 reinvite from peer */
01416 #define SIP_PAGE2_FAX_DETECT_BOTH   (3 << 28)   /*!< DP: Fax Detection support - detect both */
01417 #define SIP_PAGE2_REGISTERTRYING        (1 << 29)       /*!< DP: Send 100 Trying on REGISTER attempts */
01418 #define SIP_PAGE2_UDPTL_DESTINATION     (1 << 30)       /*!< DP: Use source IP of RTP as destination if NAT is enabled */
01419 #define SIP_PAGE2_VIDEOSUPPORT_ALWAYS  (1 << 31)       /*!< DP: Always set up video, even if endpoints don't support it */
01420 
01421 #define SIP_PAGE2_FLAGS_TO_COPY \
01422    (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_IGNORESDPVERSION | \
01423    SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | \
01424    SIP_PAGE2_BUGGY_MWI | SIP_PAGE2_TEXTSUPPORT | SIP_PAGE2_FAX_DETECT | \
01425    SIP_PAGE2_UDPTL_DESTINATION | SIP_PAGE2_VIDEOSUPPORT_ALWAYS | \
01426    SIP_PAGE2_HAVEPEERCONTEXT | SIP_PAGE2_FORWARD_LOOP_DETECTED)
01427 
01428 /*@}*/ 
01429 
01430 /*! \brief debugging state
01431  * We store separately the debugging requests from the config file
01432  * and requests from the CLI. Debugging is enabled if either is set
01433  * (which means that if sipdebug is set in the config file, we can
01434  * only turn it off by reloading the config).
01435  */
01436 enum sip_debug_e {
01437    sip_debug_none = 0,
01438    sip_debug_config = 1,
01439    sip_debug_console = 2,
01440 };
01441 
01442 static enum sip_debug_e sipdebug;
01443 
01444 /*! \brief extra debugging for 'text' related events.
01445  * At the moment this is set together with sip_debug_console.
01446  * \note It should either go away or be implemented properly.
01447  */
01448 static int sipdebug_text;
01449 
01450 /*! \brief T38 States for a call */
01451 enum t38state {
01452    T38_DISABLED = 0,                /*!< Not enabled */
01453    T38_LOCAL_REINVITE,              /*!< Offered from local - REINVITE */
01454    T38_PEER_REINVITE,               /*!< Offered from peer - REINVITE */
01455    T38_ENABLED                      /*!< Negotiated (enabled) */
01456 };
01457 
01458 /*! \brief T.38 channel settings (at some point we need to make this alloc'ed */
01459 struct t38properties {
01460    enum t38state state;    /*!< T.38 state */
01461    struct ast_control_t38_parameters our_parms;
01462    struct ast_control_t38_parameters their_parms;
01463 };
01464 
01465 /*! \brief Parameters to know status of transfer */
01466 enum referstatus {
01467    REFER_IDLE,                    /*!< No REFER is in progress */
01468    REFER_SENT,                    /*!< Sent REFER to transferee */
01469    REFER_RECEIVED,                /*!< Received REFER from transferrer */
01470    REFER_CONFIRMED,               /*!< Refer confirmed with a 100 TRYING (unused) */
01471    REFER_ACCEPTED,                /*!< Accepted by transferee */
01472    REFER_RINGING,                 /*!< Target Ringing */
01473    REFER_200OK,                   /*!< Answered by transfer target */
01474    REFER_FAILED,                  /*!< REFER declined - go on */
01475    REFER_NOAUTH                   /*!< We had no auth for REFER */
01476 };
01477 
01478 /*! \brief generic struct to map between strings and integers.
01479  * Fill it with x-s pairs, terminate with an entry with s = NULL;
01480  * Then you can call map_x_s(...) to map an integer to a string,
01481  * and map_s_x() for the string -> integer mapping.
01482  */
01483 struct _map_x_s {
01484    int x;
01485    const char *s;
01486 };              
01487 
01488 static const struct _map_x_s referstatusstrings[] = {
01489    { REFER_IDLE,     "<none>" },
01490    { REFER_SENT,     "Request sent" },
01491    { REFER_RECEIVED, "Request received" },
01492    { REFER_CONFIRMED,   "Confirmed" },
01493    { REFER_ACCEPTED, "Accepted" },
01494    { REFER_RINGING,  "Target ringing" },
01495    { REFER_200OK,    "Done" },
01496    { REFER_FAILED,      "Failed" },
01497    { REFER_NOAUTH,      "Failed - auth failure" },
01498    { -1,       NULL} /* terminator */
01499 };
01500 
01501 /*! \brief Structure to handle SIP transfers. Dynamically allocated when needed
01502    \note OEJ: Should be moved to string fields */
01503 struct sip_refer {
01504    char refer_to[AST_MAX_EXTENSION];      /*!< Place to store REFER-TO extension */
01505    char refer_to_domain[AST_MAX_EXTENSION];  /*!< Place to store REFER-TO domain */
01506    char refer_to_urioption[AST_MAX_EXTENSION];  /*!< Place to store REFER-TO uri options */
01507    char refer_to_context[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO context */
01508    char referred_by[AST_MAX_EXTENSION];      /*!< Place to store REFERRED-BY extension */
01509    char referred_by_name[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
01510    char refer_contact[AST_MAX_EXTENSION];    /*!< Place to store Contact info from a REFER extension */
01511    char replaces_callid[SIPBUFSIZE];         /*!< Replace info: callid */
01512    char replaces_callid_totag[SIPBUFSIZE/2];    /*!< Replace info: to-tag */
01513    char replaces_callid_fromtag[SIPBUFSIZE/2];     /*!< Replace info: from-tag */
01514    struct sip_pvt *refer_call;         /*!< Call we are referring. This is just a reference to a
01515                       * dialog owned by someone else, so we should not destroy
01516                       * it when the sip_refer object goes.
01517                       */
01518    int attendedtransfer;            /*!< Attended or blind transfer? */
01519    int localtransfer;            /*!< Transfer to local domain? */
01520    enum referstatus status;         /*!< REFER status */
01521 };
01522 
01523 
01524 /*! \brief Structure that encapsulates all attributes related to running 
01525  *   SIP Session-Timers feature on a per dialog basis.
01526  */
01527 struct sip_st_dlg {
01528    int st_active;                          /*!< Session-Timers on/off */ 
01529    int st_interval;                        /*!< Session-Timers negotiated session refresh interval */
01530    int st_schedid;                         /*!< Session-Timers ast_sched scheduler id */
01531    enum st_refresher st_ref;               /*!< Session-Timers session refresher */
01532    int st_expirys;                         /*!< Session-Timers number of expirys */
01533    int st_active_peer_ua;                  /*!< Session-Timers on/off in peer UA */
01534    int st_cached_min_se;                   /*!< Session-Timers cached Min-SE */
01535    int st_cached_max_se;                   /*!< Session-Timers cached Session-Expires */
01536    enum st_mode st_cached_mode;            /*!< Session-Timers cached M.O. */
01537    enum st_refresher st_cached_ref;        /*!< Session-Timers cached refresher */
01538    unsigned char quit_flag:1;              /*!< Stop trying to lock; just quit */
01539 };
01540 
01541 
01542 /*! \brief Structure that encapsulates all attributes related to configuration 
01543  *   of SIP Session-Timers feature on a per user/peer basis.
01544  */
01545 struct sip_st_cfg {
01546    enum st_mode st_mode_oper;      /*!< Mode of operation for Session-Timers           */
01547    enum st_refresher st_ref;       /*!< Session-Timer refresher                        */
01548    int st_min_se;                  /*!< Lowest threshold for session refresh interval  */
01549    int st_max_se;                  /*!< Highest threshold for session refresh interval */
01550 };
01551 
01552 struct offered_media {
01553    int offered;
01554    char text[128];
01555 };
01556 
01557 /*! \brief Structure used for each SIP dialog, ie. a call, a registration, a subscribe.
01558  * Created and initialized by sip_alloc(), the descriptor goes into the list of
01559  * descriptors (dialoglist).
01560  */
01561 struct sip_pvt {
01562    struct sip_pvt *next;         /*!< Next dialog in chain */
01563    enum invitestates invitestate;      /*!< Track state of SIP_INVITEs */
01564    int method;          /*!< SIP method that opened this dialog */
01565    AST_DECLARE_STRING_FIELDS(
01566       AST_STRING_FIELD(callid);  /*!< Global CallID */
01567       AST_STRING_FIELD(randdata);   /*!< Random data */
01568       AST_STRING_FIELD(accountcode);   /*!< Account code */
01569       AST_STRING_FIELD(realm);   /*!< Authorization realm */
01570       AST_STRING_FIELD(nonce);   /*!< Authorization nonce */
01571       AST_STRING_FIELD(opaque);  /*!< Opaque nonsense */
01572       AST_STRING_FIELD(qop);     /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
01573       AST_STRING_FIELD(domain);  /*!< Authorization domain */
01574       AST_STRING_FIELD(from);    /*!< The From: header */
01575       AST_STRING_FIELD(useragent);  /*!< User agent in SIP request */
01576       AST_STRING_FIELD(exten);   /*!< Extension where to start */
01577       AST_STRING_FIELD(context); /*!< Context for this call */
01578       AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
01579       AST_STRING_FIELD(subscribeuri); /*!< Subscribecontext */
01580       AST_STRING_FIELD(fromdomain); /*!< Domain to show in the from field */
01581       AST_STRING_FIELD(fromuser);   /*!< User to show in the user field */
01582       AST_STRING_FIELD(fromname);   /*!< Name to show in the user field */
01583       AST_STRING_FIELD(tohost);  /*!< Host we should put in the "to" field */
01584       AST_STRING_FIELD(todnid);  /*!< DNID of this call (overrides host) */
01585       AST_STRING_FIELD(language);   /*!< Default language for this call */
01586       AST_STRING_FIELD(mohinterpret);  /*!< MOH class to use when put on hold */
01587       AST_STRING_FIELD(mohsuggest); /*!< MOH class to suggest when putting a peer on hold */
01588       AST_STRING_FIELD(rdnis);   /*!< Referring DNIS */
01589       AST_STRING_FIELD(redircause); /*!< Referring cause */
01590       AST_STRING_FIELD(theirtag);   /*!< Their tag */
01591       AST_STRING_FIELD(username);   /*!< [user] name */
01592       AST_STRING_FIELD(peername);   /*!< [peer] name, not set if [user] */
01593       AST_STRING_FIELD(authname);   /*!< Who we use for authentication */
01594       AST_STRING_FIELD(uri);     /*!< Original requested URI */
01595       AST_STRING_FIELD(okcontacturi);  /*!< URI from the 200 OK on INVITE */
01596       AST_STRING_FIELD(peersecret); /*!< Password */
01597       AST_STRING_FIELD(peermd5secret);
01598       AST_STRING_FIELD(cid_num); /*!< Caller*ID number */
01599       AST_STRING_FIELD(cid_name);   /*!< Caller*ID name */
01600       AST_STRING_FIELD(fullcontact);   /*!< The Contact: that the UA registers with us */
01601          /* we only store the part in <brackets> in this field. */
01602       AST_STRING_FIELD(our_contact);   /*!< Our contact header */
01603       AST_STRING_FIELD(rpid);    /*!< Our RPID header */
01604       AST_STRING_FIELD(rpid_from);  /*!< Our RPID From header */
01605       AST_STRING_FIELD(url);     /*!< URL to be sent with next message to peer */
01606       AST_STRING_FIELD(parkinglot);    /*!< Parkinglot */
01607    );
01608    char via[128];                          /*!< Via: header */
01609    struct sip_socket socket;     /*!< The socket used for this dialog */
01610    unsigned int ocseq;        /*!< Current outgoing seqno */
01611    unsigned int icseq;        /*!< Current incoming seqno */
01612    ast_group_t callgroup;        /*!< Call group */
01613    ast_group_t pickupgroup;      /*!< Pickup group */
01614    int lastinvite;            /*!< Last Cseq of invite */
01615    struct ast_flags flags[2];    /*!< SIP_ flags */
01616 
01617    /* boolean or small integers that don't belong in flags */
01618    char do_history;        /*!< Set if we want to record history */
01619    char alreadygone;       /*!< already destroyed by our peer */
01620    char needdestroy;       /*!< need to be destroyed by the monitor thread */
01621    char outgoing_call;        /*!< this is an outgoing call */
01622    char answered_elsewhere;      /*!< This call is cancelled due to answer on another channel */
01623    char novideo;           /*!< Didn't get video in invite, don't offer */
01624    char notext;            /*!< Text not supported  (?) */
01625 
01626    int timer_t1;           /*!< SIP timer T1, ms rtt */
01627    int timer_b;                            /*!< SIP timer B, ms */
01628    unsigned int sipoptions;      /*!< Supported SIP options on the other end */
01629    unsigned int reqsipoptions;      /*!< Required SIP options on the other end */
01630    struct ast_codec_pref prefs;     /*!< codec prefs */
01631    int capability;            /*!< Special capability (codec) */
01632    int jointcapability;       /*!< Supported capability at both ends (codecs) */
01633    int peercapability;        /*!< Supported peer capability */
01634    int prefcodec;          /*!< Preferred codec (outbound only) */
01635    int noncodeccapability;       /*!< DTMF RFC2833 telephony-event */
01636    int jointnoncodeccapability;            /*!< Joint Non codec capability */
01637    int redircodecs;        /*!< Redirect codecs */
01638    int maxcallbitrate;        /*!< Maximum Call Bitrate for Video Calls */ 
01639    int t38_maxdatagram;       /*!< T.38 FaxMaxDatagram override */
01640    struct sip_proxy *outboundproxy; /*!< Outbound proxy for this dialog. Use ref_proxy to set this instead of setting it directly*/
01641    struct t38properties t38;     /*!< T38 settings */
01642    struct sockaddr_in udptlredirip; /*!< Where our T.38 UDPTL should be going if not to us */
01643    struct ast_udptl *udptl;      /*!< T.38 UDPTL session */
01644    int callingpres;        /*!< Calling presentation */
01645    int authtries;          /*!< Times we've tried to authenticate */
01646    int expiry;          /*!< How long we take to expire */
01647    long branch;            /*!< The branch identifier of this session */
01648    long invite_branch;        /*!< The branch used when we sent the initial INVITE */
01649    char tag[11];           /*!< Our tag for this session */
01650    int sessionid;          /*!< SDP Session ID */
01651    int sessionversion;        /*!< SDP Session Version */
01652    int64_t sessionversion_remote;      /*!< Remote UA's SDP Session Version */
01653    int session_modify;        /*!< Session modification request true/false  */
01654    unsigned int portinuri:1;     /*!< Non zero if a port has been specified, will also disable srv lookups */
01655    struct sockaddr_in sa;        /*!< Our peer */
01656    struct sockaddr_in redirip;      /*!< Where our RTP should be going if not to us */
01657    struct sockaddr_in vredirip;     /*!< Where our Video RTP should be going if not to us */
01658    struct sockaddr_in tredirip;     /*!< Where our Text RTP should be going if not to us */
01659    time_t lastrtprx;       /*!< Last RTP received */
01660    time_t lastrtptx;       /*!< Last RTP sent */
01661    int rtptimeout;            /*!< RTP timeout time */
01662    struct sockaddr_in recv;      /*!< Received as */
01663    struct sockaddr_in ourip;     /*!< Our IP (as seen from the outside) */
01664    struct ast_channel *owner;    /*!< Who owns us (if we have an owner) */
01665    struct sip_route *route;      /*!< Head of linked list of routing steps (fm Record-Route) */
01666    int route_persistant;         /*!< Is this the "real" route? */
01667    struct ast_variable *notify_headers;    /*!< Custom notify type */
01668    struct sip_auth *peerauth;    /*!< Realm authentication */
01669    int noncecount;            /*!< Nonce-count */
01670    unsigned int stalenonce:1; /*!< Marks the current nonce as responded too */
01671    char lastmsg[256];         /*!< Last Message sent/received */
01672    int amaflags;           /*!< AMA Flags */
01673    int pendinginvite;         /*!< Any pending INVITE or state NOTIFY (in subscribe pvt's) ? (seqno of this) */
01674    int glareinvite;        /*!< A invite received while a pending invite is already present is stored here.  Its seqno is the
01675                   value. Since this glare invite's seqno is not the same as the pending invite's, it must be 
01676                   held in order to properly process acknowledgements for our 491 response. */
01677    struct sip_request initreq;      /*!< Latest request that opened a new transaction
01678                      within this dialog.
01679                      NOT the request that opened the dialog */
01680 
01681    int initid;          /*!< Auto-congest ID if appropriate (scheduler) */
01682    int waitid;          /*!< Wait ID for scheduler after 491 or other delays */
01683    int autokillid;            /*!< Auto-kill ID (scheduler) */
01684    int t38id;                              /*!< T.38 Response ID */
01685    enum transfermodes allowtransfer;   /*!< REFER: restriction scheme */
01686    struct sip_refer *refer;      /*!< REFER: SIP transfer data structure */
01687    enum subscriptiontype subscribed;   /*!< SUBSCRIBE: Is this dialog a subscription?  */
01688    int stateid;            /*!< SUBSCRIBE: ID for devicestate subscriptions */
01689    int laststate;          /*!< SUBSCRIBE: Last known extension state */
01690    int dialogver;          /*!< SUBSCRIBE: Version for subscription dialog-info */
01691 
01692    struct ast_dsp *dsp;       /*!< A DSP for inband DTMF and fax CNG tone detection */
01693 
01694    struct sip_peer *relatedpeer;    /*!< If this dialog is related to a peer, which one 
01695                      Used in peerpoke, mwi subscriptions */
01696    struct sip_registry *registry;      /*!< If this is a REGISTER dialog, to which registry */
01697    struct ast_rtp *rtp;       /*!< RTP Session */
01698    struct ast_rtp *vrtp;         /*!< Video RTP session */
01699    struct ast_rtp *trtp;         /*!< Text RTP session */
01700    struct sip_pkt *packets;      /*!< Packets scheduled for re-transmission */
01701    struct sip_history_head *history;   /*!< History of this SIP dialog */
01702    size_t history_entries;       /*!< Number of entires in the history */
01703    struct ast_variable *chanvars;      /*!< Channel variables to set for inbound call */
01704    AST_LIST_HEAD_NOLOCK(request_queue, sip_request) request_queue; /*!< Requests that arrived but could not be processed immediately */
01705    int request_queue_sched_id;      /*!< Scheduler ID of any scheduled action to process queued requests */
01706    int provisional_keepalive_sched_id; /*!< Scheduler ID for provisional responses that need to be sent out to avoid cancellation */
01707    const char *last_provisional;   /*!< The last successfully transmitted provisonal response message */
01708    struct sip_invite_param *options;   /*!< Options for INVITE */
01709    int autoframing;        /*!< The number of Asters we group in a Pyroflax
01710                      before strolling to the Grokyzpå
01711                      (A bit unsure of this, please correct if
01712                      you know more) */
01713    struct sip_st_dlg *stimer;    /*!< SIP Session-Timers */              
01714   
01715    int red;             /*!< T.140 RTP Redundancy */
01716    int hangupcause;        /*!< Storage of hangupcause copied from our owner before we disconnect from the AST channel (only used at hangup) */
01717 
01718    struct sip_subscription_mwi *mwi;       /*!< If this is a subscription MWI dialog, to which subscription */
01719    /*! When receiving an SDP offer, it is important to take note of what media types were offered.
01720     * By doing this, even if we don't want to answer a particular media stream with something meaningful, we can
01721     * still put an m= line in our answer with the port set to 0.
01722     *
01723     * The reason for the length being 4 is that in this branch of Asterisk, the only media types supported are 
01724     * image, audio, text, and video. Therefore we need to keep track of which types of media were offered.
01725     *
01726     * Note that if we wanted to be 100% correct, we would keep a list of all media streams offered. That way we could respond
01727     * even to unknown media types, and we could respond to multiple streams of the same type. Such large-scale changes
01728     * are not a good idea for released branches, though, so we're compromising by just making sure that for the common cases:
01729     * audio and video, audio and T.38, and audio and text, we give the appropriate response to both media streams.
01730     *
01731     * The large-scale changes would be a good idea for implementing during an SDP rewrite.
01732     */
01733    struct offered_media offered_media[4];
01734 }; 
01735 
01736 
01737 /*! \brief
01738  * Here we implement the container for dialogs (sip_pvt), defining
01739  * generic wrapper functions to ease the transition from the current
01740  * implementation (a single linked list) to a different container.
01741  * In addition to a reference to the container, we need functions to lock/unlock
01742  * the container and individual items, and functions to add/remove
01743  * references to the individual items.
01744  */
01745 struct ao2_container *dialogs;
01746 
01747 #define sip_pvt_lock(x) ao2_lock(x)
01748 #define sip_pvt_trylock(x) ao2_trylock(x)
01749 #define sip_pvt_unlock(x) ao2_unlock(x)
01750 
01751 /*! \brief
01752  * when we create or delete references, make sure to use these
01753  * functions so we keep track of the refcounts.
01754  * To simplify the code, we allow a NULL to be passed to dialog_unref().
01755  */
01756 #ifdef REF_DEBUG
01757 #define dialog_ref(arg1,arg2) dialog_ref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
01758 #define dialog_unref(arg1,arg2) dialog_unref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
01759 
01760 static struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
01761 {
01762    if (p)
01763       _ao2_ref_debug(p, 1, tag, file, line, func);
01764    else
01765       ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
01766    return p;
01767 }
01768 
01769 static struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
01770 {
01771    if (p)
01772       _ao2_ref_debug(p, -1, tag, file, line, func);
01773    return NULL;
01774 }
01775 #else
01776 static struct sip_pvt *dialog_ref(struct sip_pvt *p, char *tag)
01777 {
01778    if (p)
01779       ao2_ref(p, 1);
01780    else
01781       ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
01782    return p;
01783 }
01784 
01785 static struct sip_pvt *dialog_unref(struct sip_pvt *p, char *tag)
01786 {
01787    if (p)
01788       ao2_ref(p, -1);
01789    return NULL;
01790 }
01791 #endif
01792 
01793 /*! \brief sip packet - raw format for outbound packets that are sent or scheduled for transmission
01794  * Packets are linked in a list, whose head is in the struct sip_pvt they belong to.
01795  * Each packet holds a reference to the parent struct sip_pvt.
01796  * This structure is allocated in __sip_reliable_xmit() and only for packets that
01797  * require retransmissions.
01798  */
01799 struct sip_pkt {
01800    struct sip_pkt *next;         /*!< Next packet in linked list */
01801    int retrans;            /*!< Retransmission number */
01802    int method;          /*!< SIP method for this packet */
01803    int seqno;           /*!< Sequence number */
01804    char is_resp;           /*!< 1 if this is a response packet (e.g. 200 OK), 0 if it is a request */
01805    char is_fatal;          /*!< non-zero if there is a fatal error */
01806    int response_code;      /*!< If this is a response, the response code */
01807    struct sip_pvt *owner;        /*!< Owner AST call */
01808    int retransid;          /*!< Retransmission ID */
01809    int timer_a;            /*!< SIP timer A, retransmission timer */
01810    int timer_t1;           /*!< SIP Timer T1, estimated RTT or 500 ms */
01811    int packetlen;          /*!< Length of packet */
01812    struct ast_str *data;
01813 }; 
01814 
01815 /*!
01816  * \brief A peer's mailbox
01817  *
01818  * We could use STRINGFIELDS here, but for only two strings, it seems like
01819  * too much effort ...
01820  */
01821 struct sip_mailbox {
01822    char *mailbox;
01823    char *context;
01824    unsigned int delme:1;
01825    /*! Associated MWI subscription */
01826    struct ast_event_sub *event_sub;
01827    AST_LIST_ENTRY(sip_mailbox) entry;
01828 };
01829 
01830 enum sip_peer_type {
01831    SIP_TYPE_PEER = (1 << 0),
01832    SIP_TYPE_USER = (1 << 1),
01833 };
01834 
01835 /*! \brief Structure for SIP peer data, we place calls to peers if registered  or fixed IP address (host) 
01836 */
01837 /* XXX field 'name' must be first otherwise sip_addrcmp() will fail, as will astobj2 hashing of the structure */
01838 struct sip_peer {
01839    char name[80];             /*!< the unique name of this object */
01840    AST_DECLARE_STRING_FIELDS(
01841       AST_STRING_FIELD(secret);     /*!< Password for inbound auth */
01842       AST_STRING_FIELD(md5secret);     /*!< Password in MD5 */
01843       AST_STRING_FIELD(remotesecret);     /*!< Remote secret (trunks, remote devices) */
01844       AST_STRING_FIELD(context);    /*!< Default context for incoming calls */
01845       AST_STRING_FIELD(subscribecontext); /*!< Default context for subscriptions */
01846       AST_STRING_FIELD(username);      /*!< Temporary username until registration */ 
01847       AST_STRING_FIELD(accountcode);      /*!< Account code */
01848       AST_STRING_FIELD(tohost);     /*!< If not dynamic, IP address */
01849       AST_STRING_FIELD(regexten);      /*!< Extension to register (if regcontext is used) */
01850       AST_STRING_FIELD(fromuser);      /*!< From: user when calling this peer */
01851       AST_STRING_FIELD(fromdomain);    /*!< From: domain when calling this peer */
01852       AST_STRING_FIELD(fullcontact);      /*!< Contact registered with us (not in sip.conf) */
01853       AST_STRING_FIELD(cid_num);    /*!< Caller ID num */
01854       AST_STRING_FIELD(cid_name);      /*!< Caller ID name */
01855       AST_STRING_FIELD(vmexten);       /*!< Dialplan extension for MWI notify message*/
01856       AST_STRING_FIELD(language);      /*!<  Default language for prompts */
01857       AST_STRING_FIELD(mohinterpret);     /*!<  Music on Hold class */
01858       AST_STRING_FIELD(mohsuggest);    /*!<  Music on Hold class */
01859       AST_STRING_FIELD(parkinglot);    /*!<  Parkinglot */
01860       AST_STRING_FIELD(useragent);     /*!<  User agent in SIP request (saved from registration) */
01861       );
01862    struct sip_socket socket;  /*!< Socket used for this peer */
01863    enum sip_transport default_outbound_transport;    /*!< Peer Registration may change the default outbound transport.
01864                                     If register expires, default should be reset. to this value */
01865    unsigned int transports:3;      /*!< Transports (enum sip_transport) that are acceptable for this peer */
01866    struct sip_auth *auth;     /*!< Realm authentication list */
01867    int amaflags;        /*!< AMA Flags (for billing) */
01868    int callingpres;     /*!< Calling id presentation */
01869    int inUse;        /*!< Number of calls in use */
01870    int inRinging;       /*!< Number of calls ringing */
01871    int onHold;                     /*!< Peer has someone on hold */
01872    int call_limit;         /*!< Limit of concurrent calls */
01873    int t38_maxdatagram;    /*!< T.38 FaxMaxDatagram override */
01874    int busy_level;         /*!< Level of active channels where we signal busy */
01875    enum transfermodes allowtransfer;   /*! SIP Refer restriction scheme */
01876    struct ast_codec_pref prefs;  /*!<  codec prefs */
01877    int lastmsgssent;
01878    unsigned int sipoptions;   /*!<  Supported SIP options */
01879    struct ast_flags flags[2]; /*!<  SIP_ flags */
01880 
01881    /*! Mailboxes that this peer cares about */
01882    AST_LIST_HEAD_NOLOCK(, sip_mailbox) mailboxes;
01883 
01884    /* things that don't belong in flags */
01885    char is_realtime;    /*!< this is a 'realtime' peer */
01886    char rt_fromcontact;    /*!< copy fromcontact from realtime */
01887    char host_dynamic;      /*!< Dynamic Peers register with Asterisk */
01888    char selfdestruct;      /*!< Automatic peers need to destruct themselves */
01889    char the_mark;       /*!< moved out of ASTOBJ into struct proper; That which bears the_mark should be deleted! */
01890 
01891    int expire;       /*!<  When to expire this peer registration */
01892    int capability;         /*!<  Codec capability */
01893    int rtptimeout;         /*!<  RTP timeout */
01894    int rtpholdtimeout;     /*!<  RTP Hold Timeout */
01895    int rtpkeepalive;    /*!<  Send RTP packets for keepalive */
01896    ast_group_t callgroup;     /*!<  Call group */
01897    ast_group_t pickupgroup;   /*!<  Pickup group */
01898    struct sip_proxy *outboundproxy; /*!< Outbound proxy for this peer */
01899    struct ast_dnsmgr_entry *dnsmgr;/*!<  DNS refresh manager for peer */
01900    struct sockaddr_in addr;   /*!<  IP address of peer */
01901    int maxcallbitrate;     /*!< Maximum Bitrate for a video call */
01902    unsigned int portinuri:1;  /*!< Whether the port should be included in the URI */
01903 
01904    /* Qualification */
01905    struct sip_pvt *call;      /*!<  Call pointer */
01906    int pokeexpire;         /*!<  When to expire poke (qualify= checking) */
01907    int lastms;       /*!<  How long last response took (in ms), or -1 for no response */
01908    int maxms;        /*!<  Max ms we will accept for the host to be up, 0 to not monitor */
01909    int qualifyfreq;     /*!<  Qualification: How often to check for the host to be up */
01910    struct timeval ps;      /*!<  Time for sending SIP OPTION in sip_pke_peer() */
01911    struct sockaddr_in defaddr;   /*!<  Default IP address, used until registration */
01912    struct ast_ha *ha;      /*!<  Access control list */
01913    struct ast_ha *contactha;       /*!<  Restrict what IPs are allowed in the Contact header (for registration) */
01914    struct ast_variable *chanvars;   /*!<  Variables to set for channel created by user */
01915    struct sip_pvt *mwipvt;    /*!<  Subscription for MWI */
01916    int autoframing;
01917    struct sip_st_cfg stimer;  /*!<  SIP Session-Timers */
01918    int timer_t1;        /*!<  The maximum T1 value for the peer */
01919    int timer_b;         /*!<  The maximum timer B (transaction timeouts) */
01920    int deprecated_username; /*!< If it's a realtime peer, are they using the deprecated "username" instead of "defaultuser" */
01921    
01922    /*XXX Seems like we suddenly have two flags with the same content. Why? To be continued... */
01923    enum sip_peer_type type; /*!< Distinguish between "user" and "peer" types. This is used solely for CLI and manager commands */
01924 };
01925 
01926 
01927 /*! 
01928  * \brief Registrations with other SIP proxies
01929  *
01930  * Created by sip_register(), the entry is linked in the 'regl' list,
01931  * and never deleted (other than at 'sip reload' or module unload times).
01932  * The entry always has a pending timeout, either waiting for an ACK to
01933  * the REGISTER message (in which case we have to retransmit the request),
01934  * or waiting for the next REGISTER message to be sent (either the initial one,
01935  * or once the previously completed registration one expires).
01936  * The registration can be in one of many states, though at the moment
01937  * the handling is a bit mixed.
01938  */
01939 struct sip_registry {
01940    ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
01941    AST_DECLARE_STRING_FIELDS(
01942       AST_STRING_FIELD(callid);  /*!< Global Call-ID */
01943       AST_STRING_FIELD(realm);   /*!< Authorization realm */
01944       AST_STRING_FIELD(nonce);   /*!< Authorization nonce */
01945       AST_STRING_FIELD(opaque);  /*!< Opaque nonsense */
01946       AST_STRING_FIELD(qop);     /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
01947       AST_STRING_FIELD(domain);  /*!< Authorization domain */
01948       AST_STRING_FIELD(username);   /*!< Who we are registering as */
01949       AST_STRING_FIELD(authuser);   /*!< Who we *authenticate* as */
01950       AST_STRING_FIELD(hostname);   /*!< Domain or host we register to */
01951       AST_STRING_FIELD(secret);  /*!< Password in clear text */   
01952       AST_STRING_FIELD(md5secret);  /*!< Password in md5 */
01953       AST_STRING_FIELD(callback);   /*!< Contact extension */
01954       AST_STRING_FIELD(random);
01955       AST_STRING_FIELD(peername);   /*!< Peer registering to */
01956    );
01957    enum sip_transport transport; /*!< Transport for this registration UDP, TCP or TLS */
01958    int portno;       /*!<  Optional port override */
01959    int expire;       /*!< Sched ID of expiration */
01960    int configured_expiry;     /*!< Configured value to use for the Expires header */
01961    int expiry;       /*!< Negotiated value used for the Expires header */
01962    int regattempts;     /*!< Number of attempts (since the last success) */
01963    int timeout;         /*!< sched id of sip_reg_timeout */
01964    int refresh;         /*!< How often to refresh */
01965    struct sip_pvt *call;      /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
01966    enum sipregistrystate regstate;  /*!< Registration state (see above) */
01967    struct timeval regtime;    /*!< Last successful registration time */
01968    int callid_valid;    /*!< 0 means we haven't chosen callid for this registry yet. */
01969    unsigned int ocseq;     /*!< Sequence number we got to for REGISTERs for this registry */
01970    struct ast_dnsmgr_entry *dnsmgr; /*!<  DNS refresh manager for register */
01971    struct sockaddr_in us;     /*!< Who the server thinks we are */
01972    int noncecount;         /*!< Nonce-count */
01973    char lastmsg[256];      /*!< Last Message sent/received */
01974 };
01975 
01976 enum sip_tcptls_alert {
01977    /*! \brief There is new data to be sent out */
01978    TCPTLS_ALERT_DATA,
01979    /*! \brief A request to stop the tcp_handler thread */
01980    TCPTLS_ALERT_STOP,
01981 };
01982 
01983 struct tcptls_packet {
01984    AST_LIST_ENTRY(tcptls_packet) entry;
01985    struct ast_str *data;
01986    size_t len;
01987 };
01988 /*! \brief Definition of a thread that handles a socket */
01989 struct sip_threadinfo {
01990    int stop;
01991    int alert_pipe[2]; /*! Used to alert tcptls thread when packet is ready to be written */
01992    pthread_t threadid;
01993    struct ast_tcptls_session_instance *tcptls_session;
01994    enum sip_transport type;   /*!< We keep a copy of the type here so we can display it in the connection list */
01995    AST_LIST_HEAD_NOLOCK(, tcptls_packet) packet_q;
01996 };
01997 
01998 /*! \brief Definition of an MWI subscription to another server */
01999 struct sip_subscription_mwi {
02000    ASTOBJ_COMPONENTS_FULL(struct sip_subscription_mwi,1,1);
02001    AST_DECLARE_STRING_FIELDS(
02002       AST_STRING_FIELD(username);     /*!< Who we are sending the subscription as */
02003       AST_STRING_FIELD(authuser);     /*!< Who we *authenticate* as */
02004       AST_STRING_FIELD(hostname);     /*!< Domain or host we subscribe to */
02005       AST_STRING_FIELD(secret);       /*!< Password in clear text */
02006       AST_STRING_FIELD(mailbox);      /*!< Mailbox store to put MWI into */
02007       );
02008    enum sip_transport transport;    /*!< Transport to use */
02009    int portno;                      /*!< Optional port override */
02010    int resub;                       /*!< Sched ID of resubscription */
02011    unsigned int subscribed:1;       /*!< Whether we are currently subscribed or not */
02012    struct sip_pvt *call;            /*!< Outbound subscription dialog */
02013    struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager for subscription */
02014    struct sockaddr_in us;           /*!< Who the server thinks we are */
02015 };
02016 
02017 /* --- Hash tables of various objects --------*/
02018 #ifdef LOW_MEMORY
02019 static const int HASH_PEER_SIZE = 17;
02020 static const int HASH_DIALOG_SIZE = 17;
02021 #else
02022 static const int HASH_PEER_SIZE = 563; /*!< Size of peer hash table, prime number preferred! */
02023 static const int HASH_DIALOG_SIZE = 563;
02024 #endif
02025 static struct ao2_container *threadt;
02026 
02027 /*! \brief  The peer list: Users, Peers and Friends */
02028 struct ao2_container *peers;
02029 struct ao2_container *peers_by_ip;
02030 
02031 /*! \brief  The register list: Other SIP proxies we register with and place calls to */
02032 static struct ast_register_list {
02033    ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
02034    int recheck;
02035 } regl;
02036 
02037 /*! \brief  The MWI subscription list */
02038 static struct ast_subscription_mwi_list {
02039    ASTOBJ_CONTAINER_COMPONENTS(struct sip_subscription_mwi);
02040 } submwil;
02041 
02042 /*! \brief
02043  * \note The only member of the peer used here is the name field
02044  */
02045 static int peer_hash_cb(const void *obj, const int flags)
02046 {
02047    const struct sip_peer *peer = obj;
02048 
02049    return ast_str_case_hash(peer->name);
02050 }
02051 
02052 /*!
02053  * \note The only member of the peer used here is the name field
02054  */
02055 static int peer_cmp_cb(void *obj, void *arg, int flags)
02056 {
02057    struct sip_peer *peer = obj, *peer2 = arg;
02058 
02059    return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
02060 }
02061 
02062 /*!
02063  * \note the peer's ip address field is used to create key.
02064  */
02065 static int peer_iphash_cb(const void *obj, const int flags)
02066 {
02067    const struct sip_peer *peer = obj;
02068    int ret1 = peer->addr.sin_addr.s_addr;
02069    if (ret1 < 0)
02070       ret1 = -ret1;
02071 
02072    return ret1;
02073 }
02074 
02075 /*!
02076  * Match Peers by IP and Port number.
02077  *
02078  * This function has two modes.
02079  *  - If the peer arg does not have INSECURE_PORT set, then we will only return
02080  *    a match for a peer that matches both the IP and port.
02081  *  - If the peer arg does have the INSECURE_PORT flag set, then we will only
02082  *    return a match for a peer that matches the IP and has insecure=port
02083  *    in its configuration.
02084  *
02085  * This callback will be used twice when doing peer matching.  There is a first
02086  * pass for full IP+port matching, and a second pass in case there is a match
02087  * that meets the insecure=port criteria.
02088  *
02089  * \note Connections coming in over TCP or TLS should never be matched by port.
02090  *
02091  * \note the peer's addr struct provides to fields combined to make a key: the sin_addr.s_addr and sin_port fields.
02092  */
02093 static int peer_ipcmp_cb(void *obj, void *arg, int flags)
02094 {
02095    struct sip_peer *peer = obj, *peer2 = arg;
02096 
02097    if (peer->addr.sin_addr.s_addr != peer2->addr.sin_addr.s_addr) {
02098       /* IP doesn't match */
02099       return 0;
02100    }
02101 
02102    /* We matched the IP, check to see if we need to match by port as well. */
02103    if ((peer->transports & peer2->transports) & (SIP_TRANSPORT_TLS | SIP_TRANSPORT_TCP)) {
02104       /* peer matching on port is not possible with TCP/TLS */
02105       return CMP_MATCH | CMP_STOP;
02106    } else if (ast_test_flag(&peer2->flags[0], SIP_INSECURE_PORT)) {
02107       /* We are allowing match without port for peers configured that
02108        * way in this pass through the peers. */
02109       return ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT) ?
02110             (CMP_MATCH | CMP_STOP) : 0;
02111    }
02112 
02113    /* Now only return a match if the port matches, as well. */
02114    return peer->addr.sin_port == peer2->addr.sin_port ? (CMP_MATCH | CMP_STOP) : 0;
02115 }
02116 
02117 
02118 static int threadt_hash_cb(const void *obj, const int flags)
02119 {
02120    const struct sip_threadinfo *th = obj;
02121 
02122    return (int) th->tcptls_session->remote_address.sin_addr.s_addr;
02123 }
02124 
02125 static int threadt_cmp_cb(void *obj, void *arg, int flags)
02126 {
02127    struct sip_threadinfo *th = obj, *th2 = arg;
02128 
02129    return (th->tcptls_session == th2->tcptls_session) ? CMP_MATCH | CMP_STOP : 0;
02130 }
02131 
02132 /*!
02133  * \note The only member of the dialog used here callid string
02134  */
02135 static int dialog_hash_cb(const void *obj, const int flags)
02136 {
02137    const struct sip_pvt *pvt = obj;
02138 
02139    return ast_str_case_hash(pvt->callid);
02140 }
02141 
02142 /*!
02143  * \note The only member of the dialog used here callid string
02144  */
02145 static int dialog_cmp_cb(void *obj, void *arg, int flags)
02146 {
02147    struct sip_pvt *pvt = obj, *pvt2 = arg;
02148    
02149    return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH | CMP_STOP : 0;
02150 }
02151 
02152 static int temp_pvt_init(void *);
02153 static void temp_pvt_cleanup(void *);
02154 
02155 /*! \brief A per-thread temporary pvt structure */
02156 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
02157 
02158 #ifdef LOW_MEMORY
02159 static void ts_ast_rtp_destroy(void *);
02160 
02161 AST_THREADSTORAGE_CUSTOM(ts_audio_rtp, NULL, ts_ast_rtp_destroy);
02162 AST_THREADSTORAGE_CUSTOM(ts_video_rtp, NULL, ts_ast_rtp_destroy);
02163 AST_THREADSTORAGE_CUSTOM(ts_text_rtp, NULL, ts_ast_rtp_destroy);
02164 #endif
02165 
02166 /*! \brief Authentication list for realm authentication 
02167  * \todo Move the sip_auth list to AST_LIST */
02168 static struct sip_auth *authl = NULL;
02169 
02170 
02171 /* --- Sockets and networking --------------*/
02172 
02173 /*! \brief Main socket for UDP SIP communication.
02174  *
02175  * sipsock is shared between the SIP manager thread (which handles reload
02176  * requests), the udp io handler (sipsock_read()) and the user routines that
02177  * issue udp writes (using __sip_xmit()).
02178  * The socket is -1 only when opening fails (this is a permanent condition),
02179  * or when we are handling a reload() that changes its address (this is
02180  * a transient situation during which we might have a harmless race, see
02181  * below). Because the conditions for the race to be possible are extremely
02182  * rare, we don't want to pay the cost of locking on every I/O.
02183  * Rather, we remember that when the race may occur, communication is
02184  * bound to fail anyways, so we just live with this event and let
02185  * the protocol handle this above us.
02186  */
02187 static int sipsock  = -1;
02188 
02189 static struct sockaddr_in bindaddr; /*!< UDP: The address we bind to */
02190 
02191 /*! \brief our (internal) default address/port to put in SIP/SDP messages
02192  *  internip is initialized picking a suitable address from one of the
02193  * interfaces, and the same port number we bind to. It is used as the
02194  * default address/port in SIP messages, and as the default address
02195  * (but not port) in SDP messages.
02196  */
02197 static struct sockaddr_in internip;
02198 
02199 /*! \brief our external IP address/port for SIP sessions.
02200  * externip.sin_addr is only set when we know we might be behind
02201  * a NAT, and this is done using a variety of (mutually exclusive)
02202  * ways from the config file:
02203  *
02204  * + with "externip = host[:port]" we specify the address/port explicitly.
02205  *   The address is looked up only once when (re)loading the config file;
02206  * 
02207  * + with "externhost = host[:port]" we do a similar thing, but the
02208  *   hostname is stored in externhost, and the hostname->IP mapping
02209  *   is refreshed every 'externrefresh' seconds;
02210  * 
02211  * + with "stunaddr = host[:port]" we run queries every externrefresh seconds
02212  *   to the specified server, and store the result in externip.
02213  *
02214  * Other variables (externhost, externexpire, externrefresh) are used
02215  * to support the above functions.
02216  */
02217 static struct sockaddr_in externip;    /*!< External IP address if we are behind NAT */
02218 
02219 static char externhost[MAXHOSTNAMELEN];      /*!< External host name */
02220 static time_t externexpire;         /*!< Expiration counter for re-resolving external host name in dynamic DNS */
02221 static int externrefresh = 10;
02222 static struct sockaddr_in stunaddr;    /*!< stun server address */
02223 
02224 /*! \brief  List of local networks
02225  * We store "localnet" addresses from the config file into an access list,
02226  * marked as 'DENY', so the call to ast_apply_ha() will return
02227  * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
02228  * (i.e. presumably public) addresses.
02229  */
02230 static struct ast_ha *localaddr;    /*!< List of local networks, on the same side of NAT as this Asterisk */
02231 
02232 static int ourport_tcp;          /*!< The port used for TCP connections */
02233 static int ourport_tls;          /*!< The port used for TCP/TLS connections */
02234 static struct sockaddr_in debugaddr;
02235 
02236 static struct ast_config *notify_types = NULL;     /*!< The list of manual NOTIFY types we know how to send */
02237 
02238 /*! some list management macros. */
02239  
02240 #define UNLINK(element, head, prev) do {  \
02241    if (prev)            \
02242       (prev)->next = (element)->next;  \
02243    else              \
02244       (head) = (element)->next;  \
02245    } while (0)
02246 
02247 enum t38_action_flag {
02248    SDP_T38_NONE = 0, /*!< Do not modify T38 information at all */
02249    SDP_T38_INITIATE, /*!< Remote side has requested T38 with us */
02250    SDP_T38_ACCEPT,   /*!< Remote side accepted our T38 request */
02251 };
02252 
02253 /*---------------------------- Forward declarations of functions in chan_sip.c */
02254 /* Note: This is added to help splitting up chan_sip.c into several files
02255    in coming releases. */
02256 
02257 /*--- PBX interface functions */
02258 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
02259 static int sip_devicestate(void *data);
02260 static int sip_sendtext(struct ast_channel *ast, const char *text);
02261 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
02262 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
02263 static int sip_hangup(struct ast_channel *ast);
02264 static int sip_answer(struct ast_channel *ast);
02265 static struct ast_frame *sip_read(struct ast_channel *ast);
02266 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
02267 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
02268 static int sip_transfer(struct ast_channel *ast, const char *dest);
02269 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
02270 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
02271 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
02272 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
02273 static const char *sip_get_callid(struct ast_channel *chan);
02274 
02275 static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin);
02276 static int sip_standard_port(enum sip_transport type, int port);
02277 static int sip_prepare_socket(struct sip_pvt *p);
02278 static int sip_parse_host(char *line, int lineno, char **hostname, int *portnum, enum sip_transport *transport);
02279 
02280 /*--- Transmitting responses and requests */
02281 static int sipsock_read(int *id, int fd, short events, void *ignore);
02282 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len);
02283 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod);
02284 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
02285 static int retrans_pkt(const void *data);
02286 static int transmit_response_using_temp(ast_string_field callid, struct sockaddr_in *sin, int useglobal_nat, const int intended_method, const struct sip_request *req, const char *msg);
02287 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
02288 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
02289 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
02290 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp);
02291 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
02292 static int transmit_response_with_auth(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *rand, enum xmittype reliable, const char *header, int stale);
02293 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
02294 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
02295 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable);
02296 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
02297 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
02298 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
02299 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
02300 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
02301 static int transmit_info_with_vidupdate(struct sip_pvt *p);
02302 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
02303 static int transmit_refer(struct sip_pvt *p, const char *dest);
02304 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
02305 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
02306 static int transmit_notify_custom(struct sip_pvt *p, struct ast_variable *vars);
02307 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
02308 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
02309 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
02310 static void copy_request(struct sip_request *dst, const struct sip_request *src);
02311 static void receive_message(struct sip_pvt *p, struct sip_request *req);
02312 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req);
02313 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only);
02314 
02315 /*--- Dialog management */
02316 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
02317              int useglobal_nat, const int intended_method, struct sip_request *req);
02318 static int __sip_autodestruct(const void *data);
02319 static void sip_scheddestroy(struct sip_pvt *p, int ms);
02320 static int sip_cancel_destroy(struct sip_pvt *p);
02321 static struct sip_pvt *sip_destroy(struct sip_pvt *p);
02322 static void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist);
02323 static void *registry_unref(struct sip_registry *reg, char *tag);
02324 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist);
02325 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
02326 static void __sip_pretend_ack(struct sip_pvt *p);
02327 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
02328 static int auto_congest(const void *arg);
02329 static int update_call_counter(struct sip_pvt *fup, int event);
02330 static int hangup_sip2cause(int cause);
02331 static const char *hangup_cause2sip(int cause);
02332 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
02333 static void free_old_route(struct sip_route *route);
02334 static void list_route(struct sip_route *route);
02335 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
02336 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
02337                      struct sip_request *req, char *uri);
02338 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
02339 static void check_pendings(struct sip_pvt *p);
02340 static void *sip_park_thread(void *stuff);
02341 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
02342 
02343 static void *sip_pickup_thread(void *stuff);
02344 static int sip_pickup(struct ast_channel *chan);
02345 
02346 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
02347 
02348 /*--- Codec handling / SDP */
02349 static void try_suggested_sip_codec(struct sip_pvt *p);
02350 static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
02351 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
02352 static int find_sdp(struct sip_request *req);
02353 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
02354 static int process_sdp_o(const char *o, struct sip_pvt *p);
02355 static int process_sdp_c(const char *c, struct ast_hostent *hp);
02356 static int process_sdp_a_sendonly(const char *a, int *sendonly);
02357 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp *newaudiortp, int *last_rtpmap_codec);
02358 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp *newvideortp, int *last_rtpmap_codec);
02359 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);
02360 static int process_sdp_a_image(const char *a, struct sip_pvt *p);
02361 static void add_codec_to_sdp(const struct sip_pvt *p, int codec,
02362               struct ast_str **m_buf, struct ast_str **a_buf,
02363               int debug, int *min_packet_size);
02364 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
02365             struct ast_str **m_buf, struct ast_str **a_buf,
02366             int debug);
02367 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
02368 static void do_setnat(struct sip_pvt *p, int natflags);
02369 static void stop_media_flows(struct sip_pvt *p);
02370 
02371 /*--- Authentication stuff */
02372 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
02373 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
02374 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
02375                 const char *secret, const char *md5secret, int sipmethod,
02376                 char *uri, enum xmittype reliable, int ignore);
02377 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
02378                      int sipmethod, char *uri, enum xmittype reliable,
02379                      struct sockaddr_in *sin, struct sip_peer **authpeer);
02380 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);
02381 
02382 /*--- Domain handling */
02383 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
02384 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
02385 static void clear_sip_domains(void);
02386 
02387 /*--- SIP realm authentication */
02388 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno);
02389 static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */
02390 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
02391 
02392 /*--- Misc functions */
02393 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t);
02394 static int sip_do_reload(enum channelreloadreason reason);
02395 static int reload_config(enum channelreloadreason reason);
02396 static int expire_register(const void *data);
02397 static void *do_monitor(void *data);
02398 static int restart_monitor(void);
02399 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
02400 static struct ast_variable *copy_vars(struct ast_variable *src);
02401 /* static int sip_addrcmp(char *name, struct sockaddr_in *sin);   Support for peer matching */
02402 static int sip_refer_allocate(struct sip_pvt *p);
02403 static void ast_quiet_chan(struct ast_channel *chan);
02404 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
02405 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
02406 
02407 /*!
02408  * \brief generic function for determining if a correct transport is being 
02409  * used to contact a peer
02410  *
02411  * this is done as a macro so that the "tmpl" var can be passed either a 
02412  * sip_request or a sip_peer 
02413  */
02414 #define check_request_transport(peer, tmpl) ({ \
02415    int ret = 0; \
02416    if (peer->socket.type == tmpl->socket.type) \
02417       ; \
02418    else if (!(peer->transports & tmpl->socket.type)) {\
02419       ast_log(LOG_ERROR, \
02420          "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
02421          get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
02422          ); \
02423       ret = 1; \
02424    } else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
02425       ast_log(LOG_WARNING, \
02426          "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
02427          peer->name, get_transport(tmpl->socket.type) \
02428       ); \
02429    } else { \
02430       ast_debug(1, \
02431          "peer '%s' has contacted us over %s even though we prefer %s.\n", \
02432          peer->name, get_transport(tmpl->socket.type), get_transport(peer->socket.type) \
02433       ); \
02434    }\
02435    (ret); \
02436 })
02437 
02438 
02439 /*--- Device monitoring and Device/extension state/event handling */
02440 static int cb_extensionstate(char *context, char* exten, int state, void *data);
02441 static int sip_devicestate(void *data);
02442 static int sip_poke_noanswer(const void *data);
02443 static int sip_poke_peer(struct sip_peer *peer, int force);
02444 static void sip_poke_all_peers(void);
02445 static void sip_peer_hold(struct sip_pvt *p, int hold);
02446 static void mwi_event_cb(const struct ast_event *, void *);
02447 
02448 /*--- Applications, functions, CLI and manager command helpers */
02449 static const char *sip_nat_mode(const struct sip_pvt *p);
02450 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02451 static char *transfermode2str(enum transfermodes mode) attribute_const;
02452 static const char *nat2str(int nat) attribute_const;
02453 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
02454 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02455 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02456 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02457 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02458 static void  print_group(int fd, ast_group_t group, int crlf);
02459 static const char *dtmfmode2str(int mode) attribute_const;
02460 static int str2dtmfmode(const char *str) attribute_unused;
02461 static const char *insecure2str(int mode) attribute_const;
02462 static void cleanup_stale_contexts(char *new, char *old);
02463 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
02464 static const char *domain_mode_to_text(const enum domain_mode mode);
02465 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02466 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02467 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02468 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02469 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02470 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02471 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02472 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02473 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02474 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
02475 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
02476 static char *complete_sip_peer(const char *word, int state, int flags2);
02477 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
02478 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
02479 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
02480 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
02481 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
02482 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02483 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02484 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02485 static char *sip_do_debug_ip(int fd, char *arg);
02486 static char *sip_do_debug_peer(int fd, char *arg);
02487 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02488 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02489 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02490 static int sip_dtmfmode(struct ast_channel *chan, void *data);
02491 static int sip_addheader(struct ast_channel *chan, void *data);
02492 static int sip_do_reload(enum channelreloadreason reason);
02493 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02494 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
02495 
02496 /*--- Debugging 
02497    Functions for enabling debug per IP or fully, or enabling history logging for
02498    a SIP dialog
02499 */
02500 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to debuglog at end of dialog, before destroying data */
02501 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
02502 static inline int sip_debug_test_pvt(struct sip_pvt *p);
02503 
02504 
02505 /*! \brief Append to SIP dialog history 
02506    \return Always returns 0 */
02507 #define append_history(p, event, fmt , args... )   append_history_full(p, "%-15s " fmt, event, ## args)
02508 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
02509 static void sip_dump_history(struct sip_pvt *dialog);
02510 
02511 /*--- Device object handling */
02512 static struct sip_peer *temp_peer(const char *name);
02513 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
02514 static int update_call_counter(struct sip_pvt *fup, int event);
02515 static void sip_destroy_peer(struct sip_peer *peer);
02516 static void sip_destroy_peer_fn(void *peer);
02517 static void set_peer_defaults(struct sip_peer *peer);
02518 static struct sip_peer *temp_peer(const char *name);
02519 static void register_peer_exten(struct sip_peer *peer, int onoff);
02520 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int forcenamematch, int devstate_only, int transport);
02521 static int sip_poke_peer_s(const void *data);
02522 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
02523 static void reg_source_db(struct sip_peer *peer);
02524 static void destroy_association(struct sip_peer *peer);
02525 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
02526 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
02527 static void set_socket_transport(struct sip_socket *socket, int transport);
02528 
02529 /* Realtime device support */
02530 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);
02531 static void update_peer(struct sip_peer *p, int expire);
02532 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
02533 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername);
02534 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin, int devstate_only);
02535 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02536 
02537 /*--- Internal UA client handling (outbound registrations) */
02538 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p);
02539 static void sip_registry_destroy(struct sip_registry *reg);
02540 static int sip_register(const char *value, int lineno);
02541 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
02542 static int sip_reregister(const void *data);
02543 static int __sip_do_register(struct sip_registry *r);
02544 static int sip_reg_timeout(const void *data);
02545 static void sip_send_all_registers(void);
02546 static int sip_reinvite_retry(const void *data);
02547 
02548 /*--- Parsing SIP requests and responses */
02549 static void append_date(struct sip_request *req);  /* Append date to SIP packet */
02550 static int determine_firstline_parts(struct sip_request *req);
02551 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
02552 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
02553 static int find_sip_method(const char *msg);
02554 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
02555 static int parse_request(struct sip_request *req);
02556 static const char *get_header(const struct sip_request *req, const char *name);
02557 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
02558 static int method_match(enum sipmethod id, const char *name);
02559 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
02560 static char *get_in_brackets(char *tmp);
02561 static const char *find_alias(const char *name, const char *_default);
02562 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
02563 static int lws2sws(char *msgbuf, int len);
02564 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
02565 static char *remove_uri_parameters(char *uri);
02566 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
02567 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
02568 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
02569 static int set_address_from_contact(struct sip_pvt *pvt);
02570 static void check_via(struct sip_pvt *p, struct sip_request *req);
02571 static char *get_calleridname(const char *input, char *output, size_t outputsize);
02572 static int get_rpid_num(const char *input, char *output, int maxlen);
02573 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
02574 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
02575 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline);
02576 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
02577 static struct sip_via *parse_via(const char *header);
02578 static void free_via(struct sip_via *v);
02579 
02580 /*-- TCP connection handling ---*/
02581 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session);
02582 static void *sip_tcp_worker_fn(void *);
02583 
02584 /*--- Constructing requests and responses */
02585 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
02586 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
02587 static void deinit_req(struct sip_request *req);
02588 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
02589 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
02590 static int init_resp(struct sip_request *resp, const char *msg);
02591 static inline int resp_needs_contact(const char *msg, enum sipmethod method);
02592 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
02593 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
02594 static void build_via(struct sip_pvt *p);
02595 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
02596 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog);
02597 static char *generate_random_string(char *buf, size_t size);
02598 static void build_callid_pvt(struct sip_pvt *pvt);
02599 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
02600 static void make_our_tag(char *tagbuf, size_t len);
02601 static int add_header(struct sip_request *req, const char *var, const char *value);
02602 static int add_content(struct sip_request *req, const char *line);
02603 static int finalize_content(struct sip_request *req);
02604 static int add_text(struct sip_request *req, const char *text);
02605 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
02606 static int add_vidupdate(struct sip_request *req);
02607 static void add_route(struct sip_request *req, struct sip_route *route);
02608 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
02609 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
02610 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
02611 static void set_destination(struct sip_pvt *p, char *uri);
02612 static void append_date(struct sip_request *req);
02613 static void build_contact(struct sip_pvt *p);
02614 static void build_rpid(struct sip_pvt *p);
02615 
02616 /*------Request handling functions */
02617 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
02618 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);
02619 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
02620 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
02621 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
02622 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
02623 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
02624 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
02625 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
02626 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
02627 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *nounlock);
02628 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
02629 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);
02630 
02631 /*------Response handling functions */
02632 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02633 static void handle_response_notify(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02634 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02635 static void handle_response_subscribe(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02636 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02637 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02638 
02639 /*----- RTP interface functions */
02640 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);
02641 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02642 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02643 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02644 static int sip_get_codec(struct ast_channel *chan);
02645 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);
02646 
02647 /*------ T38 Support --------- */
02648 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
02649 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
02650 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
02651 static void change_t38_state(struct sip_pvt *p, int state);
02652 
02653 /*------ Session-Timers functions --------- */
02654 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
02655 static int  proc_session_timer(const void *vp);
02656 static void stop_session_timer(struct sip_pvt *p);
02657 static void start_session_timer(struct sip_pvt *p);
02658 static void restart_session_timer(struct sip_pvt *p);
02659 static const char *strefresher2str(enum st_refresher r);
02660 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
02661 static int parse_minse(const char *p_hdrval, int *const p_interval);
02662 static int st_get_se(struct sip_pvt *, int max);
02663 static enum st_refresher st_get_refresher(struct sip_pvt *);
02664 static enum st_mode st_get_mode(struct sip_pvt *, int no_cached);
02665 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
02666 
02667 /*!--- SIP MWI Subscription support */
02668 static int sip_subscribe_mwi(const char *value, int lineno);
02669 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
02670 static void sip_send_all_mwi_subscriptions(void);
02671 static int sip_subscribe_mwi_do(const void *data);
02672 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
02673 
02674 /*! \brief Definition of this channel for PBX channel registration */
02675 static const struct ast_channel_tech sip_tech = {
02676    .type = "SIP",
02677    .description = "Session Initiation Protocol (SIP)",
02678    .capabilities = AST_FORMAT_AUDIO_MASK, /* all audio formats */
02679    .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
02680    .requester = sip_request_call,         /* called with chan unlocked */
02681    .devicestate = sip_devicestate,        /* called with chan unlocked (not chan-specific) */
02682    .call = sip_call,       /* called with chan locked */
02683    .send_html = sip_sendhtml,
02684    .hangup = sip_hangup,         /* called with chan locked */
02685    .answer = sip_answer,         /* called with chan locked */
02686    .read = sip_read,       /* called with chan locked */
02687    .write = sip_write,        /* called with chan locked */
02688    .write_video = sip_write,     /* called with chan locked */
02689    .write_text = sip_write,
02690    .indicate = sip_indicate,     /* called with chan locked */
02691    .transfer = sip_transfer,     /* called with chan locked */
02692    .fixup = sip_fixup,        /* called with chan locked */
02693    .send_digit_begin = sip_senddigit_begin,  /* called with chan unlocked */
02694    .send_digit_end = sip_senddigit_end,
02695    .bridge = ast_rtp_bridge,        /* XXX chan unlocked ? */
02696    .early_bridge = ast_rtp_early_bridge,
02697    .send_text = sip_sendtext,    /* called with chan locked */
02698    .func_channel_read = acf_channel_read,
02699    .queryoption = sip_queryoption,
02700    .get_pvt_uniqueid = sip_get_callid,
02701 };
02702 
02703 /*! \brief This version of the sip channel tech has no send_digit_begin
02704  * callback so that the core knows that the channel does not want
02705  * DTMF BEGIN frames.
02706  * The struct is initialized just before registering the channel driver,
02707  * and is for use with channels using SIP INFO DTMF.
02708  */
02709 static struct ast_channel_tech sip_tech_info;
02710 
02711 
02712 /*! \brief Working TLS connection configuration */
02713 static struct ast_tls_config sip_tls_cfg;
02714 
02715 /*! \brief Default TLS connection configuration */
02716 static struct ast_tls_config default_tls_cfg;
02717 
02718 /*! \brief The TCP server definition */
02719 static struct ast_tcptls_session_args sip_tcp_desc = {
02720    .accept_fd = -1,
02721    .master = AST_PTHREADT_NULL,
02722    .tls_cfg = NULL,
02723    .poll_timeout = -1,
02724    .name = "SIP TCP server",
02725    .accept_fn = ast_tcptls_server_root,
02726    .worker_fn = sip_tcp_worker_fn,
02727 };
02728 
02729 /*! \brief The TCP/TLS server definition */
02730 static struct ast_tcptls_session_args sip_tls_desc = {
02731    .accept_fd = -1,
02732    .master = AST_PTHREADT_NULL,
02733    .tls_cfg = &sip_tls_cfg,
02734    .poll_timeout = -1,
02735    .name = "SIP TLS server",
02736    .accept_fn = ast_tcptls_server_root,
02737    .worker_fn = sip_tcp_worker_fn,
02738 };
02739 
02740 /* wrapper macro to tell whether t points to one of the sip_tech descriptors */
02741 #define IS_SIP_TECH(t)  ((t) == &sip_tech || (t) == &sip_tech_info)
02742 
02743 /*! \brief map from an integer value to a string.
02744  * If no match is found, return errorstring
02745  */
02746 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
02747 {
02748    const struct _map_x_s *cur;
02749 
02750    for (cur = table; cur->s; cur++)
02751       if (cur->x == x)
02752          return cur->s;
02753    return errorstring;
02754 }
02755 
02756 /*! \brief map from a string to an integer value, case insensitive.
02757  * If no match is found, return errorvalue.
02758  */
02759 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
02760 {
02761    const struct _map_x_s *cur;
02762 
02763    for (cur = table; cur->s; cur++)
02764       if (!strcasecmp(cur->s, s))
02765          return cur->x;
02766    return errorvalue;
02767 }
02768 
02769 
02770 /*! \brief Interface structure with callbacks used to connect to RTP module */
02771 static struct ast_rtp_protocol sip_rtp = {
02772    .type = "SIP",
02773    .get_rtp_info = sip_get_rtp_peer,
02774    .get_vrtp_info = sip_get_vrtp_peer,
02775    .get_trtp_info = sip_get_trtp_peer,
02776    .set_rtp_peer = sip_set_rtp_peer,
02777    .get_codec = sip_get_codec,
02778 };
02779 
02780 /*!
02781  * duplicate a list of channel variables, \return the copy.
02782  */
02783 static struct ast_variable *copy_vars(struct ast_variable *src)
02784 {
02785    struct ast_variable *res = NULL, *tmp, *v = NULL;
02786 
02787    for (v = src ; v ; v = v->next) {
02788       if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
02789          tmp->next = res;
02790          res = tmp;
02791       }
02792    }
02793    return res;
02794 }
02795 
02796 static void tcptls_packet_destructor(void *obj)
02797 {
02798    struct tcptls_packet *packet = obj;
02799 
02800    ast_free(packet->data);
02801 }
02802 
02803 static void sip_tcptls_client_args_destructor(void *obj)
02804 {
02805    struct ast_tcptls_session_args *args = obj;
02806    if (args->tls_cfg) {
02807       ast_free(args->tls_cfg->certfile);
02808       ast_free(args->tls_cfg->cipher);
02809       ast_free(args->tls_cfg->cafile);
02810       ast_free(args->tls_cfg->capath);
02811    }
02812    ast_free(args->tls_cfg);
02813    ast_free((char *) args->name);
02814 }
02815 
02816 static void sip_threadinfo_destructor(void *obj)
02817 {
02818    struct sip_threadinfo *th = obj;
02819    struct tcptls_packet *packet;
02820    if (th->alert_pipe[1] > -1) {
02821       close(th->alert_pipe[0]);
02822    }
02823    if (th->alert_pipe[1] > -1) {
02824       close(th->alert_pipe[1]);
02825    }
02826    th->alert_pipe[0] = th->alert_pipe[1] = -1;
02827 
02828    while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
02829       ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
02830    }
02831 
02832    if (th->tcptls_session) {
02833       ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
02834    }
02835 }
02836 
02837 /*! \brief creates a sip_threadinfo object and links it into the threadt table. */
02838 static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
02839 {
02840    struct sip_threadinfo *th;
02841 
02842    if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
02843       return NULL;
02844    }
02845 
02846    th->alert_pipe[0] = th->alert_pipe[1] = -1;
02847 
02848    if (pipe(th->alert_pipe) == -1) {
02849       ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
02850       ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
02851       return NULL;
02852    }
02853    ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
02854    th->tcptls_session = tcptls_session;
02855    th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
02856    ao2_t_link(threadt, th, "Adding new tcptls helper thread");
02857    ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
02858    return th;
02859 }
02860 
02861 /*! \brief used to indicate to a tcptls thread that data is ready to be written */
02862 static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
02863 {
02864    int res = len;
02865    struct sip_threadinfo *th = NULL;
02866    struct tcptls_packet *packet = NULL;
02867    struct sip_threadinfo tmp = {
02868       .tcptls_session = tcptls_session,
02869    };
02870    enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
02871 
02872    if (!tcptls_session) {
02873       return XMIT_ERROR;
02874    }
02875 
02876    ast_mutex_lock(&tcptls_session->lock);
02877 
02878    if ((tcptls_session->fd == -1) ||
02879       !(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
02880       !(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
02881       !(packet->data = ast_str_create(len))) {
02882       goto tcptls_write_setup_error;
02883    }
02884 
02885    /* goto tcptls_write_error should _NOT_ be used beyond this point */
02886    ast_str_set(&packet->data, 0, "%s", (char *) buf);
02887    packet->len = len;
02888 
02889    /* alert tcptls thread handler that there is a packet to be sent.
02890     * must lock the thread info object to guarantee control of the
02891     * packet queue */
02892    ao2_lock(th);
02893    if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
02894       ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
02895       ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
02896       packet = NULL;
02897       res = XMIT_ERROR;
02898    } else { /* it is safe to queue the frame after issuing the alert when we hold the threadinfo lock */
02899       AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
02900    }
02901    ao2_unlock(th);
02902 
02903    ast_mutex_unlock(&tcptls_session->lock);
02904    ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
02905    return res;
02906 
02907 tcptls_write_setup_error:
02908    if (th) {
02909       ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
02910    }
02911    if (packet) {
02912       ao2_t_ref(packet, -1, "could not allocate packet's data");
02913    }
02914    ast_mutex_unlock(&tcptls_session->lock);
02915 
02916    return XMIT_ERROR;
02917 }
02918 
02919 /*! \brief SIP TCP connection handler */
02920 static void *sip_tcp_worker_fn(void *data)
02921 {
02922    struct ast_tcptls_session_instance *tcptls_session = data;
02923 
02924    return _sip_tcp_helper_thread(NULL, tcptls_session);
02925 }
02926 
02927 /*! \brief Check if the authtimeout has expired.
02928  * \param start the time when the session started
02929  *
02930  * \retval 0 the timeout has expired
02931  * \retval -1 error
02932  * \return the number of milliseconds until the timeout will expire
02933  */
02934 static int sip_check_authtimeout(time_t start)
02935 {
02936    int timeout;
02937    time_t now;
02938    if(time(&now) == -1) {
02939       ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
02940       return -1;
02941    }
02942 
02943    timeout = (authtimeout - (now - start)) * 1000;
02944    if (timeout < 0) {
02945       /* we have timed out */
02946       return 0;
02947    }
02948 
02949    return timeout;
02950 }
02951 
02952 /*! \brief SIP TCP thread management function 
02953    This function reads from the socket, parses the packet into a request
02954 */
02955 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session) 
02956 {
02957    int res, cl, timeout = -1, authenticated = 0, flags, after_poll = 0, need_poll = 1;
02958    time_t start;
02959    struct sip_request req = { 0, } , reqcpy = { 0, };
02960    struct sip_threadinfo *me = NULL;
02961    char buf[1024] = "";
02962    struct pollfd fds[2] = { { 0 }, { 0 }, };
02963    struct ast_tcptls_session_args *ca = NULL;
02964 
02965    /* If this is a server session, then the connection has already been
02966     * setup. Check if the authlimit has been reached and if not create the
02967     * threadinfo object so we can access this thread for writing.
02968     *
02969     * if this is a client connection more work must be done.
02970     * 1. We own the parent session args for a client connection.  This pointer needs
02971     *    to be held on to so we can decrement it's ref count on thread destruction.
02972     * 2. The threadinfo object was created before this thread was launched, however
02973     *    it must be found within the threadt table.
02974     * 3. Last, the tcptls_session must be started.
02975     */
02976    if (!tcptls_session->client) {
02977       if (ast_atomic_fetchadd_int(&unauth_sessions, +1) >= authlimit) {
02978          /* unauth_sessions is decremented in the cleanup code */
02979          goto cleanup;
02980       }
02981 
02982       if ((flags = fcntl(tcptls_session->fd, F_GETFL)) == -1) {
02983          ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
02984          goto cleanup;
02985       }
02986 
02987       flags |= O_NONBLOCK;
02988       if (fcntl(tcptls_session->fd, F_SETFL, flags) == -1) {
02989          ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
02990          goto cleanup;
02991       }
02992 
02993       if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
02994          goto cleanup;
02995       }
02996       ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
02997    } else {
02998       struct sip_threadinfo tmp = {
02999          .tcptls_session = tcptls_session,
03000       };
03001 
03002       if ((!(ca = tcptls_session->parent)) ||
03003          (!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
03004          (!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
03005          goto cleanup;
03006       }
03007    }
03008 
03009    flags = 1;
03010    if (setsockopt(tcptls_session->fd, SOL_SOCKET, SO_KEEPALIVE, &flags, sizeof(flags))) {
03011       ast_log(LOG_ERROR, "error enabling TCP keep-alives on sip socket: %s\n", strerror(errno));
03012       goto cleanup;
03013    }
03014 
03015    me->threadid = pthread_self();
03016    ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
03017 
03018    /* set up pollfd to watch for reads on both the socket and the alert_pipe */
03019    fds[0].fd = tcptls_session->fd;
03020    fds[1].fd = me->alert_pipe[0];
03021    fds[0].events = fds[1].events = POLLIN | POLLPRI;
03022 
03023    if (!(req.data = ast_str_create(SIP_MIN_PACKET)))
03024       goto cleanup;
03025    if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET)))
03026       goto cleanup;
03027 
03028    if(time(&start) == -1) {
03029       ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
03030       goto cleanup;
03031    }
03032 
03033    for (;;) {
03034       struct ast_str *str_save;
03035 
03036       if (!tcptls_session->client && req.authenticated && !authenticated) {
03037          authenticated = 1;
03038          ast_atomic_fetchadd_int(&unauth_sessions, -1);
03039       }
03040 
03041       /* calculate the timeout for unauthenticated server sessions */
03042       if (!tcptls_session->client && !authenticated ) {
03043          if ((timeout = sip_check_authtimeout(start)) < 0) {
03044             goto cleanup;
03045          }
03046 
03047          if (timeout == 0) {
03048             ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
03049             goto cleanup;
03050          }
03051       } else {
03052          timeout = -1;
03053       }
03054 
03055       res = ast_poll(fds, 2, timeout); /* polls for both socket and alert_pipe */
03056       if (res < 0) {
03057          ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
03058          goto cleanup;
03059       } else if (res == 0) {
03060          /* timeout */
03061          ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
03062          goto cleanup;
03063       }
03064 
03065       /* handle the socket event, check for both reads from the socket fd,
03066        * and writes from alert_pipe fd */
03067       if (fds[0].revents) { /* there is data on the socket to be read */
03068          after_poll = 1;
03069 
03070          fds[0].revents = 0;
03071 
03072          /* clear request structure */
03073          str_save = req.data;
03074          memset(&req, 0, sizeof(req));
03075          req.data = str_save;
03076          ast_str_reset(req.data);
03077 
03078          str_save = reqcpy.data;
03079          memset(&reqcpy, 0, sizeof(reqcpy));
03080          reqcpy.data = str_save;
03081          ast_str_reset(reqcpy.data);
03082 
03083          memset(buf, 0, sizeof(buf));
03084 
03085          if (tcptls_session->ssl) {
03086             set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
03087             req.socket.port = htons(ourport_tls);
03088          } else {
03089             set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
03090             req.socket.port = htons(ourport_tcp);
03091          }
03092          req.socket.fd = tcptls_session->fd;
03093 
03094          /* Read in headers one line at a time */
03095          while (req.len < 4 || strncmp(REQ_OFFSET_TO_STR(&req, len - 4), "\r\n\r\n", 4)) {
03096             if (!tcptls_session->client && !authenticated ) {
03097                if ((timeout = sip_check_authtimeout(start)) < 0) {
03098                   goto cleanup;
03099                }
03100 
03101                if (timeout == 0) {
03102                   ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
03103                   goto cleanup;
03104                }
03105             } else {
03106                timeout = -1;
03107             }
03108 
03109             if (!tcptls_session->ssl || need_poll) {
03110                need_poll = 0;
03111                after_poll = 1;
03112                res = ast_wait_for_input(tcptls_session->fd, timeout);
03113                if (res < 0) {
03114                   ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
03115                   goto cleanup;
03116                } else if (res == 0) {
03117                   /* timeout */
03118                   ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
03119                   goto cleanup;
03120                }
03121             }
03122 
03123             ast_mutex_lock(&tcptls_session->lock);
03124             if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
03125                ast_mutex_unlock(&tcptls_session->lock);
03126                if (after_poll) {
03127                   goto cleanup;
03128                } else {
03129                   need_poll = 1;
03130                   continue;
03131                }
03132             }
03133             ast_mutex_unlock(&tcptls_session->lock);
03134             after_poll = 0;
03135             if (me->stop)
03136                 goto cleanup;
03137             ast_str_append(&req.data, 0, "%s", buf);
03138             req.len = req.data->used;
03139          }
03140          copy_request(&reqcpy, &req);
03141          parse_request(&reqcpy);
03142          /* In order to know how much to read, we need the content-length header */
03143          if (sscanf(get_header(&reqcpy, "Content-Length"), "%30d", &cl)) {
03144             while (cl > 0) {
03145                size_t bytes_read;
03146                if (!tcptls_session->client && !authenticated ) {
03147                   if ((timeout = sip_check_authtimeout(start)) < 0) {
03148                      goto cleanup;
03149                   }
03150 
03151                   if (timeout == 0) {
03152                      ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
03153                      goto cleanup;
03154                   }
03155                } else {
03156                   timeout = -1;
03157                }
03158 
03159                if (!tcptls_session->ssl || need_poll) {
03160                   res = ast_wait_for_input(tcptls_session->fd, timeout);
03161                   if (res < 0) {
03162                      ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
03163                      goto cleanup;
03164                   } else if (res == 0) {
03165                      /* timeout */
03166                      ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
03167                      goto cleanup;
03168                   }
03169                }
03170 
03171                ast_mutex_lock(&tcptls_session->lock);
03172                if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, cl), tcptls_session->f))) {
03173                   ast_mutex_unlock(&tcptls_session->lock);
03174                   if (after_poll) {
03175                      goto cleanup;
03176                   } else {
03177                      need_poll = 1;
03178                      continue;
03179                   }
03180                }
03181                buf[bytes_read] = '\0';
03182                ast_mutex_unlock(&tcptls_session->lock);
03183                after_poll = 0;
03184                if (me->stop)
03185                   goto cleanup;
03186                cl -= strlen(buf);
03187                ast_str_append(&req.data, 0, "%s", buf);
03188                req.len = req.data->used;
03189             }
03190          }
03191          /*! \todo XXX If there's no Content-Length or if the content-length and what
03192                we receive is not the same - we should generate an error */
03193 
03194          req.socket.tcptls_session = tcptls_session;
03195          handle_request_do(&req, &tcptls_session->remote_address);
03196       }
03197 
03198       if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
03199          enum sip_tcptls_alert alert;
03200          struct tcptls_packet *packet;
03201 
03202          fds[1].revents = 0;
03203 
03204          if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
03205             ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
03206             continue;
03207          }
03208 
03209          switch (alert) {
03210          case TCPTLS_ALERT_STOP:
03211             goto cleanup;
03212          case TCPTLS_ALERT_DATA:
03213             ao2_lock(me);
03214             if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
03215                ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty");
03216             }
03217             ao2_unlock(me);
03218 
03219             if (packet) {
03220                if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
03221                   ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
03222                }
03223                ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
03224             }
03225             break;
03226          default:
03227             ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
03228          }
03229       }
03230    }
03231 
03232    ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
03233 
03234 cleanup:
03235    if (tcptls_session && !tcptls_session->client && !authenticated) {
03236       ast_atomic_fetchadd_int(&unauth_sessions, -1);
03237    }
03238 
03239    if (me) {
03240       ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
03241       ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
03242    }
03243    deinit_req(&reqcpy);
03244    deinit_req(&req);
03245 
03246    /* if client, we own the parent session arguments and must decrement ref */
03247    if (ca) {
03248       ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
03249    }
03250 
03251    if (tcptls_session) {
03252       ast_mutex_lock(&tcptls_session->lock);
03253       if (tcptls_session->f) {
03254          fclose(tcptls_session->f);
03255          tcptls_session->f = NULL;
03256       }
03257       if (tcptls_session->fd != -1) {
03258          close(tcptls_session->fd);
03259          tcptls_session->fd = -1;
03260       }
03261       tcptls_session->parent = NULL;
03262       ast_mutex_unlock(&tcptls_session->lock);
03263 
03264       ao2_ref(tcptls_session, -1);
03265       tcptls_session = NULL;
03266    }
03267    return NULL;
03268 }
03269 
03270 #ifdef REF_DEBUG
03271 #define ref_peer(arg1,arg2) _ref_peer((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
03272 #define unref_peer(arg1,arg2) _unref_peer((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
03273 static struct sip_peer *_ref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
03274 {
03275    if (peer)
03276       _ao2_ref_debug(peer, 1, tag, file, line, func);
03277    else
03278       ast_log(LOG_ERROR, "Attempt to Ref a null peer pointer\n");
03279    return peer;
03280 }
03281 
03282 static struct sip_peer *_unref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
03283 {
03284    if (peer)
03285       _ao2_ref_debug(peer, -1, tag, file, line, func);
03286    return NULL;
03287 }
03288 #else
03289 /*!
03290  * helper functions to unreference various types of objects.
03291  * By handling them this way, we don't have to declare the
03292  * destructor on each call, which removes the chance of errors.
03293  */
03294 static void *unref_peer(struct sip_peer *peer, char *tag)
03295 {
03296    ao2_t_ref(peer, -1, tag);
03297    return NULL;
03298 }
03299 
03300 static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
03301 {
03302    ao2_t_ref(peer, 1, tag);
03303    return peer;
03304 }
03305 #endif /* REF_DEBUG */
03306 
03307 static void peer_sched_cleanup(struct sip_peer *peer)
03308 {
03309    if (peer->pokeexpire != -1) {
03310       AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
03311             unref_peer(peer, "removing poke peer ref"));
03312    }
03313    if (peer->expire != -1) {
03314       AST_SCHED_DEL_UNREF(sched, peer->expire,
03315             unref_peer(peer, "remove register expire ref"));
03316    }
03317 }
03318 
03319 typedef enum {
03320    SIP_PEERS_MARKED,
03321    SIP_PEERS_ALL,
03322 } peer_unlink_flag_t;
03323 
03324 /* this func is used with ao2_callback to unlink/delete all marked or linked
03325    peers, depending on arg */
03326 static int match_and_cleanup_peer_sched(void *peerobj, void *arg, int flags)
03327 {
03328    struct sip_peer *peer = peerobj;
03329    peer_unlink_flag_t which = *(peer_unlink_flag_t *)arg;
03330 
03331    if (which == SIP_PEERS_ALL || peer->the_mark) {
03332       peer_sched_cleanup(peer);
03333       return CMP_MATCH;
03334    }
03335    return 0;
03336 }
03337 
03338 static void unlink_peers_from_tables(peer_unlink_flag_t flag)
03339 {
03340    ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
03341       match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
03342    ao2_t_callback(peers_by_ip, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
03343       match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
03344 }
03345 
03346 /* \brief Unlink all marked peers from ao2 containers */
03347 static void unlink_marked_peers_from_tables(void)
03348 {
03349    unlink_peers_from_tables(SIP_PEERS_MARKED);
03350 }
03351 
03352 static void unlink_all_peers_from_tables(void)
03353 {
03354    unlink_peers_from_tables(SIP_PEERS_ALL);
03355 }
03356 
03357 /* \brief Unlink single peer from all ao2 containers */
03358 static void unlink_peer_from_tables(struct sip_peer *peer)
03359 {
03360    ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
03361    if (peer->addr.sin_addr.s_addr) {
03362       ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
03363    }
03364 }
03365 
03366 /*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
03367  *
03368  * This function sets pvt's outboundproxy pointer to the one referenced
03369  * by the proxy parameter. Because proxy may be a refcounted object, and
03370  * because pvt's old outboundproxy may also be a refcounted object, we need
03371  * to maintain the proper refcounts.
03372  *
03373  * \param pvt The sip_pvt for which we wish to set the outboundproxy
03374  * \param proxy The sip_proxy which we will point pvt towards.
03375  * \return Returns void
03376  */
03377 static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
03378 {
03379    struct sip_proxy *old_obproxy = pvt->outboundproxy;
03380    /* The sip_cfg.outboundproxy is statically allocated, and so
03381     * we don't ever need to adjust refcounts for it
03382     */
03383    if (proxy && proxy != &sip_cfg.outboundproxy) {
03384       ao2_ref(proxy, +1);
03385    }
03386    pvt->outboundproxy = proxy;
03387    if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
03388       ao2_ref(old_obproxy, -1);
03389    }
03390 }
03391 
03392 /*!
03393  * \brief Unlink a dialog from the dialogs container, as well as any other places
03394  * that it may be currently stored.
03395  *
03396  * \note A reference to the dialog must be held before calling this function, and this
03397  * function does not release that reference.
03398  */
03399 static void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist)
03400 {
03401    struct sip_pkt *cp;
03402 
03403    dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
03404 
03405    ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
03406 
03407    /* Unlink us from the owner (channel) if we have one */
03408    if (dialog->owner) {
03409       if (lockowner)
03410          ast_channel_lock(dialog->owner);
03411       ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
03412       dialog->owner->tech_pvt = dialog_unref(dialog->owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
03413       if (lockowner)
03414          ast_channel_unlock(dialog->owner);
03415    }
03416    if (dialog->registry) {
03417       if (dialog->registry->call == dialog)
03418          dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
03419       dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
03420    }
03421    if (dialog->stateid > -1) {
03422       ast_extension_state_del(dialog->stateid, NULL);
03423       dialog_unref(dialog, "removing extension_state, should unref the associated dialog ptr that was stored there.");
03424       dialog->stateid = -1; /* shouldn't we 'zero' this out? */
03425    }
03426    /* Remove link from peer to subscription of MWI */
03427    if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog)
03428       dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
03429    if (dialog->relatedpeer && dialog->relatedpeer->call == dialog)
03430       dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
03431 
03432    /* remove all current packets in this dialog */
03433    while((cp = dialog->packets)) {
03434       dialog->packets = dialog->packets->next;
03435       AST_SCHED_DEL(sched, cp->retransid);
03436       dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
03437       if (cp->data) {
03438          ast_free(cp->data);
03439       }
03440       ast_free(cp);
03441    }
03442 
03443    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"));
03444 
03445    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"));
03446    
03447    if (dialog->autokillid > -1)
03448       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"));
03449 
03450    if (dialog->request_queue_sched_id > -1) {
03451       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"));
03452    }
03453 
03454    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"));
03455 
03456    if (dialog->t38id > -1) {
03457       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"));
03458    }
03459 
03460    if (dialog->stimer) {
03461       stop_session_timer(dialog);
03462    }
03463 
03464    dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
03465    return NULL;
03466 }
03467 
03468 static void *registry_unref(struct sip_registry *reg, char *tag)
03469 {
03470    ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
03471    ASTOBJ_UNREF(reg, sip_registry_destroy);
03472    return NULL;
03473 }
03474 
03475 /*! \brief Add object reference to SIP registry */
03476 static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
03477 {
03478    ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
03479    return ASTOBJ_REF(reg); /* Add pointer to registry in packet */
03480 }
03481 
03482 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
03483 static struct ast_udptl_protocol sip_udptl = {
03484    type: "SIP",
03485    get_udptl_info: sip_get_udptl_peer,
03486    set_udptl_peer: sip_set_udptl_peer,
03487 };
03488 
03489 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03490    __attribute__((format(printf, 2, 3)));
03491 
03492 
03493 /*! \brief Convert transfer status to string */
03494 static const char *referstatus2str(enum referstatus rstatus)
03495 {
03496    return map_x_s(referstatusstrings, rstatus, "");
03497 }
03498 
03499 static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
03500 {
03501    append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
03502    pvt->needdestroy = 1;
03503 }
03504 
03505 /*! \brief Initialize the initital request packet in the pvt structure.
03506    This packet is used for creating replies and future requests in
03507    a dialog */
03508 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
03509 {
03510    if (p->initreq.headers)
03511       ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
03512    else
03513       ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
03514    /* Use this as the basis */
03515    copy_request(&p->initreq, req);
03516    parse_request(&p->initreq);
03517    if (req->debug)
03518       ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
03519 }
03520 
03521 /*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
03522 static void sip_alreadygone(struct sip_pvt *dialog)
03523 {
03524    ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
03525    dialog->alreadygone = 1;
03526 }
03527 
03528 /*! Resolve DNS srv name or host name in a sip_proxy structure */
03529 static int proxy_update(struct sip_proxy *proxy)
03530 {
03531    /* if it's actually an IP address and not a name,
03532            there's no need for a managed lookup */
03533    if (!inet_aton(proxy->name, &proxy->ip.sin_addr)) {
03534       /* Ok, not an IP address, then let's check if it's a domain or host */
03535       /* XXX Todo - if we have proxy port, don't do SRV */
03536       if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
03537          ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
03538          return FALSE;
03539       }
03540    }
03541    proxy->last_dnsupdate = time(NULL);
03542    return TRUE;
03543 }
03544 
03545 /*! \brief converts ascii port to int representation. If no
03546  *  pt buffer is provided or the pt has errors when being converted
03547  *  to an int value, the port provided as the standard is used.
03548  */
03549 static int port_str2int(const char *pt, unsigned int standard)
03550 {
03551    int port = standard;
03552    if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
03553       port = standard;
03554    }
03555 
03556    return port;
03557 }
03558 
03559 /*! \brief Allocate and initialize sip proxy */
03560 static struct sip_proxy *proxy_allocate(char *name, char *port, int force)
03561 {
03562    struct sip_proxy *proxy;
03563 
03564    if (ast_strlen_zero(name)) {
03565       return NULL;
03566    }
03567 
03568    proxy = ao2_alloc(sizeof(*proxy), NULL);
03569    if (!proxy)
03570       return NULL;
03571    proxy->force = force;
03572    ast_copy_string(proxy->name, name, sizeof(proxy->name));
03573    proxy->ip.sin_port = htons(port_str2int(port, STANDARD_SIP_PORT));
03574    proxy->ip.sin_family = AF_INET;
03575    proxy_update(proxy);
03576    return proxy;
03577 }
03578 
03579 /*! \brief Get default outbound proxy or global proxy */
03580 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
03581 {
03582    if (peer && peer->outboundproxy) {
03583       if (sipdebug)
03584          ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
03585       append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
03586       return peer->outboundproxy;
03587    }
03588    if (sip_cfg.outboundproxy.name[0]) {
03589       if (sipdebug)
03590          ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
03591       append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
03592       return &sip_cfg.outboundproxy;
03593    }
03594    if (sipdebug)
03595       ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
03596    return NULL;
03597 }
03598 
03599 /*! \brief returns true if 'name' (with optional trailing whitespace)
03600  * matches the sip method 'id'.
03601  * Strictly speaking, SIP methods are case SENSITIVE, but we do
03602  * a case-insensitive comparison to be more tolerant.
03603  * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
03604  */
03605 static int method_match(enum sipmethod id, const char *name)
03606 {
03607    int len = strlen(sip_methods[id].text);
03608    int l_name = name ? strlen(name) : 0;
03609    /* true if the string is long enough, and ends with whitespace, and matches */
03610    return (l_name >= len && name[len] < 33 &&
03611       !strncasecmp(sip_methods[id].text, name, len));
03612 }
03613 
03614 /*! \brief  find_sip_method: Find SIP method from header */
03615 static int find_sip_method(const char *msg)
03616 {
03617    int i, res = 0;
03618    
03619    if (ast_strlen_zero(msg))
03620       return 0;
03621    for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
03622       if (method_match(i, msg))
03623          res = sip_methods[i].id;
03624    }
03625    return res;
03626 }
03627 
03628 /*! \brief Parse supported header in incoming packet */
03629 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
03630 {
03631    char *next, *sep;
03632    char *temp;
03633    unsigned int profile = 0;
03634    int i, found;
03635 
03636    if (ast_strlen_zero(supported) )
03637       return 0;
03638    temp = ast_strdupa(supported);
03639 
03640    if (sipdebug)
03641       ast_debug(3, "Begin: parsing SIP \"Supported: %s\"\n", supported);
03642 
03643    for (next = temp; next; next = sep) {
03644       found = FALSE;
03645       if ( (sep = strchr(next, ',')) != NULL)
03646          *sep++ = '\0';
03647       next = ast_skip_blanks(next);
03648       if (sipdebug)
03649          ast_debug(3, "Found SIP option: -%s-\n", next);
03650       for (i = 0; i < ARRAY_LEN(sip_options); i++) {
03651          if (!strcasecmp(next, sip_options[i].text)) {
03652             profile |= sip_options[i].id;
03653             found = TRUE;
03654             if (sipdebug)
03655                ast_debug(3, "Matched SIP option: %s\n", next);
03656             break;
03657          }
03658       }
03659 
03660       /* This function is used to parse both Suported: and Require: headers.
03661       Let the caller of this function know that an unknown option tag was 
03662       encountered, so that if the UAC requires it then the request can be 
03663       rejected with a 420 response. */
03664       if (!found)
03665          profile |= SIP_OPT_UNKNOWN;
03666 
03667       if (!found && sipdebug) {
03668          if (!strncasecmp(next, "x-", 2))
03669             ast_debug(3, "Found private SIP option, not supported: %s\n", next);
03670          else
03671             ast_debug(3, "Found no match for SIP option: %s (Please file bug report!)\n", next);
03672       }
03673    }
03674 
03675    if (pvt)
03676       pvt->sipoptions = profile;
03677    return profile;
03678 }
03679 
03680 /*! \brief See if we pass debug IP filter */
03681 static inline int sip_debug_test_addr(const struct sockaddr_in *addr) 
03682 {
03683    if (!sipdebug)
03684       return 0;
03685    if (debugaddr.sin_addr.s_addr) {
03686       if (((ntohs(debugaddr.sin_port) != 0)
03687          && (debugaddr.sin_port != addr->sin_port))
03688          || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
03689          return 0;
03690    }
03691    return 1;
03692 }
03693 
03694 /*! \brief The real destination address for a write */
03695 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
03696 {
03697    if (p->outboundproxy)
03698       return &p->outboundproxy->ip;
03699 
03700    return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
03701 }
03702 
03703 /*! \brief Display SIP nat mode */
03704 static const char *sip_nat_mode(const struct sip_pvt *p)
03705 {
03706    return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
03707 }
03708 
03709 /*! \brief Test PVT for debugging output */
03710 static inline int sip_debug_test_pvt(struct sip_pvt *p) 
03711 {
03712    if (!sipdebug)
03713       return 0;
03714    return sip_debug_test_addr(sip_real_dst(p));
03715 }
03716 
03717 /*! \brief Return int representing a bit field of transport types found in const char *transport */
03718 static int get_transport_str2enum(const char *transport)
03719 {
03720    int res = 0;
03721 
03722    if (ast_strlen_zero(transport)) {
03723       return res;
03724    }
03725 
03726    if (!strcasecmp(transport, "udp")) {
03727       res |= SIP_TRANSPORT_UDP;
03728    }
03729    if (!strcasecmp(transport, "tcp")) {
03730       res |= SIP_TRANSPORT_TCP;
03731    }
03732    if (!strcasecmp(transport, "tls")) {
03733       res |= SIP_TRANSPORT_TLS;
03734    }
03735 
03736    return res;
03737 }
03738 
03739 /*! \brief Return configuration of transports for a device */
03740 static inline const char *get_transport_list(unsigned int transports) {
03741    switch (transports) {
03742       case SIP_TRANSPORT_UDP:
03743          return "UDP";
03744       case SIP_TRANSPORT_TCP:
03745          return "TCP";
03746       case SIP_TRANSPORT_TLS:
03747          return "TLS";
03748       case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
03749          return "TCP,UDP";
03750       case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
03751          return "TLS,UDP";
03752       case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
03753          return "TLS,TCP";
03754       default:
03755          return transports ? 
03756             "TLS,TCP,UDP" : "UNKNOWN"; 
03757    }
03758 }
03759 
03760 /*! \brief Return transport as string */
03761 static inline const char *get_transport(enum sip_transport t)
03762 {
03763    switch (t) {
03764    case SIP_TRANSPORT_UDP:
03765       return "UDP";
03766    case SIP_TRANSPORT_TCP:
03767       return "TCP";
03768    case SIP_TRANSPORT_TLS:
03769       return "TLS";
03770    }
03771 
03772    return "UNKNOWN";
03773 }
03774 
03775 /*! \brief Return protocol string for srv dns query */
03776 static inline const char *get_srv_protocol(enum sip_transport t)
03777 {
03778    switch (t) {
03779    case SIP_TRANSPORT_UDP:
03780       return "udp";
03781    case SIP_TRANSPORT_TLS:
03782    case SIP_TRANSPORT_TCP:
03783       return "tcp";
03784    }
03785 
03786    return "udp";
03787 }
03788 
03789 /*! \brief Return service string for srv dns query */
03790 static inline const char *get_srv_service(enum sip_transport t)
03791 {
03792    switch (t) {
03793    case SIP_TRANSPORT_TCP:
03794    case SIP_TRANSPORT_UDP:
03795       return "sip";
03796    case SIP_TRANSPORT_TLS:
03797       return "sips";
03798    }
03799    return "sip";
03800 }
03801 
03802 /*! \brief Return transport of dialog.
03803    \note this is based on a false assumption. We don't always use the
03804    outbound proxy for all requests in a dialog. It depends on the
03805    "force" parameter. The FIRST request is always sent to the ob proxy.
03806    \todo Fix this function to work correctly
03807 */
03808 static inline const char *get_transport_pvt(struct sip_pvt *p)
03809 {
03810    if (p->outboundproxy && p->outboundproxy->transport) {
03811       set_socket_transport(&p->socket, p->outboundproxy->transport);
03812    }
03813 
03814    return get_transport(p->socket.type);
03815 }
03816 
03817 /*! \brief Transmit SIP message 
03818    Sends a SIP request or response on a given socket (in the pvt)
03819    Called by retrans_pkt, send_request, send_response and 
03820    __sip_reliable_xmit
03821 */
03822 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len)
03823 {
03824    int res = 0;
03825    const struct sockaddr_in *dst = sip_real_dst(p);
03826 
03827    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));
03828 
03829    if (sip_prepare_socket(p) < 0)
03830       return XMIT_ERROR;
03831 
03832    if (p->socket.type == SIP_TRANSPORT_UDP) {
03833       res = sendto(p->socket.fd, data->str, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
03834    } else if (p->socket.tcptls_session) {
03835       res = sip_tcptls_write(p->socket.tcptls_session, data->str, len);
03836    } else {
03837       ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
03838       return XMIT_ERROR;
03839    }
03840 
03841    if (res == -1) {
03842       switch (errno) {
03843       case EBADF:       /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
03844       case EHOSTUNREACH:   /* Host can't be reached */
03845       case ENETDOWN:       /* Inteface down */
03846       case ENETUNREACH: /* Network failure */
03847       case ECONNREFUSED:      /* ICMP port unreachable */ 
03848          res = XMIT_ERROR; /* Don't bother with trying to transmit again */
03849       }
03850    }
03851    if (res != len)
03852       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));
03853 
03854    return res;
03855 }
03856 
03857 /*! \brief Build a Via header for a request */
03858 static void build_via(struct sip_pvt *p)
03859 {
03860    /* Work around buggy UNIDEN UIP200 firmware */
03861    const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
03862 
03863    /* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
03864    snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s:%d;branch=z9hG4bK%08x%s",
03865        get_transport_pvt(p),
03866        ast_inet_ntoa(p->ourip.sin_addr),
03867        ntohs(p->ourip.sin_port), (int) p->branch, rport);
03868 }
03869 
03870 /*! \brief NAT fix - decide which IP address to use for Asterisk server?
03871  *
03872  * Using the localaddr structure built up with localnet statements in sip.conf
03873  * apply it to their address to see if we need to substitute our
03874  * externip or can get away with our internal bindaddr
03875  * 'us' is always overwritten.
03876  */
03877 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p)
03878 {
03879    struct sockaddr_in theirs;
03880    /* Set want_remap to non-zero if we want to remap 'us' to an externally
03881     * reachable IP address and port. This is done if:
03882     * 1. we have a localaddr list (containing 'internal' addresses marked
03883     *    as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
03884     *    and AST_SENSE_ALLOW on 'external' ones);
03885     * 2. either stunaddr or externip is set, so we know what to use as the
03886     *    externally visible address;
03887     * 3. the remote address, 'them', is external;
03888     * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
03889     *    when passed to ast_apply_ha() so it does need to be remapped.
03890     *    This fourth condition is checked later.
03891     */
03892    int want_remap;
03893 
03894    *us = internip;      /* starting guess for the internal address */
03895    /* now ask the system what would it use to talk to 'them' */
03896    ast_ouraddrfor(them, &us->sin_addr);
03897    theirs.sin_addr = *them;
03898 
03899    want_remap = localaddr &&
03900       (externip.sin_addr.s_addr || stunaddr.sin_addr.s_addr) &&
03901       ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
03902 
03903    if (want_remap &&
03904        (!sip_cfg.matchexterniplocally || !ast_apply_ha(localaddr, us)) ) {
03905       /* if we used externhost or stun, see if it is time to refresh the info */
03906       if (externexpire && time(NULL) >= externexpire) {
03907          if (stunaddr.sin_addr.s_addr) {
03908             ast_stun_request(sipsock, &stunaddr, NULL, &externip);
03909          } else {
03910             if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
03911                ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
03912          }
03913          externexpire = time(NULL) + externrefresh;
03914       }
03915       if (externip.sin_addr.s_addr)
03916          *us = externip;
03917       else
03918          ast_log(LOG_WARNING, "stun failed\n");
03919       ast_debug(1, "Target address %s is not local, substituting externip\n", 
03920          ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
03921    } else if (p) {
03922       /* no remapping, but we bind to a specific address, so use it. */
03923       switch (p->socket.type) {
03924       case SIP_TRANSPORT_TCP:
03925          if (sip_tcp_desc.local_address.sin_addr.s_addr) {
03926             *us = sip_tcp_desc.local_address;
03927          } else {
03928             us->sin_port = sip_tcp_desc.local_address.sin_port;
03929          }
03930          break;
03931       case SIP_TRANSPORT_TLS:
03932          if (sip_tls_desc.local_address.sin_addr.s_addr) {
03933             *us = sip_tls_desc.local_address;
03934          } else {
03935             us->sin_port = sip_tls_desc.local_address.sin_port;
03936          }
03937             break;
03938       case SIP_TRANSPORT_UDP:
03939          /* fall through on purpose */
03940       default:
03941          if (bindaddr.sin_addr.s_addr) {
03942             *us = bindaddr;
03943          }
03944       }
03945    } else if (bindaddr.sin_addr.s_addr) {
03946       *us = bindaddr;
03947    }
03948    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));
03949 }
03950 
03951 /*! \brief Append to SIP dialog history with arg list  */
03952 static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
03953 {
03954    char buf[80], *c = buf; /* max history length */
03955    struct sip_history *hist;
03956    int l;
03957 
03958    vsnprintf(buf, sizeof(buf), fmt, ap);
03959    strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
03960    l = strlen(buf) + 1;
03961    if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
03962       return;
03963    if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
03964       ast_free(hist);
03965       return;
03966    }
03967    memcpy(hist->event, buf, l);
03968    if (p->history_entries == MAX_HISTORY_ENTRIES) {
03969       struct sip_history *oldest;
03970       oldest = AST_LIST_REMOVE_HEAD(p->history, list);
03971       p->history_entries--;
03972       ast_free(oldest);
03973    }
03974    AST_LIST_INSERT_TAIL(p->history, hist, list);
03975    p->history_entries++;
03976 }
03977 
03978 /*! \brief Append to SIP dialog history with arg list  */
03979 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03980 {
03981    va_list ap;
03982 
03983    if (!p)
03984       return;
03985 
03986    if (!p->do_history && !recordhistory && !dumphistory)
03987       return;
03988 
03989    va_start(ap, fmt);
03990    append_history_va(p, fmt, ap);
03991    va_end(ap);
03992 
03993    return;
03994 }
03995 
03996 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
03997 static int retrans_pkt(const void *data)
03998 {
03999    struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
04000    int reschedule = DEFAULT_RETRANS;
04001    int xmitres = 0;
04002 
04003    /* Lock channel PVT */
04004    sip_pvt_lock(pkt->owner);
04005 
04006    if (pkt->retrans < MAX_RETRANS) {
04007       pkt->retrans++;
04008       if (!pkt->timer_t1) {   /* Re-schedule using timer_a and timer_t1 */
04009          if (sipdebug)
04010             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);
04011       } else {
04012          int siptimer_a;
04013 
04014          if (sipdebug)
04015             ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
04016          if (!pkt->timer_a)
04017             pkt->timer_a = 2 ;
04018          else
04019             pkt->timer_a = 2 * pkt->timer_a;
04020 
04021          /* For non-invites, a maximum of 4 secs */
04022          siptimer_a = pkt->timer_t1 * pkt->timer_a;   /* Double each time */
04023          if (pkt->method != SIP_INVITE && siptimer_a > 4000)
04024             siptimer_a = 4000;
04025 
04026          /* Reschedule re-transmit */
04027          reschedule = siptimer_a;
04028          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);
04029       }
04030 
04031       if (sip_debug_test_pvt(pkt->owner)) {
04032          const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
04033          ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
04034             pkt->retrans, sip_nat_mode(pkt->owner),
04035             ast_inet_ntoa(dst->sin_addr),
04036             ntohs(dst->sin_port), pkt->data->str);
04037       }
04038 
04039       append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
04040       xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
04041       if (xmitres == XMIT_ERROR) {
04042          ast_log(LOG_WARNING, "Network error on retransmit in dialog %s\n", pkt->owner->callid);
04043       } else {
04044          sip_pvt_unlock(pkt->owner);
04045          return  reschedule;
04046       }
04047    }
04048    /* Too many retries */
04049    if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
04050       if (pkt->is_fatal || sipdebug)   /* Tell us if it's critical or if we're debugging */
04051          ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s) -- See https://wiki.asterisk.org/wiki/display/AST/SIP+Retransmissions \n",
04052             pkt->owner->callid, pkt->seqno,
04053             pkt->is_fatal ? "Critical" : "Non-critical", pkt->is_resp ? "Response" : "Request");
04054    } else if (pkt->method == SIP_OPTIONS && sipdebug) {
04055          ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s)  -- See https://wiki.asterisk.org/wiki/display/AST/SIP+Retransmissions \n", pkt->owner->callid);
04056 
04057    }
04058    if (xmitres == XMIT_ERROR) {
04059       ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
04060       append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
04061    } else {
04062       append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
04063    }
04064    pkt->retransid = -1;
04065 
04066    if (pkt->is_fatal) {
04067       while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
04068          sip_pvt_unlock(pkt->owner);   /* SIP_PVT, not channel */
04069          usleep(1);
04070          sip_pvt_lock(pkt->owner);
04071       }
04072 
04073       if (pkt->owner->owner && !pkt->owner->owner->hangupcause)
04074          pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
04075 
04076       if (pkt->owner->owner) {
04077          sip_alreadygone(pkt->owner);
04078          ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet (see https://wiki.asterisk.org/wiki/display/AST/SIP+Retransmissions ).\n", pkt->owner->callid);
04079          ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_PROTOCOL_ERROR);
04080          ast_channel_unlock(pkt->owner->owner);
04081       } else {
04082          /* If no channel owner, destroy now */
04083 
04084          /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
04085          if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
04086             pvt_set_needdestroy(pkt->owner, "no response to critical packet");
04087             sip_alreadygone(pkt->owner);
04088             append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
04089          }
04090       }
04091    }
04092 
04093    if (pkt->method == SIP_BYE) {
04094       /* We're not getting answers on SIP BYE's.  Tear down the call anyway. */
04095       sip_alreadygone(pkt->owner);
04096       if (pkt->owner->owner)
04097          ast_channel_unlock(pkt->owner->owner);
04098       append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
04099       pvt_set_needdestroy(pkt->owner, "no response to BYE");
04100    }
04101 
04102    /* Remove the packet */
04103    for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
04104       if (cur == pkt) {
04105          UNLINK(cur, pkt->owner->packets, prev);
04106          sip_pvt_unlock(pkt->owner);
04107          if (pkt->owner)
04108             pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
04109          if (pkt->data)
04110             ast_free(pkt->data);
04111          pkt->data = NULL;
04112          ast_free(pkt);
04113          return 0;
04114       }
04115    }
04116    /* error case */
04117    ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
04118    sip_pvt_unlock(pkt->owner);
04119    return 0;
04120 }
04121 
04122 /*! \brief Transmit packet with retransmits 
04123    \return 0 on success, -1 on failure to allocate packet 
04124 */
04125 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)
04126 {
04127    struct sip_pkt *pkt = NULL;
04128    int siptimer_a = DEFAULT_RETRANS;
04129    int xmitres = 0;
04130    int respid;
04131 
04132    if (sipmethod == SIP_INVITE) {
04133       /* Note this is a pending invite */
04134       p->pendinginvite = seqno;
04135    }
04136 
04137    /* If the transport is something reliable (TCP or TLS) then don't really send this reliably */
04138    /* I removed the code from retrans_pkt that does the same thing so it doesn't get loaded into the scheduler */
04139    /*! \todo According to the RFC some packets need to be retransmitted even if its TCP, so this needs to get revisited */
04140    if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
04141       xmitres = __sip_xmit(p, data, len); /* Send packet */
04142       if (xmitres == XMIT_ERROR) {  /* Serious network trouble, no need to try again */
04143          append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
04144          return AST_FAILURE;
04145       } else {
04146          return AST_SUCCESS;
04147       }
04148    }
04149 
04150    if (!(pkt = ast_calloc(1, sizeof(*pkt))))
04151       return AST_FAILURE;
04152    /* copy data, add a terminator and save length */
04153    if (!(pkt->data = ast_str_create(len))) {
04154       ast_free(pkt);
04155       return AST_FAILURE;
04156    }
04157    ast_str_set(&pkt->data, 0, "%s%s", data->str, "\0");
04158    pkt->packetlen = len;
04159    /* copy other parameters from the caller */
04160    pkt->method = sipmethod;
04161    pkt->seqno = seqno;
04162    pkt->is_resp = resp;
04163    pkt->is_fatal = fatal;
04164    pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
04165    pkt->next = p->packets;
04166    p->packets = pkt; /* Add it to the queue */
04167    if (resp) {
04168       /* Parse out the response code */
04169       if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
04170          pkt->response_code = respid;
04171       }
04172    }
04173    pkt->timer_t1 = p->timer_t1;  /* Set SIP timer T1 */
04174    pkt->retransid = -1;
04175    if (pkt->timer_t1)
04176       siptimer_a = pkt->timer_t1 * 2;
04177 
04178    /* Schedule retransmission */
04179    AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
04180    if (sipdebug)
04181       ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id  #%d\n", pkt->retransid);
04182 
04183    xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);   /* Send packet */
04184 
04185    if (xmitres == XMIT_ERROR) {  /* Serious network trouble, no need to try again */
04186       append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
04187       ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
04188       AST_SCHED_DEL(sched, pkt->retransid);
04189       p->packets = pkt->next;
04190       pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
04191       ast_free(pkt->data);
04192       ast_free(pkt);
04193       return AST_FAILURE;
04194    } else {
04195       return AST_SUCCESS;
04196    }
04197 }
04198 
04199 /*! \brief Kill a SIP dialog (called only by the scheduler)
04200  * The scheduler has a reference to this dialog when p->autokillid != -1,
04201  * and we are called using that reference. So if the event is not
04202  * rescheduled, we need to call dialog_unref().
04203  */
04204 static int __sip_autodestruct(const void *data)
04205 {
04206    struct sip_pvt *p = (struct sip_pvt *)data;
04207 
04208    /* If this is a subscription, tell the phone that we got a timeout */
04209    if (p->subscribed) {
04210       transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);  /* Send last notification */
04211       p->subscribed = NONE;
04212       append_history(p, "Subscribestatus", "timeout");
04213       ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
04214       return 10000;  /* Reschedule this destruction so that we know that it's gone */
04215    }
04216 
04217    /* If there are packets still waiting for delivery, delay the destruction */
04218    if (p->packets) {
04219       if (!p->needdestroy) {
04220          char method_str[31];
04221          ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
04222          append_history(p, "ReliableXmit", "timeout");
04223          if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
04224             if (method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
04225                pvt_set_needdestroy(p, "autodestruct");
04226             }
04227          }
04228          return 10000;
04229       } else {
04230          /* They've had their chance to respond. Time to bail */
04231          __sip_pretend_ack(p);
04232       }
04233    }
04234 
04235    /* Reset schedule ID */
04236    p->autokillid = -1;
04237 
04238 
04239    /*
04240     * Lock both the pvt and the channel safely so that we can queue up a frame.
04241     */
04242    sip_pvt_lock(p);
04243    while (p->owner && ast_channel_trylock(p->owner)) {
04244       sip_pvt_unlock(p);
04245       sched_yield();
04246       sip_pvt_lock(p);
04247    }
04248 
04249    if (p->owner) {
04250       ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
04251       ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
04252       ast_channel_unlock(p->owner);
04253    } else if (p->refer && !p->alreadygone) {
04254       ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
04255       transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
04256       append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
04257       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
04258    } else {
04259       append_history(p, "AutoDestroy", "%s", p->callid);
04260       ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
04261       dialog_unlink_all(p, TRUE, TRUE); /* once it's unlinked and unrefd everywhere, it'll be freed automagically */
04262       /* dialog_unref(p, "unref dialog-- no other matching conditions"); -- unlink all now should finish off the dialog's references and free it. */
04263       /* sip_destroy(p); */      /* Go ahead and destroy dialog. All attempts to recover is done */
04264       /* sip_destroy also absorbs the reference */
04265    }
04266 
04267    sip_pvt_unlock(p);
04268 
04269    dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
04270 
04271    return 0;
04272 }
04273 
04274 /*! \brief Schedule destruction of SIP dialog */
04275 static void sip_scheddestroy(struct sip_pvt *p, int ms)
04276 {
04277    if (ms < 0) {
04278       if (p->timer_t1 == 0) {
04279          p->timer_t1 = global_t1;   /* Set timer T1 if not set (RFC 3261) */
04280          p->timer_b = global_timer_b;  /* Set timer B if not set (RFC 3261) */
04281       }
04282       ms = p->timer_t1 * 64;
04283    }
04284    if (sip_debug_test_pvt(p))
04285       ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
04286    if (sip_cancel_destroy(p))
04287       ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
04288 
04289    if (p->do_history)
04290       append_history(p, "SchedDestroy", "%d ms", ms);
04291    p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
04292 
04293    if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0)
04294       stop_session_timer(p);
04295 }
04296 
04297 /*! \brief Cancel destruction of SIP dialog.
04298  * Be careful as this also absorbs the reference - if you call it
04299  * from within the scheduler, this might be the last reference.
04300  */
04301 static int sip_cancel_destroy(struct sip_pvt *p)
04302 {
04303    if (p->autokillid > -1) {
04304       append_history(p, "CancelDestroy", "");
04305       AST_SCHED_DEL_UNREF(sched, p->autokillid, dialog_unref(p, "remove ref for autokillid"));
04306    }
04307    return 0;
04308 }
04309 
04310 /*! \brief Acknowledges receipt of a packet and stops retransmission 
04311  * called with p locked*/
04312 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
04313 {
04314    struct sip_pkt *cur, *prev = NULL;
04315    const char *msg = "Not Found";   /* used only for debugging */
04316    int res = FALSE;
04317 
04318    /* If we have an outbound proxy for this dialog, then delete it now since
04319      the rest of the requests in this dialog needs to follow the routing.
04320      If obforcing is set, we will keep the outbound proxy during the whole
04321      dialog, regardless of what the SIP rfc says
04322    */
04323    if (p->outboundproxy && !p->outboundproxy->force){
04324       ref_proxy(p, NULL);
04325    }
04326 
04327    for (cur = p->packets; cur; prev = cur, cur = cur->next) {
04328       if (cur->seqno != seqno || cur->is_resp != resp)
04329          continue;
04330       if (cur->is_resp || cur->method == sipmethod) {
04331          res = TRUE;
04332          msg = "Found";
04333          if (!resp && (seqno == p->pendinginvite)) {
04334             ast_debug(1, "Acked pending invite %d\n", p->pendinginvite);
04335             p->pendinginvite = 0;
04336          }
04337          if (cur->retransid > -1) {
04338             if (sipdebug)
04339                ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
04340          }
04341          /* This odd section is designed to thwart a 
04342           * race condition in the packet scheduler. There are
04343           * two conditions under which deleting the packet from the
04344           * scheduler can fail.
04345           *
04346           * 1. The packet has been removed from the scheduler because retransmission
04347           * is being attempted. The problem is that if the packet is currently attempting
04348           * retransmission and we are at this point in the code, then that MUST mean
04349           * that retrans_pkt is waiting on p's lock. Therefore we will relinquish the
04350           * lock temporarily to allow retransmission.
04351           *
04352           * 2. The packet has reached its maximum number of retransmissions and has
04353           * been permanently removed from the packet scheduler. If this is the case, then
04354           * the packet's retransid will be set to -1. The atomicity of the setting and checking
04355           * of the retransid to -1 is ensured since in both cases p's lock is held.
04356           */
04357          while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
04358             sip_pvt_unlock(p);
04359             usleep(1);
04360             sip_pvt_lock(p);
04361          }
04362          UNLINK(cur, p->packets, prev);
04363          dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
04364          if (cur->data)
04365             ast_free(cur->data);
04366          ast_free(cur);
04367          break;
04368       }
04369    }
04370    ast_debug(1, "Stopping retransmission on '%s' of %s %d: Match %s\n",
04371       p->callid, resp ? "Response" : "Request", seqno, msg);
04372    return res;
04373 }
04374 
04375 /*! \brief Pretend to ack all packets
04376  * called with p locked */
04377 static void __sip_pretend_ack(struct sip_pvt *p)
04378 {
04379    struct sip_pkt *cur = NULL;
04380 
04381    while (p->packets) {
04382       int method;
04383       if (cur == p->packets) {
04384          ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
04385          return;
04386       }
04387       cur = p->packets;
04388       method = (cur->method) ? cur->method : find_sip_method(cur->data->str);
04389       __sip_ack(p, cur->seqno, cur->is_resp, method);
04390    }
04391 }
04392 
04393 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
04394 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
04395 {
04396    struct sip_pkt *cur;
04397    int res = FALSE;
04398 
04399    for (cur = p->packets; cur; cur = cur->next) {
04400       if (cur->seqno == seqno && cur->is_resp == resp &&
04401          (cur->is_resp || method_match(sipmethod, cur->data->str))) {
04402          /* this is our baby */
04403          if (cur->retransid > -1) {
04404             if (sipdebug)
04405                ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
04406          }
04407          AST_SCHED_DEL(sched, cur->retransid);
04408          res = TRUE;
04409          break;
04410       }
04411    }
04412    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");
04413    return res;
04414 }
04415 
04416 
04417 /*! \brief Copy SIP request, parse it */
04418 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
04419 {
04420    copy_request(dst, src);
04421    parse_request(dst);
04422 }
04423 
04424 /*! \brief add a blank line if no body */
04425 static void add_blank(struct sip_request *req)
04426 {
04427    if (!req->lines) {
04428       /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
04429       ast_str_append(&req->data, 0, "\r\n");
04430       req->len = ast_str_strlen(req->data);
04431    }
04432 }
04433 
04434 static int send_provisional_keepalive_full(struct sip_pvt *pvt, int with_sdp)
04435 {
04436    const char *msg = NULL;
04437 
04438    if (!pvt->last_provisional || !strncasecmp(pvt->last_provisional, "100", 3)) {
04439       msg = "183 Session Progress";
04440    }
04441 
04442    if (pvt->invitestate < INV_COMPLETED) {
04443       if (with_sdp) {
04444          transmit_response_with_sdp(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq, XMIT_UNRELIABLE, FALSE);
04445       } else {
04446          transmit_response(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq);
04447       }
04448       return PROVIS_KEEPALIVE_TIMEOUT;
04449    }
04450 
04451    return 0;
04452 }
04453 
04454 static int send_provisional_keepalive(const void *data) {
04455    struct sip_pvt *pvt = (struct sip_pvt *) data;
04456 
04457    return send_provisional_keepalive_full(pvt, 0);
04458 }
04459 
04460 static int send_provisional_keepalive_with_sdp(const void *data) {
04461    struct sip_pvt *pvt = (void *)data;
04462 
04463    return send_provisional_keepalive_full(pvt, 1);
04464 }
04465 
04466 static void update_provisional_keepalive(struct sip_pvt *pvt, int with_sdp)
04467 {
04468    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"));
04469 
04470    pvt->provisional_keepalive_sched_id = ast_sched_add(sched, PROVIS_KEEPALIVE_TIMEOUT,
04471       with_sdp ? send_provisional_keepalive_with_sdp : send_provisional_keepalive, dialog_ref(pvt, "Increment refcount to pass dialog pointer to sched callback"));
04472 }
04473 
04474 /*! \brief Transmit response on SIP request*/
04475 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
04476 {
04477    int res;
04478 
04479    finalize_content(req);
04480    add_blank(req);
04481    if (sip_debug_test_pvt(p)) {
04482       const struct sockaddr_in *dst = sip_real_dst(p);
04483 
04484       ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
04485          reliable ? "Reliably " : "", sip_nat_mode(p),
04486          ast_inet_ntoa(dst->sin_addr),
04487          ntohs(dst->sin_port), req->data->str);
04488    }
04489    if (p->do_history) {
04490       struct sip_request tmp = { .rlPart1 = 0, };
04491       parse_copy(&tmp, req);
04492       append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), 
04493          (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlPart2) : sip_methods[tmp.method].text);
04494       deinit_req(&tmp);
04495    }
04496 
04497    /* If we are sending a final response to an INVITE, stop retransmitting provisional responses */
04498    if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
04499       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"));
04500    }
04501 
04502    res = (reliable) ?
04503        __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
04504       __sip_xmit(p, req->data, req->len);
04505    deinit_req(req);
04506    if (res > 0)
04507       return 0;
04508    return res;
04509 }
04510 
04511 /*! \brief Send SIP Request to the other part of the dialogue */
04512 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
04513 {
04514    int res;
04515 
04516    /* If we have an outbound proxy, reset peer address 
04517       Only do this once.
04518    */
04519    if (p->outboundproxy) {
04520       p->sa = p->outboundproxy->ip;
04521    }
04522 
04523    finalize_content(req);
04524    add_blank(req);
04525    if (sip_debug_test_pvt(p)) {
04526       if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
04527          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);
04528       else
04529          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);
04530    }
04531    if (p->do_history) {
04532       struct sip_request tmp = { .rlPart1 = 0, };
04533       parse_copy(&tmp, req);
04534       append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
04535       deinit_req(&tmp);
04536    }
04537    res = (reliable) ?
04538       __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
04539       __sip_xmit(p, req->data, req->len);
04540    deinit_req(req);
04541    return res;
04542 }
04543 
04544 /*! \brief Query an option on a SIP dialog */
04545 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
04546 {
04547    int res = -1;
04548    enum ast_t38_state state = T38_STATE_UNAVAILABLE;
04549    struct sip_pvt *p = (struct sip_pvt *) chan->tech_pvt;
04550 
04551    switch (option) {
04552    case AST_OPTION_T38_STATE:
04553       /* Make sure we got an ast_t38_state enum passed in */
04554       if (*datalen != sizeof(enum ast_t38_state)) {
04555          ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
04556          return -1;
04557       }
04558 
04559       sip_pvt_lock(p);
04560 
04561       /* 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 */
04562       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
04563          switch (p->t38.state) {
04564          case T38_LOCAL_REINVITE:
04565          case T38_PEER_REINVITE:
04566             state = T38_STATE_NEGOTIATING;
04567             break;
04568          case T38_ENABLED:
04569             state = T38_STATE_NEGOTIATED;
04570             break;
04571          default:
04572             state = T38_STATE_UNKNOWN;
04573          }
04574       }
04575 
04576       sip_pvt_unlock(p);
04577 
04578       *((enum ast_t38_state *) data) = state;
04579       res = 0;
04580 
04581       break;
04582    default:
04583       break;
04584    }
04585 
04586    return res;
04587 }
04588 
04589 /*! \brief Locate closing quote in a string, skipping escaped quotes.
04590  * optionally with a limit on the search.
04591  * start must be past the first quote.
04592  */
04593 static const char *find_closing_quote(const char *start, const char *lim)
04594 {
04595    char last_char = '\0';
04596    const char *s;
04597    for (s = start; *s && s != lim; last_char = *s++) {
04598       if (*s == '"' && last_char != '\\')
04599          break;
04600    }
04601    return s;
04602 }
04603 
04604 /*! \brief Pick out text in brackets from character string
04605    \return pointer to terminated stripped string
04606    \param tmp input string that will be modified
04607    Examples:
04608 \verbatim
04609    "foo" <bar> valid input, returns bar
04610    foo      returns the whole string
04611    < "foo ... >   returns the string between brackets
04612    < "foo...   bogus (missing closing bracket), returns the whole string
04613          XXX maybe should still skip the opening bracket
04614 \endverbatim
04615  */
04616 static char *get_in_brackets(char *tmp)
04617 {
04618    const char *parse = tmp;
04619    char *first_bracket;
04620 
04621    /*
04622     * Skip any quoted text until we find the part in brackets.
04623    * On any error give up and return the full string.
04624    */
04625    while ( (first_bracket = strchr(parse, '<')) ) {
04626       char *first_quote = strchr(parse, '"');
04627 
04628       if (!first_quote || first_quote > first_bracket)
04629          break; /* no need to look at quoted part */
04630       /* the bracket is within quotes, so ignore it */
04631       parse = find_closing_quote(first_quote + 1, NULL);
04632       if (!*parse) { /* not found, return full string ? */
04633          /* XXX or be robust and return in-bracket part ? */
04634          ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
04635          break;
04636       }
04637       parse++;
04638    }
04639    if (first_bracket) {
04640       char *second_bracket = strchr(first_bracket + 1, '>');
04641       if (second_bracket) {
04642          *second_bracket = '\0';
04643          tmp = first_bracket + 1;
04644       } else {
04645          ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
04646       }
04647    }
04648    
04649    return tmp;
04650 }
04651 
04652 /*! \brief * parses a URI in its components.
04653  *
04654  * \note 
04655  * - If scheme is specified, drop it from the top.
04656  * - If a component is not requested, do not split around it.
04657  * - Multiple scheme's can be specified ',' delimited. ex: "sip:,sips:"
04658  *
04659  * This means that if we don't have domain, we cannot split
04660  * name:pass and domain:port.
04661  * It is safe to call with ret_name, pass, domain, port
04662  * pointing all to the same place.
04663  * Init pointers to empty string so we never get NULL dereferencing.
04664  * Overwrites the string.
04665  * return 0 on success, other values on error.
04666  * \verbatim 
04667  * general form we are expecting is sip[s]:username[:password][;parameter]@host[:port][;...] 
04668  * \endverbatim
04669  * 
04670  */
04671 static int parse_uri(char *uri, const char *scheme,
04672    char **ret_name, char **pass, char **domain, char **port, char **options, char **transport)
04673 {
04674    char *name = NULL;
04675    int error = 0;
04676 
04677    /* init field as required */
04678    if (pass)
04679       *pass = "";
04680    if (port)
04681       *port = "";
04682    if (scheme) {
04683       int l;
04684       char *scheme2 = ast_strdupa(scheme);
04685       char *cur = strsep(&scheme2, ",");
04686       for (; !ast_strlen_zero(cur); cur = strsep(&scheme2, ",")) {
04687          l = strlen(cur);
04688          if (!strncasecmp(uri, cur, l)) {
04689             uri += l;
04690             break;
04691          }
04692       }
04693       if (ast_strlen_zero(cur)) {
04694          ast_debug(1, "No supported scheme found in '%s' using the scheme[s] %s\n", uri, scheme);
04695          error = -1;
04696       }
04697    }
04698    if (transport) {
04699       char *t, *type = "";
04700       *transport = "";
04701       if ((t = strstr(uri, "transport="))) {
04702          strsep(&t, "=");
04703          if ((type = strsep(&t, ";"))) {
04704             *transport = type;
04705          }
04706       }
04707    }
04708 
04709    if (!domain) {
04710       /* if we don't want to split around domain, keep everything as a name,
04711        * so we need to do nothing here, except remember why.
04712        */
04713    } else {
04714       /* store the result in a temp. variable to avoid it being
04715        * overwritten if arguments point to the same place.
04716        */
04717       char *c, *dom = "";
04718 
04719       if ((c = strchr(uri, '@')) == NULL) {
04720          /* domain-only URI, according to the SIP RFC. */
04721          dom = uri;
04722          name = "";
04723       } else {
04724          *c++ = '\0';
04725          dom = c;
04726          name = uri;
04727       }
04728 
04729       /* Remove options in domain and name */
04730       dom = strsep(&dom, ";");
04731       name = strsep(&name, ";");
04732 
04733       if (port && (c = strchr(dom, ':'))) { /* Remove :port */
04734          *c++ = '\0';
04735          *port = c;
04736       }
04737       if (pass && (c = strchr(name, ':'))) { /* user:password */
04738          *c++ = '\0';
04739          *pass = c;
04740       }
04741       *domain = dom;
04742    }
04743    if (ret_name)  /* same as for domain, store the result only at the end */
04744       *ret_name = name;
04745    if (options)
04746       *options = uri ? uri : "";
04747 
04748    return error;
04749 }
04750 
04751 /*! \brief Send message with Access-URL header, if this is an HTML URL only! */
04752 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
04753 {
04754    struct sip_pvt *p = chan->tech_pvt;
04755 
04756    if (subclass != AST_HTML_URL)
04757       return -1;
04758 
04759    ast_string_field_build(p, url, "<%s>;mode=active", data);
04760 
04761    if (sip_debug_test_pvt(p))
04762       ast_debug(1, "Send URL %s, state = %d!\n", data, chan->_state);
04763 
04764    switch (chan->_state) {
04765    case AST_STATE_RING:
04766       transmit_response(p, "100 Trying", &p->initreq);
04767       break;
04768    case AST_STATE_RINGING:
04769       transmit_response(p, "180 Ringing", &p->initreq);
04770       break;
04771    case AST_STATE_UP:
04772       if (!p->pendinginvite) {      /* We are up, and have no outstanding invite */
04773          transmit_reinvite_with_sdp(p, FALSE, FALSE);
04774       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
04775          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);   
04776       }  
04777       break;
04778    default:
04779       ast_log(LOG_WARNING, "Don't know how to send URI when state is %d!\n", chan->_state);
04780    }
04781 
04782    return 0;
04783 }
04784 
04785 /*! \brief Deliver SIP call ID for the call */
04786 static const char *sip_get_callid(struct ast_channel *chan)
04787 {
04788    return chan->tech_pvt ? ((struct sip_pvt *) chan->tech_pvt)->callid : "";
04789 }
04790 
04791 /*! \brief Send SIP MESSAGE text within a call
04792    Called from PBX core sendtext() application */
04793 static int sip_sendtext(struct ast_channel *ast, const char *text)
04794 {
04795    struct sip_pvt *p = ast->tech_pvt;
04796    int debug = sip_debug_test_pvt(p);
04797 
04798    if (debug)
04799       ast_verbose("Sending text %s on %s\n", text, ast->name);
04800    if (!p)
04801       return -1;
04802    /* NOT ast_strlen_zero, because a zero-length message is specifically
04803     * allowed by RFC 3428 (See section 10, Examples) */
04804    if (!text)
04805       return 0;
04806    if (debug)
04807       ast_verbose("Really sending text %s on %s\n", text, ast->name);
04808    transmit_message_with_text(p, text);
04809    return 0;   
04810 }
04811 
04812 /*! \brief Update peer object in realtime storage 
04813    If the Asterisk system name is set in asterisk.conf, we will use
04814    that name and store that in the "regserver" field in the sippeers
04815    table to facilitate multi-server setups.
04816 */
04817 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)
04818 {
04819    char port[10];
04820    char ipaddr[INET_ADDRSTRLEN];
04821    char regseconds[20];
04822    char *tablename = NULL;
04823    char str_lastms[20];
04824 
04825    const char *sysname = ast_config_AST_SYSTEM_NAME;
04826    char *syslabel = NULL;
04827 
04828    time_t nowtime = time(NULL) + expirey;
04829    const char *fc = fullcontact ? "fullcontact" : NULL;
04830 
04831    int realtimeregs = ast_check_realtime("sipregs");
04832 
04833    tablename = realtimeregs ? "sipregs" : "sippeers";
04834    
04835 
04836    snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
04837    snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);  /* Expiration time */
04838    ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
04839    snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
04840    
04841    if (ast_strlen_zero(sysname)) /* No system name, disable this */
04842       sysname = NULL;
04843    else if (sip_cfg.rtsave_sysname)
04844       syslabel = "regserver";
04845 
04846    /* XXX IMPORTANT: Anytime you add a new parameter to be updated, you
04847          *  must also add it to contrib/scripts/asterisk.ldap-schema,
04848          *  contrib/scripts/asterisk.ldif,
04849          *  and to configs/res_ldap.conf.sample as described in
04850          *  bugs 15156 and 15895 
04851          */
04852    if (fc) {
04853       ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04854          "port", port, "regseconds", regseconds,
04855          deprecated_username ? "username" : "defaultuser", defaultuser,
04856          "useragent", useragent, "lastms", str_lastms,
04857          fc, fullcontact, syslabel, sysname, SENTINEL); /* note fc and syslabel _can_ be NULL */
04858    } else {
04859       ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04860          "port", port, "regseconds", regseconds,
04861          "useragent", useragent, "lastms", str_lastms,
04862          deprecated_username ? "username" : "defaultuser", defaultuser,
04863          syslabel, sysname, SENTINEL); /* note syslabel _can_ be NULL */
04864    }
04865 }
04866 
04867 /*! \brief Automatically add peer extension to dial plan */
04868 static void register_peer_exten(struct sip_peer *peer, int onoff)
04869 {
04870    char multi[256];
04871    char *stringp, *ext, *context;
04872    struct pbx_find_info q = { .stacklen = 0 };
04873 
04874    /* XXX note that global_regcontext is both a global 'enable' flag and
04875     * the name of the global regexten context, if not specified
04876     * individually.
04877     */
04878    if (ast_strlen_zero(global_regcontext))
04879       return;
04880 
04881    ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
04882    stringp = multi;
04883    while ((ext = strsep(&stringp, "&"))) {
04884       if ((context = strchr(ext, '@'))) {
04885          *context++ = '\0';   /* split ext@context */
04886          if (!ast_context_find(context)) {
04887             ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
04888             continue;
04889          }
04890       } else {
04891          context = global_regcontext;
04892       }
04893       if (onoff) {
04894          if (!ast_exists_extension(NULL, context, ext, 1, NULL)) {
04895             ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
04896                 ast_strdup(peer->name), ast_free_ptr, "SIP");
04897          }
04898       } else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
04899          ast_context_remove_extension(context, ext, 1, NULL);
04900       }
04901    }
04902 }
04903 
04904 /*! Destroy mailbox subscriptions */
04905 static void destroy_mailbox(struct sip_mailbox *mailbox)
04906 {
04907    if (mailbox->mailbox)
04908       ast_free(mailbox->mailbox);
04909    if (mailbox->context)
04910       ast_free(mailbox->context);
04911    if (mailbox->event_sub)
04912       ast_event_unsubscribe(mailbox->event_sub);
04913    ast_free(mailbox);
04914 }
04915 
04916 /*! Destroy all peer-related mailbox subscriptions */
04917 static void clear_peer_mailboxes(struct sip_peer *peer)
04918 {
04919    struct sip_mailbox *mailbox;
04920 
04921    while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
04922       destroy_mailbox(mailbox);
04923 }
04924 
04925 static void sip_destroy_peer_fn(void *peer)
04926 {
04927    sip_destroy_peer(peer);
04928 }
04929 
04930 /*! \brief Destroy peer object from memory */
04931 static void sip_destroy_peer(struct sip_peer *peer)
04932 {
04933    ast_debug(3, "Destroying SIP peer %s\n", peer->name);
04934    if (peer->outboundproxy)
04935       ao2_ref(peer->outboundproxy, -1);
04936    peer->outboundproxy = NULL;
04937 
04938    /* Delete it, it needs to disappear */
04939    if (peer->call) {
04940       dialog_unlink_all(peer->call, TRUE, TRUE);
04941       peer->call = dialog_unref(peer->call, "peer->call is being unset");
04942    }
04943    
04944 
04945    if (peer->mwipvt) {  /* We have an active subscription, delete it */
04946       dialog_unlink_all(peer->mwipvt, TRUE, TRUE);
04947       peer->mwipvt = dialog_unref(peer->mwipvt, "unreffing peer->mwipvt");
04948    }
04949    
04950    if (peer->chanvars) {
04951       ast_variables_destroy(peer->chanvars);
04952       peer->chanvars = NULL;
04953    }
04954    
04955    register_peer_exten(peer, FALSE);
04956    ast_free_ha(peer->ha);
04957    if (peer->selfdestruct)
04958       ast_atomic_fetchadd_int(&apeerobjs, -1);
04959    else if (!ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->is_realtime) {
04960       ast_atomic_fetchadd_int(&rpeerobjs, -1);
04961       ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
04962    } else
04963       ast_atomic_fetchadd_int(&speerobjs, -1);
04964    clear_realm_authentication(peer->auth);
04965    peer->auth = NULL;
04966    if (peer->dnsmgr)
04967       ast_dnsmgr_release(peer->dnsmgr);
04968    clear_peer_mailboxes(peer);
04969 
04970    if (peer->socket.tcptls_session) {
04971       ao2_ref(peer->socket.tcptls_session, -1);
04972       peer->socket.tcptls_session = NULL;
04973    }
04974 
04975    ast_string_field_free_memory(peer);
04976 }
04977 
04978 /*! \brief Update peer data in database (if used) */
04979 static void update_peer(struct sip_peer *p, int expire)
04980 {
04981    int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
04982    if (sip_cfg.peer_rtupdate &&
04983        (p->is_realtime || rtcachefriends)) {
04984       realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, p->useragent, expire, p->deprecated_username, p->lastms);
04985    }
04986 }
04987 
04988 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *cfg)
04989 {
04990    struct ast_variable *var = NULL;
04991    struct ast_flags flags = {0};
04992    char *cat = NULL;
04993    const char *insecure;
04994    while ((cat = ast_category_browse(cfg, cat))) {
04995       insecure = ast_variable_retrieve(cfg, cat, "insecure");
04996       set_insecure_flags(&flags, insecure, -1);
04997       if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
04998          var = ast_category_root(cfg, cat);
04999          break;
05000       }
05001    }
05002    return var;
05003 }
05004 
05005 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername)
05006 {
05007    struct ast_variable *tmp;
05008    for (tmp = var; tmp; tmp = tmp->next) {
05009       if (!newpeername && !strcasecmp(tmp->name, "name"))
05010          newpeername = tmp->value;
05011    }
05012    return newpeername;
05013 }
05014 
05015 /*! \brief  realtime_peer: Get peer from realtime storage
05016  * Checks the "sippeers" realtime family from extconfig.conf 
05017  * Checks the "sipregs" realtime family from extconfig.conf if it's configured.
05018  * This returns a pointer to a peer and because we use build_peer, we can rest
05019  * assured that the refcount is bumped.
05020 */
05021 static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin, int devstate_only)
05022 {
05023    struct sip_peer *peer;
05024    struct ast_variable *var = NULL;
05025    struct ast_variable *varregs = NULL;
05026    struct ast_variable *tmp;
05027    struct ast_config *peerlist = NULL;
05028    char ipaddr[INET_ADDRSTRLEN];
05029    char portstring[6]; /*up to 5 digits plus null terminator*/
05030    char *cat = NULL;
05031    unsigned short portnum;
05032    int realtimeregs = ast_check_realtime("sipregs");
05033 
05034    /* First check on peer name */
05035    if (newpeername) {
05036       if (realtimeregs)
05037          varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
05038 
05039       var = ast_load_realtime("sippeers", "name", newpeername, "host", "dynamic", SENTINEL);
05040       if (!var && sin)
05041          var = ast_load_realtime("sippeers", "name", newpeername, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
05042       if (!var) {
05043          var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
05044          /*!\note
05045           * If this one loaded something, then we need to ensure that the host
05046           * field matched.  The only reason why we can't have this as a criteria
05047           * is because we only have the IP address and the host field might be
05048           * set as a name (and the reverse PTR might not match).
05049           */
05050          if (var && sin) {
05051             for (tmp = var; tmp; tmp = tmp->next) {
05052                if (!strcasecmp(tmp->name, "host")) {
05053                   struct hostent *hp;
05054                   struct ast_hostent ahp;
05055                   if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
05056                      /* No match */
05057                      ast_variables_destroy(var);
05058                      var = NULL;
05059                   }
05060                   break;
05061                }
05062             }
05063          }
05064       }
05065    }
05066 
05067    if (!var && sin) {   /* Then check on IP address for dynamic peers */
05068       ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
05069       portnum = ntohs(sin->sin_port);
05070       sprintf(portstring, "%u", portnum);
05071       var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, SENTINEL);  /* First check for fixed IP hosts */
05072       if (var) {
05073          if (realtimeregs) {
05074             newpeername = get_name_from_variable(var, newpeername);
05075             varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
05076          }
05077       } else {
05078          if (realtimeregs)
05079             varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, "port", portstring, SENTINEL); /* Then check for registered hosts */
05080          else
05081             var = ast_load_realtime("sippeers", "ipaddr", ipaddr, "port", portstring, SENTINEL); /* Then check for registered hosts */
05082          if (varregs) {
05083             newpeername = get_name_from_variable(varregs, newpeername);
05084             var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
05085          }
05086       }
05087       if (!var) { /*We couldn't match on ipaddress and port, so we need to check if port is insecure*/
05088          peerlist = ast_load_realtime_multientry("sippeers", "host", ipaddr, SENTINEL);
05089          if (peerlist) {
05090             var = get_insecure_variable_from_config(peerlist);
05091             if(var) {
05092                if (realtimeregs) {
05093                   newpeername = get_name_from_variable(var, newpeername);
05094                   varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
05095                }
05096             } else { /*var wasn't found in the list of "hosts", so try "ipaddr"*/
05097                peerlist = NULL;
05098                cat = NULL;
05099                peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, SENTINEL);
05100                if(peerlist) {
05101                   var = get_insecure_variable_from_config(peerlist);
05102                   if(var) {
05103                      if (realtimeregs) {
05104                         newpeername = get_name_from_variable(var, newpeername);
05105                         varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
05106                      }
05107                   }
05108                }
05109             }
05110          } else {
05111             if (realtimeregs) {
05112                peerlist = ast_load_realtime_multientry("sipregs", "ipaddr", ipaddr, SENTINEL);
05113                if (peerlist) {
05114                   varregs = get_insecure_variable_from_config(peerlist);
05115                   if (varregs) {
05116                      newpeername = get_name_from_variable(varregs, newpeername);
05117                      var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
05118                   }
05119                }
05120             } else {
05121                peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, SENTINEL);
05122                if (peerlist) {
05123                   var = get_insecure_variable_from_config(peerlist);
05124                   if (var) {
05125                      newpeername = get_name_from_variable(var, newpeername);
05126                      varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
05127                   }
05128                }
05129             }
05130          }
05131       }
05132    }
05133 
05134    if (!var) {
05135       if (peerlist)
05136          ast_config_destroy(peerlist);
05137       return NULL;
05138    }
05139 
05140    for (tmp = var; tmp; tmp = tmp->next) {
05141       if (!newpeername && !strcasecmp(tmp->name, "name")) {
05142          newpeername = tmp->value;
05143       }
05144    }
05145    
05146    if (!newpeername) {  /* Did not find peer in realtime */
05147       ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", ipaddr);
05148       if(peerlist)
05149          ast_config_destroy(peerlist);
05150       else
05151          ast_variables_destroy(var);
05152       return NULL;
05153    }
05154 
05155 
05156    /* Peer found in realtime, now build it in memory */
05157    peer = build_peer(newpeername, var, varregs, TRUE, devstate_only);
05158    if (!peer) {
05159       if(peerlist)
05160          ast_config_destroy(peerlist);
05161       else {
05162          ast_variables_destroy(var);
05163          ast_variables_destroy(varregs);
05164       }
05165       return NULL;
05166    }
05167 
05168    ast_debug(3, "-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
05169 
05170    if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && !devstate_only) {
05171       /* Cache peer */
05172       ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
05173       if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
05174          AST_SCHED_REPLACE_UNREF(peer->expire, sched, sip_cfg.rtautoclear * 1000, expire_register, peer,
05175                unref_peer(_data, "remove registration ref"),
05176                unref_peer(peer, "remove registration ref"),
05177                ref_peer(peer, "add registration ref"));
05178       }
05179       ao2_t_link(peers, peer, "link peer into peers table");
05180       if (peer->addr.sin_addr.s_addr) {
05181          ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
05182       }
05183    }
05184    peer->is_realtime = 1;
05185    if (peerlist)
05186       ast_config_destroy(peerlist);
05187    else {
05188       ast_variables_destroy(var);
05189       ast_variables_destroy(varregs);
05190    }
05191 
05192    return peer;
05193 }
05194 
05195 /* Function to assist finding peers by name only */
05196 static int find_by_name(void *obj, void *arg, void *data, int flags)
05197 {
05198    struct sip_peer *search = obj, *match = arg;
05199    int *which_objects = data;
05200 
05201    /* Usernames in SIP uri's are case sensitive. Domains are not */
05202    if (strcmp(search->name, match->name)) {
05203       return 0;
05204    }
05205 
05206    switch (*which_objects) {
05207    case FINDUSERS:
05208       if (!(search->type & SIP_TYPE_USER)) {
05209          return 0;
05210       }
05211       break;
05212    case FINDPEERS:
05213       if (!(search->type & SIP_TYPE_PEER)) {
05214          return 0;
05215       }
05216       break;
05217    case FINDALLDEVICES:
05218       break;
05219    }
05220 
05221    return CMP_MATCH | CMP_STOP;
05222 }
05223 
05224 /*! 
05225  * \brief Locate device by name or ip address 
05226  *
05227  * \param which_objects Define which objects should be matched when doing a lookup
05228  *        by name.  Valid options are FINDUSERS, FINDPEERS, or FINDALLDEVICES.
05229  *        Note that this option is not used at all when doing a lookup by IP.
05230  *
05231  * This is used on find matching device on name or ip/port.
05232  * If the device was declared as type=peer, we don't match on peer name on incoming INVITEs.
05233  *
05234  * \note Avoid using this function in new functions if there is a way to avoid it,
05235  * since it might cause a database lookup.
05236  */
05237 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int which_objects, int devstate_only, int transport)
05238 {
05239    struct sip_peer *p = NULL;
05240    struct sip_peer tmp_peer;
05241 
05242    if (peer) {
05243       ast_copy_string(tmp_peer.name, peer, sizeof(tmp_peer.name));
05244       p = ao2_t_callback_data(peers, OBJ_POINTER, find_by_name, &tmp_peer, &which_objects, "ao2_find in peers table");
05245    } else if (sin) { /* search by addr? */
05246       tmp_peer.addr.sin_addr.s_addr = sin->sin_addr.s_addr;
05247       tmp_peer.addr.sin_port = sin->sin_port;
05248       tmp_peer.flags[0].flags = 0;
05249       tmp_peer.transports = transport;
05250       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); */
05251       if (!p) {
05252          ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
05253          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); */
05254          if (p) {
05255             return p;
05256          }
05257       }
05258    }
05259 
05260    if (!p && (realtime || devstate_only)) {
05261       p = realtime_peer(peer, sin, devstate_only);
05262       if (p) {
05263          switch (which_objects) {
05264          case FINDUSERS:
05265             if (!(p->type & SIP_TYPE_USER)) {
05266                unref_peer(p, "Wrong type of realtime SIP endpoint");
05267                return NULL;
05268             }
05269             break;
05270          case FINDPEERS:
05271             if (!(p->type & SIP_TYPE_PEER)) {
05272                unref_peer(p, "Wrong type of realtime SIP endpoint");
05273                return NULL;
05274             }
05275             break;
05276          case FINDALLDEVICES:
05277             break;
05278          }
05279       }
05280    }
05281 
05282    return p;
05283 }
05284 
05285 /*! \brief Set nat mode on the various data sockets */
05286 static void do_setnat(struct sip_pvt *p, int natflags)
05287 {
05288    const char *mode = natflags ? "On" : "Off";
05289 
05290    if (p->rtp) {
05291       ast_debug(1, "Setting NAT on RTP to %s\n", mode);
05292       ast_rtp_setnat(p->rtp, natflags);
05293    }
05294    if (p->vrtp) {
05295       ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
05296       ast_rtp_setnat(p->vrtp, natflags);
05297    }
05298    if (p->udptl) {
05299       ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
05300       ast_udptl_setnat(p->udptl, natflags);
05301    }
05302    if (p->trtp) {
05303       ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
05304       ast_rtp_setnat(p->trtp, natflags);
05305    }
05306 }
05307 
05308 /*! \brief Change the T38 state on a SIP dialog */
05309 static void change_t38_state(struct sip_pvt *p, int state)
05310 {
05311    int old = p->t38.state;
05312    struct ast_channel *chan = p->owner;
05313    struct ast_control_t38_parameters parameters = { .request_response = 0 };
05314 
05315    /* Don't bother changing if we are already in the state wanted */
05316    if (old == state)
05317       return;
05318 
05319    p->t38.state = state;
05320    ast_debug(2, "T38 state changed to %d on channel %s\n", p->t38.state, chan ? chan->name : "<none>");
05321 
05322    /* If no channel was provided we can't send off a control frame */
05323    if (!chan)
05324       return;
05325 
05326    /* Given the state requested and old state determine what control frame we want to queue up */
05327    switch (state) {
05328    case T38_PEER_REINVITE:
05329       parameters = p->t38.their_parms;
05330       parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05331       parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
05332       ast_udptl_set_tag(p->udptl, "SIP/%s", p->username);
05333       break;
05334    case T38_ENABLED:
05335       parameters = p->t38.their_parms;
05336       parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05337       parameters.request_response = AST_T38_NEGOTIATED;
05338       ast_udptl_set_tag(p->udptl, "SIP/%s", p->username);
05339       break;
05340    case T38_DISABLED:
05341       if (old == T38_ENABLED) {
05342          parameters.request_response = AST_T38_TERMINATED;
05343       } else if (old == T38_LOCAL_REINVITE) {
05344          parameters.request_response = AST_T38_REFUSED;
05345       }
05346       break;
05347    case T38_LOCAL_REINVITE:
05348       /* wait until we get a peer response before responding to local reinvite */
05349       break;
05350    }
05351 
05352    /* Woot we got a message, create a control frame and send it on! */
05353    if (parameters.request_response)
05354       ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
05355 }
05356 
05357 /*! \brief Set the global T38 capabilities on a SIP dialog structure */
05358 static void set_t38_capabilities(struct sip_pvt *p)
05359 {
05360    if (p->udptl) {
05361       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY) {
05362                         ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
05363       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_FEC) {
05364          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
05365       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL) {
05366          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
05367       }
05368    }
05369 }
05370 
05371 static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
05372 {
05373    if (to_sock->tcptls_session) {
05374       ao2_ref(to_sock->tcptls_session, -1);
05375       to_sock->tcptls_session = NULL;
05376    }
05377 
05378    if (from_sock->tcptls_session) {
05379       ao2_ref(from_sock->tcptls_session, +1);
05380    }
05381 
05382    *to_sock = *from_sock;
05383 }
05384 
05385 /*! \brief Create address structure from peer reference.
05386  * This function copies data from peer to the dialog, so we don't have to look up the peer
05387  * again from memory or database during the life time of the dialog.
05388  *
05389  * \return -1 on error, 0 on success.
05390  *
05391  */
05392 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
05393 {
05394 
05395    /* this checks that the dialog is contacting the peer on a valid
05396     * transport type based on the peers transport configuration,
05397     * otherwise, this function bails out */
05398    if (dialog->socket.type && check_request_transport(peer, dialog))
05399       return -1;
05400    copy_socket_data(&dialog->socket, &peer->socket);
05401 
05402    if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
05403        (!peer->maxms || ((peer->lastms >= 0)  && (peer->lastms <= peer->maxms)))) {
05404       dialog->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
05405       dialog->recv = dialog->sa;
05406    } else 
05407       return -1;
05408 
05409    ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
05410    ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
05411    dialog->capability = peer->capability;
05412    if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) &&
05413          (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
05414             !(dialog->capability & AST_FORMAT_VIDEO_MASK)) &&
05415          dialog->vrtp) {
05416       ast_rtp_destroy(dialog->vrtp);
05417       dialog->vrtp = NULL;
05418    }
05419    if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT) && dialog->trtp) {
05420       ast_rtp_destroy(dialog->trtp);
05421       dialog->trtp = NULL;
05422    }
05423    dialog->prefs = peer->prefs;
05424    if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
05425       /* t38pt_udptl was enabled in the peer and not in [general] */
05426       if (dialog->udptl || (!dialog->udptl && (dialog->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr)))) {
05427          dialog->t38_maxdatagram = peer->t38_maxdatagram;
05428          set_t38_capabilities(dialog);
05429       } else {
05430          /* It is impossible to support T38 without udptl */
05431          ast_debug(1, "UDPTL creation failed on dialog.\n");
05432          ast_clear_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT);
05433       }
05434    } else if (dialog->udptl) {
05435       ast_udptl_destroy(dialog->udptl);
05436       dialog->udptl = NULL;
05437    }
05438    do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
05439 
05440    if (dialog->rtp) { /* Audio */
05441       ast_rtp_setdtmf(dialog->rtp, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
05442       ast_rtp_setdtmfcompensate(dialog->rtp, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
05443       ast_rtp_set_rtptimeout(dialog->rtp, peer->rtptimeout);
05444       ast_rtp_set_rtpholdtimeout(dialog->rtp, peer->rtpholdtimeout);
05445       ast_rtp_set_rtpkeepalive(dialog->rtp, peer->rtpkeepalive);
05446       /* Set Frame packetization */
05447       ast_rtp_codec_setpref(dialog->rtp, &dialog->prefs);
05448       dialog->autoframing = peer->autoframing;
05449    }
05450    if (dialog->vrtp) { /* Video */
05451       ast_rtp_setdtmf(dialog->vrtp, 0);
05452       ast_rtp_setdtmfcompensate(dialog->vrtp, 0);
05453       ast_rtp_set_rtptimeout(dialog->vrtp, peer->rtptimeout);
05454       ast_rtp_set_rtpholdtimeout(dialog->vrtp, peer->rtpholdtimeout);
05455       ast_rtp_set_rtpkeepalive(dialog->vrtp, peer->rtpkeepalive);
05456    }
05457    if (dialog->trtp) { /* Realtime text */
05458       ast_rtp_setdtmf(dialog->trtp, 0);
05459       ast_rtp_setdtmfcompensate(dialog->trtp, 0);
05460       ast_rtp_set_rtptimeout(dialog->trtp, peer->rtptimeout);
05461       ast_rtp_set_rtpholdtimeout(dialog->trtp, peer->rtpholdtimeout);
05462       ast_rtp_set_rtpkeepalive(dialog->trtp, peer->rtpkeepalive);
05463    }
05464 
05465    ast_string_field_set(dialog, peername, peer->name);
05466    ast_string_field_set(dialog, authname, peer->username);
05467    ast_string_field_set(dialog, username, peer->username);
05468    ast_string_field_set(dialog, peersecret, peer->secret);
05469    ast_string_field_set(dialog, peermd5secret, peer->md5secret);
05470    ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
05471    ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
05472    ast_string_field_set(dialog, tohost, peer->tohost);
05473    ast_string_field_set(dialog, fullcontact, peer->fullcontact);
05474    ast_string_field_set(dialog, context, peer->context);
05475    ast_string_field_set(dialog, parkinglot, peer->parkinglot);
05476    ref_proxy(dialog, obproxy_get(dialog, peer));
05477    dialog->callgroup = peer->callgroup;
05478    dialog->pickupgroup = peer->pickupgroup;
05479    dialog->allowtransfer = peer->allowtransfer;
05480    dialog->jointnoncodeccapability = dialog->noncodeccapability;
05481    dialog->rtptimeout = peer->rtptimeout;
05482    dialog->peerauth = peer->auth;
05483    dialog->maxcallbitrate = peer->maxcallbitrate;
05484    if (ast_strlen_zero(dialog->tohost))
05485       ast_string_field_set(dialog, tohost, ast_inet_ntoa(dialog->sa.sin_addr));
05486    if (!ast_strlen_zero(peer->fromdomain)) {
05487       ast_string_field_set(dialog, fromdomain, peer->fromdomain);
05488       if (!dialog->initreq.headers) {
05489          char *c;
05490          char *tmpcall = ast_strdupa(dialog->callid);
05491          /* this sure looks to me like we are going to change the callid on this dialog!! */
05492          c = strchr(tmpcall, '@');
05493          if (c) {
05494             *c = '\0';
05495             ao2_t_unlink(dialogs, dialog, "About to change the callid -- remove the old name");
05496             ast_string_field_build(dialog, callid, "%s@%s", tmpcall, peer->fromdomain);
05497             ao2_t_link(dialogs, dialog, "New dialog callid -- inserted back into table");
05498          }
05499       }
05500    }
05501    if (!ast_strlen_zero(peer->fromuser)) 
05502       ast_string_field_set(dialog, fromuser, peer->fromuser);
05503    if (!ast_strlen_zero(peer->language))
05504       ast_string_field_set(dialog, language, peer->language);
05505    /* Set timer T1 to RTT for this peer (if known by qualify=) */
05506    /* Minimum is settable or default to 100 ms */
05507    /* If there is a maxms and lastms from a qualify use that over a manual T1
05508       value. Otherwise, use the peer's T1 value. */
05509    if (peer->maxms && peer->lastms)
05510       dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
05511    else
05512       dialog->timer_t1 = peer->timer_t1;
05513 
05514    /* Set timer B to control transaction timeouts, the peer setting is the default and overrides
05515       the known timer */
05516    if (peer->timer_b)
05517       dialog->timer_b = peer->timer_b;
05518    else
05519       dialog->timer_b = 64 * dialog->timer_t1;
05520 
05521    if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
05522        (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
05523       dialog->noncodeccapability |= AST_RTP_DTMF;
05524    else
05525       dialog->noncodeccapability &= ~AST_RTP_DTMF;
05526    if (peer->call_limit)
05527       ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
05528    if (!dialog->portinuri)
05529       dialog->portinuri = peer->portinuri;
05530    
05531    dialog->chanvars = copy_vars(peer->chanvars);
05532 
05533    return 0;
05534 }
05535 
05536 /*! \brief create address structure from device name
05537  *      Or, if peer not found, find it in the global DNS 
05538  *      returns TRUE (-1) on failure, FALSE on success */
05539 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog)
05540 {
05541    struct hostent *hp;
05542    struct ast_hostent ahp;
05543    struct sip_peer *peer;
05544    char *port;
05545    int portno = 0;
05546    char host[MAXHOSTNAMELEN], *hostn;
05547    char peername[256];
05548    int srv_ret = 0;
05549 
05550    ast_copy_string(peername, opeer, sizeof(peername));
05551    port = strchr(peername, ':');
05552    if (port) {
05553       *port++ = '\0';
05554       dialog->portinuri = 1;
05555    }
05556    dialog->sa.sin_family = AF_INET;
05557    dialog->timer_t1 = global_t1; /* Default SIP retransmission timer T1 (RFC 3261) */
05558    dialog->timer_b = global_timer_b; /* Default SIP transaction timer B (RFC 3261) */
05559    peer = find_peer(peername, NULL, TRUE, FINDPEERS, FALSE, 0);
05560 
05561    if (peer) {
05562       int res;
05563       if (newdialog) {
05564          set_socket_transport(&dialog->socket, 0);
05565       }
05566       res = create_addr_from_peer(dialog, peer);
05567       if (!ast_strlen_zero(port)) {
05568          if ((portno = atoi(port))) {
05569             dialog->sa.sin_port = dialog->recv.sin_port = htons(portno);
05570          }
05571       }
05572       unref_peer(peer, "create_addr: unref peer from find_peer hashtab lookup");
05573       return res;
05574    }
05575 
05576    do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
05577 
05578    ast_string_field_set(dialog, tohost, peername);
05579 
05580    /* Get the outbound proxy information */
05581    ref_proxy(dialog, obproxy_get(dialog, NULL));
05582 
05583    if (sin) {
05584       /* This address should be updated using dnsmgr */
05585       memcpy(&dialog->sa.sin_addr, &sin->sin_addr, sizeof(dialog->sa.sin_addr));
05586       if (!sin->sin_port) {
05587          portno = port_str2int(port, (dialog->socket.type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
05588       } else {
05589          portno = ntohs(sin->sin_port);
05590       }
05591    } else {
05592 
05593       /* Let's see if we can find the host in DNS. First try DNS SRV records,
05594          then hostname lookup */
05595       /*! \todo Fix this function. When we ask for SRV, we should check all transports 
05596            In the future, we should first check NAPTR to find out transport preference
05597        */
05598       hostn = peername;
05599       /* Section 4.2 of RFC 3263 specifies that if a port number is specified, then
05600        * an A record lookup should be used instead of SRV.
05601        */
05602       if (!port && sip_cfg.srvlookup) {
05603          char service[MAXHOSTNAMELEN];
05604          int tportno;
05605          snprintf(service, sizeof(service), "_%s._%s.%s",
05606              get_srv_service(dialog->socket.type),
05607              get_srv_protocol(dialog->socket.type), peername);
05608          srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
05609          if (srv_ret > 0) {
05610             hostn = host;
05611             portno = tportno;
05612          }
05613       }
05614       if (!portno)
05615          portno = port_str2int(port, (dialog->socket.type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
05616       hp = ast_gethostbyname(hostn, &ahp);
05617       if (!hp) {
05618          ast_log(LOG_WARNING, "No such host: %s\n", peername);
05619          return -1;
05620       }
05621       memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
05622    }
05623 
05624    if (!dialog->socket.type)
05625       set_socket_transport(&dialog->socket, SIP_TRANSPORT_UDP);
05626    if (!dialog->socket.port)
05627       dialog->socket.port = bindaddr.sin_port;
05628    dialog->sa.sin_port = htons(portno);
05629    dialog->recv = dialog->sa;
05630    return 0;
05631 }
05632 
05633 /*! \brief Scheduled congestion on a call.
05634  * Only called by the scheduler, must return the reference when done.
05635  */
05636 static int auto_congest(const void *arg)
05637 {
05638    struct sip_pvt *p = (struct sip_pvt *)arg;
05639 
05640    sip_pvt_lock(p);
05641    p->initid = -1;   /* event gone, will not be rescheduled */
05642    if (p->owner) {
05643       /* XXX fails on possible deadlock */
05644       if (!ast_channel_trylock(p->owner)) {
05645          append_history(p, "Cong", "Auto-congesting (timer)");
05646          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
05647          ast_channel_unlock(p->owner);
05648       }
05649 
05650       /* Give the channel a chance to act before we proceed with destruction */
05651       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05652    }
05653    sip_pvt_unlock(p);
05654    dialog_unref(p, "unreffing arg passed into auto_congest callback (p->initid)");
05655    return 0;
05656 }
05657 
05658 
05659 /*! \brief Initiate SIP call from PBX 
05660  *      used from the dial() application      */
05661 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
05662 {
05663    int res;
05664    struct sip_pvt *p = ast->tech_pvt;  /* chan is locked, so the reference cannot go away */
05665    struct varshead *headp;
05666    struct ast_var_t *current;
05667    const char *referer = NULL;   /* SIP referrer */
05668 
05669    if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
05670       ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
05671       return -1;
05672    }
05673 
05674    /* Check whether there is vxml_url, distinctive ring variables */
05675    headp=&ast->varshead;
05676    AST_LIST_TRAVERSE(headp, current, entries) {
05677       /* Check whether there is a VXML_URL variable */
05678       if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
05679          p->options->vxml_url = ast_var_value(current);
05680       } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
05681          p->options->uri_options = ast_var_value(current);
05682       } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
05683          /* Check whether there is a variable with a name starting with SIPADDHEADER */
05684          p->options->addsipheaders = 1;
05685       } else if (!strcasecmp(ast_var_name(current), "SIPFROMDOMAIN")) {
05686          ast_string_field_set(p, fromdomain, ast_var_value(current));
05687       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
05688          /* This is a transfered call */
05689          p->options->transfer = 1;
05690       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
05691          /* This is the referrer */
05692          referer = ast_var_value(current);
05693       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
05694          /* We're replacing a call. */
05695          p->options->replaces = ast_var_value(current);
05696       }
05697    }
05698 
05699    res = 0;
05700    ast_set_flag(&p->flags[0], SIP_OUTGOING);
05701 
05702    /* T.38 re-INVITE FAX detection should never be done for outgoing calls,
05703     * so ensure it is disabled.
05704     */
05705    ast_clear_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38);
05706 
05707    if (p->options->transfer) {
05708       char buf[SIPBUFSIZE/2];
05709 
05710       if (referer) {
05711          if (sipdebug)
05712             ast_debug(3, "Call for %s transfered by %s\n", p->username, referer);
05713          snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
05714       } else 
05715          snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
05716       ast_string_field_set(p, cid_name, buf);
05717    } 
05718    ast_debug(1, "Outgoing Call for %s\n", p->username);
05719 
05720    res = update_call_counter(p, INC_CALL_RINGING);
05721 
05722    if (res == -1) {
05723       ast->hangupcause = AST_CAUSE_USER_BUSY;
05724       return res;
05725    }
05726    p->callingpres = ast->cid.cid_pres;
05727    p->jointcapability = ast_translate_available_formats(p->capability, p->prefcodec);
05728    p->jointnoncodeccapability = p->noncodeccapability;
05729 
05730    /* If there are no audio formats left to offer, punt */
05731    if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
05732       ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
05733       res = -1;
05734    } else {
05735       int xmitres;
05736 
05737       xmitres = transmit_invite(p, SIP_INVITE, 1, 2);
05738       if (xmitres == XMIT_ERROR)
05739          return -1;
05740       p->invitestate = INV_CALLING;
05741    
05742       /* Initialize auto-congest time */
05743       AST_SCHED_REPLACE_UNREF(p->initid, sched, p->timer_b, auto_congest, p, 
05744                         dialog_unref(_data, "dialog ptr dec when SCHED_REPLACE del op succeeded"), 
05745                         dialog_unref(p, "dialog ptr dec when SCHED_REPLACE add failed"),
05746                         dialog_ref(p, "dialog ptr inc when SCHED_REPLACE add succeeded") );
05747    }
05748    return res;
05749 }
05750 
05751 /*! \brief Destroy registry object
05752    Objects created with the register= statement in static configuration */
05753 static void sip_registry_destroy(struct sip_registry *reg)
05754 {
05755    /* Really delete */
05756    ast_debug(3, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
05757 
05758    if (reg->call) {
05759       /* Clear registry before destroying to ensure
05760          we don't get reentered trying to grab the registry lock */
05761       reg->call->registry = registry_unref(reg->call->registry, "destroy reg->call->registry");
05762       ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
05763       dialog_unlink_all(reg->call, TRUE, TRUE);
05764       reg->call = dialog_unref(reg->call, "unref reg->call");
05765       /* reg->call = sip_destroy(reg->call); */
05766    }
05767    AST_SCHED_DEL(sched, reg->expire);  
05768    AST_SCHED_DEL(sched, reg->timeout);
05769    
05770    ast_string_field_free_memory(reg);
05771    ast_atomic_fetchadd_int(&regobjs, -1);
05772    ast_dnsmgr_release(reg->dnsmgr);
05773    ast_free(reg);
05774 }
05775 
05776 /*! \brief Destroy MWI subscription object */
05777 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi)
05778 {
05779    if (mwi->call) {
05780       mwi->call->mwi = NULL;
05781       sip_destroy(mwi->call);
05782    }
05783    
05784    AST_SCHED_DEL(sched, mwi->resub);
05785    ast_string_field_free_memory(mwi);
05786    ast_dnsmgr_release(mwi->dnsmgr);
05787    ast_free(mwi);
05788 }
05789 
05790 /*! \brief Execute destruction of SIP dialog structure, release memory */
05791 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
05792 {
05793    struct sip_request *req;
05794 
05795    /* Destroy Session-Timers if allocated */
05796    if (p->stimer) {
05797       p->stimer->quit_flag = 1;
05798       stop_session_timer(p);
05799       ast_free(p->stimer);
05800       p->stimer = NULL;
05801    }
05802 
05803    if (sip_debug_test_pvt(p))
05804       ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
05805 
05806    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05807       update_call_counter(p, DEC_CALL_LIMIT);
05808       ast_debug(2, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
05809    }
05810 
05811    /* Unlink us from the owner if we have one */
05812    if (p->owner) {
05813       if (lockowner)
05814          ast_channel_lock(p->owner);
05815       if (option_debug)
05816          ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
05817       p->owner->tech_pvt = NULL;
05818       /* Make sure that the channel knows its backend is going away */
05819       p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
05820       if (lockowner)
05821          ast_channel_unlock(p->owner);
05822       /* Give the channel a chance to react before deallocation */
05823       usleep(1);
05824    }
05825 
05826    /* Remove link from peer to subscription of MWI */
05827    if (p->relatedpeer && p->relatedpeer->mwipvt)
05828       p->relatedpeer->mwipvt = dialog_unref(p->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
05829    if (p->relatedpeer && p->relatedpeer->call == p)
05830       p->relatedpeer->call = dialog_unref(p->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
05831    
05832    if (p->relatedpeer)
05833       p->relatedpeer = unref_peer(p->relatedpeer,"unsetting a dialog relatedpeer field in sip_destroy");
05834    
05835    if (p->registry) {
05836       if (p->registry->call == p)
05837          p->registry->call = dialog_unref(p->registry->call, "nulling out the registry's call dialog field in unlink_all");
05838       p->registry = registry_unref(p->registry, "delete p->registry");
05839    }
05840    
05841    if (p->mwi) {
05842       p->mwi->call = NULL;
05843    }
05844 
05845    if (dumphistory)
05846       sip_dump_history(p);
05847 
05848    if (p->options)
05849       ast_free(p->options);
05850 
05851    if (p->notify_headers) {
05852       ast_variables_destroy(p->notify_headers);
05853       p->notify_headers = NULL;
05854    }
05855    if (p->rtp) {
05856       ast_rtp_destroy(p->rtp);
05857    }
05858    if (p->vrtp) {
05859       ast_rtp_destroy(p->vrtp);
05860    }
05861    if (p->trtp) {
05862       while (ast_rtp_get_bridged(p->trtp))
05863          usleep(1);
05864       ast_rtp_destroy(p->trtp);
05865    }
05866    if (p->udptl)
05867       ast_udptl_destroy(p->udptl);
05868    if (p->refer)
05869       ast_free(p->refer);
05870    if (p->route) {
05871       free_old_route(p->route);
05872       p->route = NULL;
05873    }
05874    deinit_req(&p->initreq);
05875 
05876    /* Clear history */
05877    if (p->history) {
05878       struct sip_history *hist;
05879       while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
05880          ast_free(hist);
05881          p->history_entries--;
05882       }
05883       ast_free(p->history);
05884       p->history = NULL;
05885    }
05886 
05887    while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
05888       ast_free(req);
05889    }
05890 
05891    if (p->chanvars) {
05892       ast_variables_destroy(p->chanvars);
05893       p->chanvars = NULL;
05894    }
05895 
05896    ast_string_field_free_memory(p);
05897 
05898    if (p->socket.tcptls_session) {
05899       ao2_ref(p->socket.tcptls_session, -1);
05900       p->socket.tcptls_session = NULL;
05901    }
05902 }
05903 
05904 /*! \brief  update_call_counter: Handle call_limit for SIP devices
05905  * Setting a call-limit will cause calls above the limit not to be accepted.
05906  *
05907  * Remember that for a type=friend, there's one limit for the user and
05908  * another for the peer, not a combined call limit.
05909  * This will cause unexpected behaviour in subscriptions, since a "friend"
05910  * is *two* devices in Asterisk, not one.
05911  *
05912  * Thought: For realtime, we should probably update storage with inuse counter... 
05913  *
05914  * \return 0 if call is ok (no call limit, below threshold)
05915  * -1 on rejection of call
05916  *    
05917  */
05918 static int update_call_counter(struct sip_pvt *fup, int event)
05919 {
05920    char name[256];
05921    int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
05922    int outgoing = fup->outgoing_call;
05923    struct sip_peer *p = NULL;
05924 
05925    ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
05926 
05927 
05928    /* Test if we need to check call limits, in order to avoid 
05929       realtime lookups if we do not need it */
05930    if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
05931       return 0;
05932 
05933    ast_copy_string(name, fup->username, sizeof(name));
05934 
05935    /* Check the list of devices */
05936    if ((p = find_peer(ast_strlen_zero(fup->peername) ? name : fup->peername, NULL, TRUE, FINDALLDEVICES, FALSE, 0))) { 
05937       inuse = &p->inUse;
05938       call_limit = &p->call_limit;
05939       inringing = &p->inRinging;
05940       ast_copy_string(name, fup->peername, sizeof(name));
05941    }
05942    if (!p) {
05943       ast_debug(2, "%s is not a local device, no call limit\n", name);
05944       return 0;
05945    }
05946 
05947    switch(event) {
05948    /* incoming and outgoing affects the inUse counter */
05949    case DEC_CALL_LIMIT:
05950       /* Decrement inuse count if applicable */
05951       if (inuse) {
05952          sip_pvt_lock(fup);
05953          ao2_lock(p);
05954          if (*inuse > 0) {
05955             if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
05956                (*inuse)--;
05957                ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
05958             }
05959          } else {
05960             *inuse = 0;
05961          }
05962          ao2_unlock(p);
05963          sip_pvt_unlock(fup);
05964       }
05965 
05966       /* Decrement ringing count if applicable */
05967       if (inringing) {
05968          sip_pvt_lock(fup);
05969          ao2_lock(p);
05970          if (*inringing > 0) {
05971             if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05972                (*inringing)--;
05973                ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
05974             }
05975          } else {
05976             *inringing = 0;
05977          }
05978          ao2_unlock(p);
05979          sip_pvt_unlock(fup);
05980       }
05981 
05982       /* Decrement onhold count if applicable */
05983       sip_pvt_lock(fup);
05984       ao2_lock(p);
05985       if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && sip_cfg.notifyhold) {
05986          ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
05987          ao2_unlock(p);
05988          sip_pvt_unlock(fup);
05989          sip_peer_hold(fup, FALSE);
05990       } else {
05991          ao2_unlock(p);
05992          sip_pvt_unlock(fup);
05993       }
05994       if (sipdebug)
05995          ast_debug(2, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
05996       break;
05997 
05998    case INC_CALL_RINGING:
05999    case INC_CALL_LIMIT:
06000       /* If call limit is active and we have reached the limit, reject the call */
06001       if (*call_limit > 0 ) {
06002          if (*inuse >= *call_limit) {
06003             ast_log(LOG_NOTICE, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
06004             unref_peer(p, "update_call_counter: unref peer p, call limit exceeded");
06005             return -1; 
06006          }
06007       }
06008       if (inringing && (event == INC_CALL_RINGING)) {
06009          sip_pvt_lock(fup);
06010          ao2_lock(p);
06011          if (!ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
06012             (*inringing)++;
06013             ast_set_flag(&fup->flags[0], SIP_INC_RINGING);
06014          }
06015          ao2_unlock(p);
06016          sip_pvt_unlock(fup);
06017       }
06018       if (inuse) {
06019          sip_pvt_lock(fup);
06020          ao2_lock(p);
06021          if (!ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
06022             (*inuse)++;
06023             ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
06024          }
06025          ao2_unlock(p);
06026          sip_pvt_unlock(fup);
06027       }
06028       if (sipdebug) {
06029          ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", "peer", name, *inuse, *call_limit);
06030       }
06031       break;
06032 
06033    case DEC_CALL_RINGING:
06034       if (inringing) {
06035          sip_pvt_lock(fup);
06036          ao2_lock(p);
06037          if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
06038             if (*inringing > 0) {
06039                (*inringing)--;
06040             }
06041             ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
06042          }
06043          ao2_unlock(p);
06044          sip_pvt_unlock(fup);
06045       }
06046       break;
06047 
06048    default:
06049       ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
06050    }
06051 
06052    if (p) {
06053       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", p->name);
06054       unref_peer(p, "update_call_counter: unref_peer from call counter");
06055    } 
06056    return 0;
06057 }
06058 
06059 
06060 static void sip_destroy_fn(void *p)
06061 {
06062    sip_destroy(p);
06063 }
06064 
06065 /*! \brief Destroy SIP call structure.
06066  * Make it return NULL so the caller can do things like
06067  * foo = sip_destroy(foo);
06068  * and reduce the chance of bugs due to dangling pointers.
06069  */
06070 static struct sip_pvt * sip_destroy(struct sip_pvt *p)
06071 {
06072    ast_debug(3, "Destroying SIP dialog %s\n", p->callid);
06073    __sip_destroy(p, TRUE, TRUE);
06074    return NULL;
06075 }
06076 
06077 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
06078 static int hangup_sip2cause(int cause)
06079 {
06080    /* Possible values taken from causes.h */
06081 
06082    switch(cause) {
06083       case 401:   /* Unauthorized */
06084          return AST_CAUSE_CALL_REJECTED;
06085       case 403:   /* Not found */
06086          return AST_CAUSE_CALL_REJECTED;
06087       case 404:   /* Not found */
06088          return AST_CAUSE_UNALLOCATED;
06089       case 405:   /* Method not allowed */
06090          return AST_CAUSE_INTERWORKING;
06091       case 407:   /* Proxy authentication required */
06092          return AST_CAUSE_CALL_REJECTED;
06093       case 408:   /* No reaction */
06094          return AST_CAUSE_NO_USER_RESPONSE;
06095       case 409:   /* Conflict */
06096          return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
06097       case 410:   /* Gone */
06098          return AST_CAUSE_NUMBER_CHANGED;
06099       case 411:   /* Length required */
06100          return AST_CAUSE_INTERWORKING;
06101       case 413:   /* Request entity too large */
06102          return AST_CAUSE_INTERWORKING;
06103       case 414:   /* Request URI too large */
06104          return AST_CAUSE_INTERWORKING;
06105       case 415:   /* Unsupported media type */
06106          return AST_CAUSE_INTERWORKING;
06107       case 420:   /* Bad extension */
06108          return AST_CAUSE_NO_ROUTE_DESTINATION;
06109       case 480:   /* No answer */
06110          return AST_CAUSE_NO_ANSWER;
06111       case 481:   /* No answer */
06112          return AST_CAUSE_INTERWORKING;
06113       case 482:   /* Loop detected */
06114          return AST_CAUSE_INTERWORKING;
06115       case 483:   /* Too many hops */
06116          return AST_CAUSE_NO_ANSWER;
06117       case 484:   /* Address incomplete */
06118          return AST_CAUSE_INVALID_NUMBER_FORMAT;
06119       case 485:   /* Ambiguous */
06120          return AST_CAUSE_UNALLOCATED;
06121       case 486:   /* Busy everywhere */
06122          return AST_CAUSE_BUSY;
06123       case 487:   /* Request terminated */
06124          return AST_CAUSE_INTERWORKING;
06125       case 488:   /* No codecs approved */
06126          return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
06127       case 491:   /* Request pending */
06128          return AST_CAUSE_INTERWORKING;
06129       case 493:   /* Undecipherable */
06130          return AST_CAUSE_INTERWORKING;
06131       case 500:   /* Server internal failure */
06132          return AST_CAUSE_FAILURE;
06133       case 501:   /* Call rejected */
06134          return AST_CAUSE_FACILITY_REJECTED;
06135       case 502:   
06136          return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
06137       case 503:   /* Service unavailable */
06138          return AST_CAUSE_CONGESTION;
06139       case 504:   /* Gateway timeout */
06140          return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
06141       case 505:   /* SIP version not supported */
06142          return AST_CAUSE_INTERWORKING;
06143       case 600:   /* Busy everywhere */
06144          return AST_CAUSE_USER_BUSY;
06145       case 603:   /* Decline */
06146          return AST_CAUSE_CALL_REJECTED;
06147       case 604:   /* Does not exist anywhere */
06148          return AST_CAUSE_UNALLOCATED;
06149       case 606:   /* Not acceptable */
06150          return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
06151       default:
06152          return AST_CAUSE_NORMAL;
06153    }
06154    /* Never reached */
06155    return 0;
06156 }
06157 
06158 /*! \brief Convert Asterisk hangup causes to SIP codes 
06159 \verbatim
06160  Possible values from causes.h
06161         AST_CAUSE_NOTDEFINED    AST_CAUSE_NORMAL        AST_CAUSE_BUSY
06162         AST_CAUSE_FAILURE       AST_CAUSE_CONGESTION    AST_CAUSE_UNALLOCATED
06163 
06164    In addition to these, a lot of PRI codes is defined in causes.h 
06165    ...should we take care of them too ?
06166    
06167    Quote RFC 3398
06168 
06169    ISUP Cause value                        SIP response
06170    ----------------                        ------------
06171    1  unallocated number                   404 Not Found
06172    2  no route to network                  404 Not found
06173    3  no route to destination              404 Not found
06174    16 normal call clearing                 --- (*)
06175    17 user busy                            486 Busy here
06176    18 no user responding                   408 Request Timeout
06177    19 no answer from the user              480 Temporarily unavailable
06178    20 subscriber absent                    480 Temporarily unavailable
06179    21 call rejected                        403 Forbidden (+)
06180    22 number changed (w/o diagnostic)      410 Gone
06181    22 number changed (w/ diagnostic)       301 Moved Permanently
06182    23 redirection to new destination       410 Gone
06183    26 non-selected user clearing           404 Not Found (=)
06184    27 destination out of order             502 Bad Gateway
06185    28 address incomplete                   484 Address incomplete
06186    29 facility rejected                    501 Not implemented
06187    31 normal unspecified                   480 Temporarily unavailable
06188 \endverbatim
06189 */
06190 static const char *hangup_cause2sip(int cause)
06191 {
06192    switch (cause) {
06193       case AST_CAUSE_UNALLOCATED:      /* 1 */
06194       case AST_CAUSE_NO_ROUTE_DESTINATION:   /* 3 IAX2: Can't find extension in context */
06195       case AST_CAUSE_NO_ROUTE_TRANSIT_NET:   /* 2 */
06196          return "404 Not Found";
06197       case AST_CAUSE_CONGESTION:    /* 34 */
06198       case AST_CAUSE_SWITCH_CONGESTION:   /* 42 */
06199          return "503 Service Unavailable";
06200       case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
06201          return "408 Request Timeout";
06202       case AST_CAUSE_NO_ANSWER:     /* 19 */
06203       case AST_CAUSE_UNREGISTERED:        /* 20 */
06204          return "480 Temporarily unavailable";
06205       case AST_CAUSE_CALL_REJECTED:    /* 21 */
06206          return "403 Forbidden";
06207       case AST_CAUSE_NUMBER_CHANGED:      /* 22 */
06208          return "410 Gone";
06209       case AST_CAUSE_NORMAL_UNSPECIFIED:  /* 31 */
06210          return "480 Temporarily unavailable";
06211       case AST_CAUSE_INVALID_NUMBER_FORMAT:
06212          return "484 Address incomplete";
06213       case AST_CAUSE_USER_BUSY:
06214          return "486 Busy here";
06215       case AST_CAUSE_FAILURE:
06216          return "500 Server internal failure";
06217       case AST_CAUSE_FACILITY_REJECTED:   /* 29 */
06218          return "501 Not Implemented";
06219       case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
06220          return "503 Service Unavailable";
06221       /* Used in chan_iax2 */
06222       case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
06223          return "502 Bad Gateway";
06224       case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
06225          return "488 Not Acceptable Here";
06226          
06227       case AST_CAUSE_NOTDEFINED:
06228       default:
06229          ast_debug(1, "AST hangup cause %d (no match found in SIP)\n", cause);
06230          return NULL;
06231    }
06232 
06233    /* Never reached */
06234    return 0;
06235 }
06236 
06237 
06238 /*! \brief  sip_hangup: Hangup SIP call
06239  * Part of PBX interface, called from ast_hangup */
06240 static int sip_hangup(struct ast_channel *ast)
06241 {
06242    struct sip_pvt *p = ast->tech_pvt;
06243    int needcancel = FALSE;
06244    int needdestroy = 0;
06245    struct ast_channel *oldowner = ast;
06246 
06247    if (!p) {
06248       ast_debug(1, "Asked to hangup channel that was not connected\n");
06249       return 0;
06250    }
06251    if (ast_test_flag(ast, AST_FLAG_ANSWERED_ELSEWHERE) || ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
06252       ast_debug(1, "This call was answered elsewhere");
06253       if (ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
06254          ast_debug(1, "####### It's the cause code, buddy. The cause code!!!\n");
06255       }
06256       append_history(p, "Cancel", "Call answered elsewhere");
06257       p->answered_elsewhere = TRUE;
06258    }
06259 
06260    /* Store hangupcause locally in PVT so we still have it before disconnect */
06261    if (p->owner)
06262       p->hangupcause = p->owner->hangupcause;
06263 
06264    if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
06265       if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06266          if (sipdebug)
06267             ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
06268          update_call_counter(p, DEC_CALL_LIMIT);
06269       }
06270       ast_debug(4, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
06271       if (p->autokillid > -1 && sip_cancel_destroy(p))
06272          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
06273       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06274       ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Really hang up next time */
06275       p->needdestroy = 0;
06276       p->owner->tech_pvt = dialog_unref(p->owner->tech_pvt, "unref p->owner->tech_pvt");
06277       sip_pvt_lock(p);
06278       p->owner = NULL;  /* Owner will be gone after we return, so take it away */
06279       sip_pvt_unlock(p);
06280       ast_module_unref(ast_module_info->self);
06281       return 0;
06282    }
06283 
06284    if (ast_test_flag(ast, AST_FLAG_ZOMBIE)) {
06285       if (p->refer)
06286          ast_debug(1, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast->name, p->callid);
06287       else
06288          ast_debug(1, "Hanging up zombie call. Be scared.\n");
06289    } else
06290       ast_debug(1, "Hangup call %s, SIP callid %s\n", ast->name, p->callid);
06291 
06292    sip_pvt_lock(p);
06293    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06294       if (sipdebug)
06295          ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
06296       update_call_counter(p, DEC_CALL_LIMIT);
06297    }
06298 
06299    /* Determine how to disconnect */
06300    if (p->owner != ast) {
06301       ast_log(LOG_WARNING, "Huh?  We aren't the owner? Can't hangup call.\n");
06302       sip_pvt_unlock(p);
06303       return 0;
06304    }
06305    /* If the call is not UP, we need to send CANCEL instead of BYE */
06306    /* In case of re-invites, the call might be UP even though we have an incomplete invite transaction */
06307    if (p->invitestate < INV_COMPLETED && p->owner->_state != AST_STATE_UP) {
06308       needcancel = TRUE;
06309       ast_debug(4, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
06310    }
06311 
06312    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
06313 
06314    append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", p->owner ? ast_cause2str(p->hangupcause) : "Unknown");
06315 
06316    /* Disconnect */
06317    if (p->dsp)
06318       ast_dsp_free(p->dsp);
06319 
06320    p->owner = NULL;
06321    ast->tech_pvt = dialog_unref(ast->tech_pvt, "unref ast->tech_pvt");
06322 
06323    ast_module_unref(ast_module_info->self);
06324    /* Do not destroy this pvt until we have timeout or
06325       get an answer to the BYE or INVITE/CANCEL 
06326       If we get no answer during retransmit period, drop the call anyway.
06327       (Sorry, mother-in-law, you can't deny a hangup by sending
06328       603 declined to BYE...)
06329    */
06330    if (p->alreadygone)
06331       needdestroy = 1;  /* Set destroy flag at end of this function */
06332    else if (p->invitestate != INV_CALLING)
06333       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06334 
06335    /* Start the process if it's not already started */
06336    if (!p->alreadygone && p->initreq.data && !ast_strlen_zero(p->initreq.data->str)) {
06337       if (needcancel) { /* Outgoing call, not up */
06338          if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06339             /* stop retransmitting an INVITE that has not received a response */
06340             /* if we can't send right now, mark it pending */
06341             if (p->invitestate == INV_CALLING) {
06342                /* We can't send anything in CALLING state */
06343                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
06344                /* 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. */
06345                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06346                append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
06347             } else {
06348                struct sip_pkt *cur;
06349 
06350                for (cur = p->packets; cur; cur = cur->next) {
06351                   __sip_semi_ack(p, cur->seqno, cur->is_resp, cur->method ? cur->method : find_sip_method(cur->data->str));
06352                }
06353                p->invitestate = INV_CANCELLED;
06354                /* Send a new request: CANCEL */
06355                transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
06356                /* Actually don't destroy us yet, wait for the 487 on our original 
06357                   INVITE, but do set an autodestruct just in case we never get it. */
06358                needdestroy = 0;
06359                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06360             }
06361          } else { /* Incoming call, not up */
06362             const char *res;
06363             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"));
06364             if (p->hangupcause && (res = hangup_cause2sip(p->hangupcause)))
06365                transmit_response_reliable(p, res, &p->initreq);
06366             else 
06367                transmit_response_reliable(p, "603 Declined", &p->initreq);
06368             p->invitestate = INV_TERMINATED;
06369          }
06370       } else { /* Call is in UP state, send BYE */
06371          if (p->stimer->st_active == TRUE) {
06372             stop_session_timer(p);
06373          }
06374 
06375          if (!p->pendinginvite) {
06376             struct ast_channel *bridge = ast_bridged_channel(oldowner);
06377             char *audioqos = "";
06378             char *videoqos = "";
06379             char *textqos = "";
06380 
06381             /* We need to get the lock on bridge because ast_rtp_set_vars will attempt
06382              * to lock the bridge. This may get hairy...
06383              */
06384             while (bridge && ast_channel_trylock(bridge)) {
06385                sip_pvt_unlock(p);
06386                do {
06387                   /* Use oldowner since p->owner is already NULL */
06388                   CHANNEL_DEADLOCK_AVOIDANCE(oldowner);
06389                } while (sip_pvt_trylock(p));
06390                bridge = ast_bridged_channel(oldowner);
06391             }
06392 
06393             if (p->rtp)
06394                ast_rtp_set_vars(oldowner, p->rtp);
06395 
06396             if (bridge) {
06397                struct sip_pvt *q = bridge->tech_pvt;
06398 
06399                if (IS_SIP_TECH(bridge->tech) && q && q->rtp)
06400                   ast_rtp_set_vars(bridge, q->rtp);
06401                ast_channel_unlock(bridge);
06402             }
06403 
06404             if (p->vrtp)
06405                videoqos = ast_rtp_get_quality(p->vrtp, NULL, RTPQOS_SUMMARY);
06406             if (p->trtp)
06407                textqos = ast_rtp_get_quality(p->trtp, NULL, RTPQOS_SUMMARY);
06408             /* Send a hangup */
06409             if (oldowner->_state == AST_STATE_UP) {
06410                transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
06411             }
06412 
06413             /* Get RTCP quality before end of call */
06414             if (p->do_history) {
06415                if (p->rtp)
06416                   append_history(p, "RTCPaudio", "Quality:%s", audioqos);
06417                if (p->vrtp)
06418                   append_history(p, "RTCPvideo", "Quality:%s", videoqos);
06419                if (p->trtp)
06420                   append_history(p, "RTCPtext", "Quality:%s", textqos);
06421             }
06422             if (p->rtp && oldowner)
06423                pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", audioqos);
06424             if (p->vrtp && oldowner)
06425                pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", videoqos);
06426             if (p->trtp && oldowner)
06427                pbx_builtin_setvar_helper(oldowner, "RTPTEXTQOS", textqos);
06428          } else {
06429             /* Note we will need a BYE when this all settles out
06430                but we can't send one while we have "INVITE" outstanding. */
06431             ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
06432             ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE); 
06433             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"));
06434             if (sip_cancel_destroy(p))
06435                ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
06436          }
06437       }
06438    }
06439    if (needdestroy) {
06440       pvt_set_needdestroy(p, "hangup");
06441    }
06442    sip_pvt_unlock(p);
06443    return 0;
06444 }
06445 
06446 /*! \brief Try setting codec suggested by the SIP_CODEC channel variable */
06447 static void try_suggested_sip_codec(struct sip_pvt *p)
06448 {
06449    int fmt;
06450    const char *codec;
06451 
06452    codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
06453    if (!codec) 
06454       return;
06455 
06456    fmt = ast_getformatbyname(codec);
06457    if (fmt) {
06458       ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
06459       if (p->jointcapability & fmt) {
06460          p->jointcapability &= fmt;
06461          p->capability &= fmt;
06462       } else
06463          ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
06464    } else
06465       ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
06466    return;  
06467 }
06468 
06469 /*! \brief  sip_answer: Answer SIP call , send 200 OK on Invite 
06470  * Part of PBX interface */
06471 static int sip_answer(struct ast_channel *ast)
06472 {
06473    int res = 0;
06474    struct sip_pvt *p = ast->tech_pvt;
06475 
06476    sip_pvt_lock(p);
06477    if (ast->_state != AST_STATE_UP) {
06478       try_suggested_sip_codec(p);   
06479 
06480       ast_setstate(ast, AST_STATE_UP);
06481       ast_debug(1, "SIP answering channel: %s\n", ast->name);
06482       ast_rtp_new_source(p->rtp);
06483       res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL, FALSE);
06484       ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
06485    }
06486    sip_pvt_unlock(p);
06487    return res;
06488 }
06489 
06490 /*! \brief Send frame to media channel (rtp) */
06491 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
06492 {
06493    struct sip_pvt *p = ast->tech_pvt;
06494    int res = 0;
06495 
06496    switch (frame->frametype) {
06497    case AST_FRAME_VOICE:
06498       if (!(frame->subclass & ast->nativeformats)) {
06499          char s1[512], s2[512], s3[512];
06500          ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %s(%d) read/write = %s(%d)/%s(%d)\n",
06501             frame->subclass, 
06502             ast_getformatname_multiple(s1, sizeof(s1) - 1, ast->nativeformats & AST_FORMAT_AUDIO_MASK),
06503             ast->nativeformats & AST_FORMAT_AUDIO_MASK,
06504             ast_getformatname_multiple(s2, sizeof(s2) - 1, ast->readformat),
06505             ast->readformat,
06506             ast_getformatname_multiple(s3, sizeof(s3) - 1, ast->writeformat),
06507             ast->writeformat);
06508          return 0;
06509       }
06510       if (p) {
06511          sip_pvt_lock(p);
06512          if (p->t38.state == T38_ENABLED) {
06513             /* drop frame, can't sent VOICE frames while in T.38 mode */
06514             sip_pvt_unlock(p);
06515             break;
06516          } else if (p->rtp) {
06517             /* If channel is not up, activate early media session */
06518             if ((ast->_state != AST_STATE_UP) &&
06519                 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06520                 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06521                ast_rtp_new_source(p->rtp);
06522                if (!global_prematuremediafilter) {
06523                   p->invitestate = INV_EARLY_MEDIA;
06524                   transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06525                   ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06526                }
06527             }
06528             p->lastrtptx = time(NULL);
06529             res = ast_rtp_write(p->rtp, frame);
06530          }
06531          sip_pvt_unlock(p);
06532       }
06533       break;
06534    case AST_FRAME_VIDEO:
06535       if (p) {
06536          sip_pvt_lock(p);
06537          if (p->vrtp) {
06538             /* Activate video early media */
06539             if ((ast->_state != AST_STATE_UP) &&
06540                 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06541                 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06542                p->invitestate = INV_EARLY_MEDIA;
06543                transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06544                ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06545             }
06546             p->lastrtptx = time(NULL);
06547             res = ast_rtp_write(p->vrtp, frame);
06548          }
06549          sip_pvt_unlock(p);
06550       }
06551       break;
06552    case AST_FRAME_TEXT:
06553       if (p) {
06554          sip_pvt_lock(p);
06555          if (p->red) {
06556             red_buffer_t140(p->trtp, frame);
06557          } else {
06558             if (p->trtp) {
06559                /* Activate text early media */
06560                if ((ast->_state != AST_STATE_UP) &&
06561                    !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06562                    !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06563                   p->invitestate = INV_EARLY_MEDIA;
06564                   transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06565                   ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06566                }
06567                p->lastrtptx = time(NULL);
06568                res = ast_rtp_write(p->trtp, frame);
06569             }
06570          }
06571          sip_pvt_unlock(p);
06572       }
06573       break;
06574    case AST_FRAME_IMAGE:
06575       return 0;
06576       break;
06577    case AST_FRAME_MODEM:
06578       if (p) {
06579          sip_pvt_lock(p);
06580          /* UDPTL requires two-way communication, so early media is not needed here.
06581             we simply forget the frames if we get modem frames before the bridge is up.
06582             Fax will re-transmit.
06583          */
06584          if ((ast->_state == AST_STATE_UP) &&
06585              p->udptl &&
06586              (p->t38.state == T38_ENABLED)) {
06587             res = ast_udptl_write(p->udptl, frame);
06588          }
06589          sip_pvt_unlock(p);
06590       }
06591       break;
06592    default: 
06593       ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
06594       return 0;
06595    }
06596 
06597    return res;
06598 }
06599 
06600 /*! \brief  sip_fixup: Fix up a channel:  If a channel is consumed, this is called.
06601         Basically update any ->owner links */
06602 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
06603 {
06604    int ret = -1;
06605    struct sip_pvt *p;
06606 
06607    if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE))
06608       ast_debug(1, "New channel is zombie\n");
06609    if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE))
06610       ast_debug(1, "Old channel is zombie\n");
06611 
06612    if (!newchan || !newchan->tech_pvt) {
06613       if (!newchan)
06614          ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
06615       else
06616          ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
06617       return -1;
06618    }
06619    p = newchan->tech_pvt;
06620 
06621    sip_pvt_lock(p);
06622    append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
06623    append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
06624    if (p->owner != oldchan)
06625       ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
06626    else {
06627       p->owner = newchan;
06628       /* Re-invite RTP back to Asterisk. Needed if channel is masqueraded out of a native
06629          RTP bridge (i.e., RTP not going through Asterisk): RTP bridge code might not be
06630          able to do this if the masquerade happens before the bridge breaks (e.g., AMI
06631          redirect of both channels). Note that a channel can not be masqueraded *into*
06632          a native bridge. So there is no danger that this breaks a native bridge that
06633          should stay up. */
06634       sip_set_rtp_peer(newchan, NULL, NULL, 0, 0, 0);
06635       ret = 0;
06636    }
06637    ast_debug(3, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);
06638 
06639    sip_pvt_unlock(p);
06640    return ret;
06641 }
06642 
06643 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
06644 {
06645    struct sip_pvt *p = ast->tech_pvt;
06646    int res = 0;
06647 
06648    sip_pvt_lock(p);
06649    switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06650    case SIP_DTMF_INBAND:
06651       res = -1; /* Tell Asterisk to generate inband indications */
06652       break;
06653    case SIP_DTMF_RFC2833:
06654       if (p->rtp)
06655          ast_rtp_senddigit_begin(p->rtp, digit);
06656       break;
06657    default:
06658       break;
06659    }
06660    sip_pvt_unlock(p);
06661 
06662    return res;
06663 }
06664 
06665 /*! \brief Send DTMF character on SIP channel
06666    within one call, we're able to transmit in many methods simultaneously */
06667 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
06668 {
06669    struct sip_pvt *p = ast->tech_pvt;
06670    int res = 0;
06671 
06672    sip_pvt_lock(p);
06673    switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06674    case SIP_DTMF_INFO:
06675    case SIP_DTMF_SHORTINFO:
06676       transmit_info_with_digit(p, digit, duration);
06677       break;
06678    case SIP_DTMF_RFC2833:
06679       if (p->rtp)
06680          ast_rtp_senddigit_end_with_duration(p->rtp, digit, duration);
06681       break;
06682    case SIP_DTMF_INBAND:
06683       res = -1; /* Tell Asterisk to stop inband indications */
06684       break;
06685    }
06686    sip_pvt_unlock(p);
06687 
06688    return res;
06689 }
06690 
06691 /*! \brief Transfer SIP call */
06692 static int sip_transfer(struct ast_channel *ast, const char *dest)
06693 {
06694    struct sip_pvt *p = ast->tech_pvt;
06695    int res;
06696 
06697    if (dest == NULL) /* functions below do not take a NULL */
06698       dest = "";
06699    sip_pvt_lock(p);
06700    if (ast->_state == AST_STATE_RING)
06701       res = sip_sipredirect(p, dest);
06702    else
06703       res = transmit_refer(p, dest);
06704    sip_pvt_unlock(p);
06705    return res;
06706 }
06707 
06708 /*! \brief Helper function which updates T.38 capability information and triggers a reinvite */
06709 static int interpret_t38_parameters(struct sip_pvt *p, const struct ast_control_t38_parameters *parameters)
06710 {
06711    int res = 0;
06712 
06713    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) || !p->udptl) {
06714       return -1;
06715    }
06716    switch (parameters->request_response) {
06717    case AST_T38_NEGOTIATED:
06718    case AST_T38_REQUEST_NEGOTIATE:         /* Request T38 */
06719       /* Negotiation can not take place without a valid max_ifp value. */
06720       if (!parameters->max_ifp) {
06721          change_t38_state(p, T38_DISABLED);
06722          if (p->t38.state == T38_PEER_REINVITE) {
06723             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"));
06724             transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06725          }
06726          break;
06727       } else if (p->t38.state == T38_PEER_REINVITE) {
06728          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"));
06729          p->t38.our_parms = *parameters;
06730          /* modify our parameters to conform to the peer's parameters,
06731           * based on the rules in the ITU T.38 recommendation
06732           */
06733          if (!p->t38.their_parms.fill_bit_removal) {
06734             p->t38.our_parms.fill_bit_removal = FALSE;
06735          }
06736          if (!p->t38.their_parms.transcoding_mmr) {
06737             p->t38.our_parms.transcoding_mmr = FALSE;
06738          }
06739          if (!p->t38.their_parms.transcoding_jbig) {
06740             p->t38.our_parms.transcoding_jbig = FALSE;
06741          }
06742          p->t38.our_parms.version = MIN(p->t38.our_parms.version, p->t38.their_parms.version);
06743          p->t38.our_parms.rate_management = p->t38.their_parms.rate_management;
06744          ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06745          change_t38_state(p, T38_ENABLED);
06746          transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
06747       } else if (p->t38.state != T38_ENABLED) {
06748          p->t38.our_parms = *parameters;
06749          ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06750          change_t38_state(p, T38_LOCAL_REINVITE);
06751          if (!p->pendinginvite) {
06752             transmit_reinvite_with_sdp(p, TRUE, FALSE);
06753          } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
06754             ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
06755          }
06756       }
06757       break;
06758    case AST_T38_TERMINATED:
06759    case AST_T38_REFUSED:
06760    case AST_T38_REQUEST_TERMINATE:         /* Shutdown T38 */
06761       if (p->t38.state == T38_PEER_REINVITE) {
06762          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"));
06763          change_t38_state(p, T38_DISABLED);
06764          transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06765       } else if (p->t38.state == T38_ENABLED)
06766          transmit_reinvite_with_sdp(p, FALSE, FALSE);
06767       break;
06768    case AST_T38_REQUEST_PARMS: {    /* Application wants remote's parameters re-sent */
06769       struct ast_control_t38_parameters parameters = p->t38.their_parms;
06770 
06771       if (p->t38.state == T38_PEER_REINVITE) {
06772          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"));
06773          parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
06774          parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
06775          ast_queue_control_data(p->owner, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
06776          /* we need to return a positive value here, so that applications that
06777           * send this request can determine conclusively whether it was accepted or not...
06778           * older versions of chan_sip would just silently accept it and return zero.
06779           */
06780          res = AST_T38_REQUEST_PARMS;
06781       }
06782       break;
06783    }
06784    default:
06785       res = -1;
06786       break;
06787    }
06788 
06789    return res;
06790 }
06791 
06792 /*! \brief Play indication to user 
06793  * With SIP a lot of indications is sent as messages, letting the device play
06794    the indication - busy signal, congestion etc 
06795    \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
06796 */
06797 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
06798 {
06799    struct sip_pvt *p = ast->tech_pvt;
06800    int res = 0;
06801 
06802    sip_pvt_lock(p);
06803    switch(condition) {
06804    case AST_CONTROL_RINGING:
06805       if (ast->_state == AST_STATE_RING) {
06806          p->invitestate = INV_EARLY_MEDIA;
06807          if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
06808              (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {            
06809             /* Send 180 ringing if out-of-band seems reasonable */
06810             transmit_provisional_response(p, "180 Ringing", &p->initreq, 0);
06811             ast_set_flag(&p->flags[0], SIP_RINGING);
06812             if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
06813                break;
06814          } else {
06815             /* Well, if it's not reasonable, just send in-band */
06816          }
06817       }
06818       res = -1;
06819       break;
06820    case AST_CONTROL_BUSY:
06821       if (ast->_state != AST_STATE_UP) {
06822          transmit_response_reliable(p, "486 Busy Here", &p->initreq);
06823          p->invitestate = INV_COMPLETED;
06824          sip_alreadygone(p);
06825          ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06826          break;
06827       }
06828       res = -1;
06829       break;
06830    case AST_CONTROL_CONGESTION:
06831       if (ast->_state != AST_STATE_UP) {
06832          transmit_response_reliable(p, "503 Service Unavailable", &p->initreq);
06833          p->invitestate = INV_COMPLETED;
06834          sip_alreadygone(p);
06835          ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06836          break;
06837       }
06838       res = -1;
06839       break;
06840    case AST_CONTROL_PROCEEDING:
06841       if ((ast->_state != AST_STATE_UP) &&
06842           !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06843           !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06844          transmit_response(p, "100 Trying", &p->initreq);
06845          p->invitestate = INV_PROCEEDING;  
06846          break;
06847       }
06848       res = -1;
06849       break;
06850    case AST_CONTROL_PROGRESS:
06851       if ((ast->_state != AST_STATE_UP) &&
06852           !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06853           !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06854          p->invitestate = INV_EARLY_MEDIA;
06855          transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06856          ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06857          break;
06858       }
06859       res = -1;
06860       break;
06861    case AST_CONTROL_HOLD:
06862       ast_rtp_new_source(p->rtp);
06863       ast_moh_start(ast, data, p->mohinterpret);
06864       break;
06865    case AST_CONTROL_UNHOLD:
06866       ast_rtp_new_source(p->rtp);
06867       ast_moh_stop(ast);
06868       break;
06869    case AST_CONTROL_VIDUPDATE:   /* Request a video frame update */
06870       if (p->vrtp && !p->novideo) {
06871          transmit_info_with_vidupdate(p);
06872          /* ast_rtcp_send_h261fur(p->vrtp); */
06873       } else
06874          res = -1;
06875       break;
06876    case AST_CONTROL_T38_PARAMETERS:
06877       if (datalen != sizeof(struct ast_control_t38_parameters)) {
06878          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);
06879          res = -1;
06880       } else {
06881          const struct ast_control_t38_parameters *parameters = data;
06882          res = interpret_t38_parameters(p, parameters);
06883       }
06884       break;
06885    case AST_CONTROL_SRCUPDATE:
06886       ast_rtp_new_source(p->rtp);
06887       break;
06888    case AST_CONTROL_SRCCHANGE:
06889       ast_rtp_change_source(p->rtp);
06890       break;
06891    case -1:
06892       res = -1;
06893       break;
06894    default:
06895       ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
06896       res = -1;
06897       break;
06898    }
06899    sip_pvt_unlock(p);
06900    return res;
06901 }
06902 
06903 
06904 /*! \brief Initiate a call in the SIP channel
06905    called from sip_request_call (calls from the pbx ) for outbound channels
06906    and from handle_request_invite for inbound channels
06907    
06908 */
06909 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title)
06910 {
06911    struct ast_channel *tmp;
06912    struct ast_variable *v = NULL;
06913    int fmt;
06914    int what;
06915    int video;
06916    int text;
06917    int needvideo = 0;
06918    int needtext = 0;
06919    char buf[SIPBUFSIZE];
06920    char *decoded_exten;
06921 
06922    {
06923       const char *my_name; /* pick a good name */
06924    
06925       if (title) {
06926          my_name = title;
06927       } else {
06928          char *port = NULL;
06929          my_name = ast_strdupa(i->fromdomain);
06930          if ((port = strchr(i->fromdomain, ':'))) {
06931             *port = '\0';
06932          }
06933       }
06934 
06935       sip_pvt_unlock(i);
06936       /* Don't hold a sip pvt lock while we allocate a channel */
06937       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));
06938 
06939    }
06940    if (!tmp) {
06941       ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
06942       sip_pvt_lock(i);
06943       return NULL;
06944    }
06945    sip_pvt_lock(i);
06946 
06947    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;
06948 
06949    /* Select our native format based on codec preference until we receive
06950       something from another device to the contrary. */
06951    if (i->jointcapability) {  /* The joint capabilities of us and peer */
06952       what = i->jointcapability;
06953       video = i->jointcapability & AST_FORMAT_VIDEO_MASK;
06954       text = i->jointcapability & AST_FORMAT_TEXT_MASK;
06955    } else if (i->capability) {      /* Our configured capability for this peer */
06956       what = i->capability;
06957       video = i->capability & AST_FORMAT_VIDEO_MASK;
06958       text = i->capability & AST_FORMAT_TEXT_MASK;
06959    } else {
06960       what = global_capability;  /* Global codec support */
06961       video = global_capability & AST_FORMAT_VIDEO_MASK;
06962       text = global_capability & AST_FORMAT_TEXT_MASK;
06963    }
06964 
06965    /* Set the native formats for audio  and merge in video */
06966    tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | video | text;
06967    ast_debug(3, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmp->nativeformats));
06968    ast_debug(3, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcapability));
06969    ast_debug(3, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->capability));
06970    ast_debug(3, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, ast_codec_choose(&i->prefs, what, 1)));
06971    if (i->prefcodec)
06972       ast_debug(3, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcodec));
06973 
06974    /* XXX Why are we choosing a codec from the native formats?? */
06975    fmt = ast_best_codec(tmp->nativeformats);
06976 
06977    /* If we have a prefcodec setting, we have an inbound channel that set a 
06978       preferred format for this call. Otherwise, we check the jointcapability
06979       We also check for vrtp. If it's not there, we are not allowed do any video anyway.
06980     */
06981    if (i->vrtp) {
06982       if (ast_test_flag(&i->flags[1], SIP_PAGE2_VIDEOSUPPORT))
06983          needvideo = AST_FORMAT_VIDEO_MASK;
06984       else if (i->prefcodec)
06985          needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK;  /* Outbound call */
06986       else
06987          needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK;  /* Inbound call */
06988    }
06989 
06990    if (i->trtp) {
06991       if (i->prefcodec)
06992          needtext = i->prefcodec & AST_FORMAT_TEXT_MASK; /* Outbound call */
06993       else
06994          needtext = i->jointcapability & AST_FORMAT_TEXT_MASK; /* Inbound call */
06995    }
06996 
06997    if (needvideo) 
06998       ast_debug(3, "This channel can handle video! HOLLYWOOD next!\n");
06999    else
07000       ast_debug(3, "This channel will not be able to handle video.\n");
07001 
07002    if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) || (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) ||
07003        (ast_test_flag(&i->flags[1], SIP_PAGE2_FAX_DETECT))) {
07004       int features = 0;
07005 
07006       if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) || (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
07007          features |= DSP_FEATURE_DIGIT_DETECT;
07008       }
07009 
07010       if (ast_test_flag(&i->flags[1], SIP_PAGE2_FAX_DETECT)) {
07011          features |= DSP_FEATURE_FAX_DETECT;
07012       }
07013 
07014       i->dsp = ast_dsp_new();
07015       ast_dsp_set_features(i->dsp, features);
07016       if (global_relaxdtmf)
07017          ast_dsp_set_digitmode(i->dsp, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
07018          }
07019 
07020    /* Set file descriptors for audio, video, realtime text and UDPTL as needed */
07021    if (i->rtp) {
07022       ast_channel_set_fd(tmp, 0, ast_rtp_fd(i->rtp));
07023       ast_channel_set_fd(tmp, 1, ast_rtcp_fd(i->rtp));
07024    }
07025    if (needvideo && i->vrtp) {
07026       ast_channel_set_fd(tmp, 2, ast_rtp_fd(i->vrtp));
07027       ast_channel_set_fd(tmp, 3, ast_rtcp_fd(i->vrtp));
07028    }
07029    if (needtext && i->trtp) 
07030       ast_channel_set_fd(tmp, 4, ast_rtp_fd(i->trtp));
07031    if (i->udptl)
07032       ast_channel_set_fd(tmp, 5, ast_udptl_fd(i->udptl));
07033 
07034    if (state == AST_STATE_RING)
07035       tmp->rings = 1;
07036    tmp->adsicpe = AST_ADSI_UNAVAILABLE;
07037    tmp->writeformat = fmt;
07038    tmp->rawwriteformat = fmt;
07039    tmp->readformat = fmt;
07040    tmp->rawreadformat = fmt;
07041    tmp->tech_pvt = dialog_ref(i, "sip_new: set chan->tech_pvt to i");
07042 
07043    tmp->callgroup = i->callgroup;
07044    tmp->pickupgroup = i->pickupgroup;
07045    tmp->cid.cid_pres = i->callingpres;
07046    if (!ast_strlen_zero(i->parkinglot))
07047       ast_string_field_set(tmp, parkinglot, i->parkinglot);
07048    if (!ast_strlen_zero(i->accountcode))
07049       ast_string_field_set(tmp, accountcode, i->accountcode);
07050    if (i->amaflags)
07051       tmp->amaflags = i->amaflags;
07052    if (!ast_strlen_zero(i->language))
07053       ast_string_field_set(tmp, language, i->language);
07054    i->owner = tmp;
07055    ast_module_ref(ast_module_info->self);
07056    ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
07057    /*Since it is valid to have extensions in the dialplan that have unescaped characters in them
07058     * we should decode the uri before storing it in the channel, but leave it encoded in the sip_pvt
07059     * structure so that there aren't issues when forming URI's
07060     */
07061    if (ast_exists_extension(NULL, i->context, i->exten, 1, i->cid_num)) {
07062       /* encoded in dialplan, so keep extension encoded */
07063       ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
07064    } else {
07065       decoded_exten = ast_strdupa(i->exten);
07066       ast_uri_decode(decoded_exten);
07067       ast_copy_string(tmp->exten, decoded_exten, sizeof(tmp->exten));
07068    }
07069 
07070    /* Don't use ast_set_callerid() here because it will
07071     * generate an unnecessary NewCallerID event  */
07072    tmp->cid.cid_ani = ast_strdup(i->cid_num);
07073    if (!ast_strlen_zero(i->rdnis))
07074       tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
07075    
07076    if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
07077       tmp->cid.cid_dnid = ast_strdup(i->exten);
07078 
07079    tmp->priority = 1;
07080    if (!ast_strlen_zero(i->uri))
07081       pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
07082    if (!ast_strlen_zero(i->domain))
07083       pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
07084    if (!ast_strlen_zero(i->callid))
07085       pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
07086    if (i->rtp)
07087       ast_jb_configure(tmp, &global_jbconf);
07088 
07089    /* Set channel variables for this call from configuration */
07090    for (v = i->chanvars ; v ; v = v->next) {
07091       char valuebuf[1024];
07092       pbx_builtin_setvar_helper(tmp, v->name, ast_get_encoded_str(v->value, valuebuf, sizeof(valuebuf)));
07093    }
07094 
07095    if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
07096       ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
07097       tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
07098       ast_hangup(tmp);
07099       tmp = NULL;
07100    }
07101 
07102    if (i->do_history)
07103       append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);
07104 
07105    /* Inform manager user about new channel and their SIP call ID */
07106    if (sip_cfg.callevents)
07107       manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
07108          "Channel: %s\r\nUniqueid: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\n",
07109          tmp->name, tmp->uniqueid, "SIP", i->callid, i->fullcontact);
07110 
07111    return tmp;
07112 }
07113 
07114 /*! \brief Reads one line of SIP message body */
07115 static char *get_body_by_line(const char *line, const char *name, int nameLen, char delimiter)
07116 {
07117    if (!strncasecmp(line, name, nameLen) && line[nameLen] == delimiter)
07118       return ast_skip_blanks(line + nameLen + 1);
07119 
07120    return "";
07121 }
07122 
07123 /*! \brief Lookup 'name' in the SDP starting
07124  * at the 'start' line. Returns the matching line, and 'start'
07125  * is updated with the next line number.
07126  */
07127 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
07128 {
07129    int len = strlen(name);
07130 
07131    while (*start < (req->sdp_start + req->sdp_count)) {
07132       const char *r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[(*start)++]), name, len, '=');
07133       if (r[0] != '\0')
07134          return r;
07135    }
07136 
07137    /* if the line was not found, ensure that *start points past the SDP */
07138    (*start)++;
07139 
07140    return "";
07141 }
07142 
07143 /*! \brief Fetches the next valid SDP line between the 'start' line
07144  * (inclusive) and the 'stop' line (exclusive). Returns the type
07145  * ('a', 'c', ...) and matching line in reference 'start' is updated
07146  * with the next line number.
07147  */
07148 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value)
07149 {
07150    char type = '\0';
07151    const char *line = NULL;
07152 
07153    if (stop > (req->sdp_start + req->sdp_count)) {
07154       stop = req->sdp_start + req->sdp_count;
07155    }
07156 
07157    while (*start < stop) {
07158       line = REQ_OFFSET_TO_STR(req, line[(*start)++]);
07159       if (line[1] == '=') {
07160          type = line[0];
07161          *value = ast_skip_blanks(line + 2);
07162          break;
07163       }
07164    }
07165 
07166    return type;
07167 }
07168 
07169 /*! \brief Get a specific line from the message body */
07170 static char *get_body(struct sip_request *req, char *name, char delimiter) 
07171 {
07172    int x;
07173    int len = strlen(name);
07174    char *r;
07175 
07176    for (x = 0; x < req->lines; x++) {
07177       r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[x]), name, len, delimiter);
07178       if (r[0] != '\0')
07179          return r;
07180    }
07181 
07182    return "";
07183 }
07184 
07185 /*! \brief Find compressed SIP alias */
07186 static const char *find_alias(const char *name, const char *_default)
07187 {
07188    /*! \brief Structure for conversion between compressed SIP and "normal" SIP */
07189    static const struct cfalias {
07190       char * const fullname;
07191       char * const shortname;
07192    } aliases[] = {
07193       { "Content-Type",  "c" },
07194       { "Content-Encoding",    "e" },
07195       { "From",       "f" },
07196       { "Call-ID",       "i" },
07197       { "Contact",       "m" },
07198       { "Content-Length",   "l" },
07199       { "Subject",       "s" },
07200       { "To",         "t" },
07201       { "Supported",     "k" },
07202       { "Refer-To",      "r" },
07203       { "Referred-By",   "b" },
07204       { "Allow-Events",  "u" },
07205       { "Event",      "o" },
07206       { "Via",     "v" },
07207       { "Accept-Contact",      "a" },
07208       { "Reject-Contact",      "j" },
07209       { "Request-Disposition", "d" },
07210       { "Session-Expires",     "x" },
07211       { "Identity",            "y" },
07212       { "Identity-Info",       "n" },
07213    };
07214    int x;
07215 
07216    for (x = 0; x < ARRAY_LEN(aliases); x++) {
07217       if (!strcasecmp(aliases[x].fullname, name))
07218          return aliases[x].shortname;
07219    }
07220 
07221    return _default;
07222 }
07223 
07224 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
07225 {
07226    int pass;
07227 
07228    /*
07229     * Technically you can place arbitrary whitespace both before and after the ':' in
07230     * a header, although RFC3261 clearly says you shouldn't before, and place just
07231     * one afterwards.  If you shouldn't do it, what absolute idiot decided it was 
07232     * a good idea to say you can do it, and if you can do it, why in the hell would.
07233     * you say you shouldn't.
07234     * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
07235     * and we always allow spaces after that for compatibility.
07236     */
07237    for (pass = 0; name && pass < 2;pass++) {
07238       int x, len = strlen(name);
07239       for (x = *start; x < req->headers; x++) {
07240          char *header = REQ_OFFSET_TO_STR(req, header[x]);
07241          if (!strncasecmp(header, name, len)) {
07242             char *r = header + len; /* skip name */
07243             if (sip_cfg.pedanticsipchecking)
07244                r = ast_skip_blanks(r);
07245 
07246             if (*r == ':') {
07247                *start = x+1;
07248                return ast_skip_blanks(r+1);
07249             }
07250          }
07251       }
07252       if (pass == 0) /* Try aliases */
07253          name = find_alias(name, NULL);
07254    }
07255 
07256    /* Don't return NULL, so get_header is always a valid pointer */
07257    return "";
07258 }
07259 
07260 /*! \brief Get header from SIP request 
07261    \return Always return something, so don't check for NULL because it won't happen :-)
07262 */
07263 static const char *get_header(const struct sip_request *req, const char *name)
07264 {
07265    int start = 0;
07266    return __get_header(req, name, &start);
07267 }
07268 
07269 /*! \brief Read RTP from network */
07270 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
07271 {
07272    /* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
07273    struct ast_frame *f;
07274    
07275    if (!p->rtp) {
07276       /* We have no RTP allocated for this channel */
07277       return &ast_null_frame;
07278    }
07279 
07280    switch(ast->fdno) {
07281    case 0:
07282       f = ast_rtp_read(p->rtp);  /* RTP Audio */
07283       break;
07284    case 1:
07285       f = ast_rtcp_read(p->rtp); /* RTCP Control Channel */
07286       break;
07287    case 2:
07288       f = ast_rtp_read(p->vrtp); /* RTP Video */
07289       break;
07290    case 3:
07291       f = ast_rtcp_read(p->vrtp);   /* RTCP Control Channel for video */
07292       break;
07293    case 4:
07294       f = ast_rtp_read(p->trtp); /* RTP Text */
07295       if (sipdebug_text) {
07296          int i;
07297          unsigned char* arr = f->data.ptr;
07298          for (i=0; i < f->datalen; i++)
07299             ast_verbose("%c", (arr[i] > ' ' && arr[i] < '}') ? arr[i] : '.');
07300          ast_verbose(" -> ");
07301          for (i=0; i < f->datalen; i++)
07302             ast_verbose("%02X ", arr[i]);
07303          ast_verbose("\n");
07304       }
07305       break;
07306    case 5:
07307       f = ast_udptl_read(p->udptl); /* UDPTL for T.38 */
07308       break;
07309    default:
07310       f = &ast_null_frame;
07311    }
07312    /* Don't forward RFC2833 if we're not supposed to */
07313    if (f && (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) &&
07314        (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833)) {
07315       ast_debug(1, "Ignoring DTMF (%c) RTP frame because dtmfmode is not RFC2833\n", f->subclass);
07316       return &ast_null_frame;
07317    }
07318 
07319    /* We already hold the channel lock */
07320    if (!p->owner || (f && f->frametype != AST_FRAME_VOICE))
07321       return f;
07322 
07323    if (f && f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
07324       if (!(f->subclass & p->jointcapability)) {
07325          ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
07326             ast_getformatname(f->subclass), p->owner->name);
07327          return &ast_null_frame;
07328       }
07329       ast_debug(1, "Oooh, format changed to %d %s\n",
07330          f->subclass, ast_getformatname(f->subclass));
07331       p->owner->nativeformats = (p->owner->nativeformats & (AST_FORMAT_VIDEO_MASK | AST_FORMAT_TEXT_MASK)) | f->subclass;
07332       ast_set_read_format(p->owner, p->owner->readformat);
07333       ast_set_write_format(p->owner, p->owner->writeformat);
07334    }
07335 
07336    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) {
07337       f = ast_dsp_process(p->owner, p->dsp, f);
07338                 if (f && f->frametype == AST_FRAME_DTMF) {
07339          if (f->subclass == 'f') {
07340                                 if (option_debug)
07341                                         ast_log(LOG_DEBUG, "Fax CNG detected on %s\n", ast->name);
07342                                 *faxdetect = 1;
07343             /* If we only needed this DSP for fax detection purposes we can just drop it now */
07344             if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
07345                ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
07346             } else {
07347                ast_dsp_free(p->dsp);
07348                p->dsp = NULL;
07349             }
07350          } else {
07351             ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass);
07352          }
07353       }
07354    }
07355    
07356    return f;
07357 }
07358 
07359 /*! \brief Read SIP RTP from channel */
07360 static struct ast_frame *sip_read(struct ast_channel *ast)
07361 {
07362    struct ast_frame *fr;
07363    struct sip_pvt *p = ast->tech_pvt;
07364    int faxdetected = FALSE;
07365 
07366    sip_pvt_lock(p);
07367    fr = sip_rtp_read(ast, p, &faxdetected);
07368    p->lastrtprx = time(NULL);
07369 
07370    /* If we detect a CNG tone and fax detection is enabled then send us off to the fax extension */
07371    if (faxdetected && ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
07372       if (strcmp(ast->exten, "fax")) {
07373          const char *target_context = S_OR(ast->macrocontext, ast->context);
07374          /* We need to unlock 'ast' here because
07375           * ast_exists_extension has the potential to start and
07376           * stop an autoservice on the channel. Such action is
07377           * prone to deadlock if the channel is locked.
07378           */
07379          sip_pvt_unlock(p);
07380          ast_channel_unlock(ast);
07381          if (ast_exists_extension(ast, target_context, "fax", 1, ast->cid.cid_num)) {
07382             ast_channel_lock(ast);
07383             sip_pvt_lock(p);
07384             ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to CNG detection\n", ast->name);
07385             pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
07386             if (ast_async_goto(ast, target_context, "fax", 1)) {
07387                ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast->name, target_context);
07388             }
07389             fr = &ast_null_frame;
07390          } else {
07391             ast_channel_lock(ast);
07392             sip_pvt_lock(p);
07393             ast_log(LOG_NOTICE, "FAX CNG detected but no fax extension\n");
07394                         }
07395                 }
07396         }
07397 
07398    /* Only allow audio through if they sent progress with SDP, or if the channel is actually answered */
07399    if (fr && fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast->_state != AST_STATE_UP) {
07400       fr = &ast_null_frame;
07401    }
07402 
07403    sip_pvt_unlock(p);
07404 
07405    return fr;
07406 }
07407 
07408 
07409 /*! \brief Generate 32 byte random string for callid's etc */
07410 static char *generate_random_string(char *buf, size_t size)
07411 {
07412    long val[4];
07413    int x;
07414 
07415    for (x=0; x<4; x++)
07416       val[x] = ast_random();
07417    snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
07418 
07419    return buf;
07420 }
07421 
07422 /*! \brief Build SIP Call-ID value for a non-REGISTER transaction */
07423 static void build_callid_pvt(struct sip_pvt *pvt)
07424 {
07425    char buf[33];
07426 
07427    const char *host = S_OR(pvt->fromdomain, ast_inet_ntoa(pvt->ourip.sin_addr));
07428    
07429    ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07430 
07431 }
07432 
07433 /*! \brief Build SIP Call-ID value for a REGISTER transaction */
07434 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain)
07435 {
07436    char buf[33];
07437 
07438    const char *host = S_OR(fromdomain, ast_inet_ntoa(ourip));
07439 
07440    ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07441 }
07442 
07443 /*! \brief Make our SIP dialog tag */
07444 static void make_our_tag(char *tagbuf, size_t len)
07445 {
07446    snprintf(tagbuf, len, "as%08lx", ast_random());
07447 }
07448 
07449 /*! \brief Allocate Session-Timers struct w/in dialog */
07450 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
07451 {
07452    struct sip_st_dlg *stp;
07453 
07454    if (p->stimer) {
07455       ast_log(LOG_ERROR, "Session-Timer struct already allocated\n");
07456       return p->stimer;
07457    }
07458 
07459    if (!(stp = ast_calloc(1, sizeof(struct sip_st_dlg))))
07460       return NULL;
07461 
07462    p->stimer = stp;
07463 
07464    stp->st_schedid = -1;           /* Session-Timers ast_sched scheduler id */
07465 
07466    return p->stimer;
07467 }
07468 
07469 /*! \brief Allocate sip_pvt structure, set defaults and link in the container.
07470  * Returns a reference to the object so whoever uses it later must
07471  * remember to release the reference.
07472  */
07473 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
07474              int useglobal_nat, const int intended_method, struct sip_request *req)
07475 {
07476    struct sip_pvt *p;
07477 
07478    if (!(p = ao2_t_alloc(sizeof(*p), sip_destroy_fn, "allocate a dialog(pvt) struct")))
07479       return NULL;
07480 
07481    if (ast_string_field_init(p, 512)) {
07482       ao2_t_ref(p, -1, "failed to string_field_init, drop p");
07483       return NULL;
07484    }
07485 
07486    if (req) {
07487       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 */
07488    } else {
07489       set_socket_transport(&p->socket, SIP_TRANSPORT_UDP);
07490    }
07491 
07492    p->socket.fd = -1;
07493    p->method = intended_method;
07494    p->initid = -1;
07495    p->waitid = -1;
07496    p->autokillid = -1;
07497    p->request_queue_sched_id = -1;
07498    p->provisional_keepalive_sched_id = -1;
07499    p->t38id = -1;
07500    p->subscribed = NONE;
07501    p->stateid = -1;
07502    p->sessionversion_remote = -1;
07503    p->session_modify = TRUE;
07504    p->stimer = NULL;
07505    p->prefs = default_prefs;     /* Set default codecs for this call */
07506 
07507    if (intended_method != SIP_OPTIONS) {  /* Peerpoke has it's own system */
07508       p->timer_t1 = global_t1;   /* Default SIP retransmission timer T1 (RFC 3261) */
07509       p->timer_b = global_timer_b;  /* Default SIP transaction timer B (RFC 3261) */
07510    }
07511 
07512    if (!sin)
07513       p->ourip = internip;
07514    else {
07515       p->sa = *sin;
07516       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
07517    }
07518 
07519    /* Copy global flags to this PVT at setup. */
07520    ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
07521    ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
07522 
07523    p->do_history = recordhistory;
07524 
07525    p->branch = ast_random();  
07526    make_our_tag(p->tag, sizeof(p->tag));
07527    p->ocseq = INITIAL_CSEQ;
07528 
07529    if (sip_methods[intended_method].need_rtp) {
07530       p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
07531       /* If the global videosupport flag is on, we always create a RTP interface for video */
07532       if (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
07533             ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS))
07534          p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
07535       if (ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT))
07536          p->trtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
07537       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
07538          if (!(p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr))) {
07539             /* udptl creation failed, T38 can not be supported on this dialog */
07540             ast_log(LOG_ERROR, "UDPTL creation failed\n");
07541             ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
07542          }
07543       }
07544       if (!p->rtp|| (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) && !p->vrtp) 
07545             || (ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) && !p->trtp)) {
07546          ast_log(LOG_WARNING, "Unable to create RTP audio %s%ssession: %s\n",
07547             ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "and video " : "",
07548             ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "and text " : "", strerror(errno));
07549          if (p->chanvars) {
07550             ast_variables_destroy(p->chanvars);
07551             p->chanvars = NULL;
07552          }
07553          ao2_t_ref(p, -1, "failed to create RTP audio session, drop p");
07554          return NULL;
07555          p->t38_maxdatagram = global_t38_maxdatagram;
07556       }
07557       ast_rtp_setqos(p->rtp, global_tos_audio, global_cos_audio, "SIP RTP");
07558       ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
07559       ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
07560       ast_rtp_set_rtptimeout(p->rtp, global_rtptimeout);
07561       ast_rtp_set_rtpholdtimeout(p->rtp, global_rtpholdtimeout);
07562       ast_rtp_set_rtpkeepalive(p->rtp, global_rtpkeepalive);
07563       if (p->vrtp) {
07564          ast_rtp_setqos(p->vrtp, global_tos_video, global_cos_video, "SIP VRTP");
07565          ast_rtp_setdtmf(p->vrtp, 0);
07566          ast_rtp_setdtmfcompensate(p->vrtp, 0);
07567          ast_rtp_set_rtptimeout(p->vrtp, global_rtptimeout);
07568          ast_rtp_set_rtpholdtimeout(p->vrtp, global_rtpholdtimeout);
07569          ast_rtp_set_rtpkeepalive(p->vrtp, global_rtpkeepalive);
07570       }
07571       if (p->trtp) {
07572          ast_rtp_setqos(p->trtp, global_tos_text, global_cos_text, "SIP TRTP");
07573          ast_rtp_setdtmf(p->trtp, 0);
07574          ast_rtp_setdtmfcompensate(p->trtp, 0);
07575       }
07576       if (p->udptl)
07577          ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
07578       p->maxcallbitrate = default_maxcallbitrate;
07579       p->autoframing = global_autoframing;
07580       ast_rtp_codec_setpref(p->rtp, &p->prefs);
07581    }
07582 
07583    if (useglobal_nat && sin) {
07584       /* Setup NAT structure according to global settings if we have an address */
07585       ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
07586       p->recv = *sin;
07587       do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
07588    }
07589 
07590    if (p->method != SIP_REGISTER)
07591       ast_string_field_set(p, fromdomain, default_fromdomain);
07592    build_via(p);
07593    if (!callid)
07594       build_callid_pvt(p);
07595    else
07596       ast_string_field_set(p, callid, callid);
07597    /* Assign default music on hold class */
07598    ast_string_field_set(p, mohinterpret, default_mohinterpret);
07599    ast_string_field_set(p, mohsuggest, default_mohsuggest);
07600    p->capability = global_capability;
07601    p->allowtransfer = sip_cfg.allowtransfer;
07602    if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
07603        (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
07604       p->noncodeccapability |= AST_RTP_DTMF;
07605    if (p->udptl) {
07606       p->t38_maxdatagram = global_t38_maxdatagram;
07607       set_t38_capabilities(p);
07608    }
07609    ast_string_field_set(p, context, sip_cfg.default_context);
07610    ast_string_field_set(p, parkinglot, default_parkinglot);
07611 
07612    AST_LIST_HEAD_INIT_NOLOCK(&p->request_queue);
07613 
07614    /* Add to active dialog list */
07615 
07616    ao2_t_link(dialogs, p, "link pvt into dialogs table");
07617    
07618    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");
07619    return p;
07620 }
07621 
07622 static void free_via(struct sip_via *v)
07623 {
07624    if (!v) {
07625       return;
07626    }
07627 
07628    ast_free(v->via);
07629    ast_free(v);
07630 }
07631 
07632 /*!
07633  * \brief Parse a Via header
07634  *
07635  * This function parses the Via header and processes it according to section
07636  * 18.2 of RFC 3261 and RFC 3581. Since we don't have a transport layer, we
07637  * only care about the maddr and ttl parms.  The received and rport params are
07638  * not parsed.
07639  *
07640  * \note This function fails to parse some odd combinations of SWS in parameter
07641  * lists.
07642  *
07643  * \code
07644  * VIA syntax. RFC 3261 section 25.1
07645  * Via               =  ( "Via" / "v" ) HCOLON via-parm *(COMMA via-parm)
07646  * via-parm          =  sent-protocol LWS sent-by *( SEMI via-params )
07647  * via-params        =  via-ttl / via-maddr
07648  *                   / via-received / via-branch
07649  *                   / via-extension
07650  * via-ttl           =  "ttl" EQUAL ttl
07651  * via-maddr         =  "maddr" EQUAL host
07652  * via-received      =  "received" EQUAL (IPv4address / IPv6address)
07653  * via-branch        =  "branch" EQUAL token
07654  * via-extension     =  generic-param
07655  * sent-protocol     =  protocol-name SLASH protocol-version
07656  *                   SLASH transport
07657  * protocol-name     =  "SIP" / token
07658  * protocol-version  =  token
07659  * transport         =  "UDP" / "TCP" / "TLS" / "SCTP"
07660  *                   / other-transport
07661  * sent-by           =  host [ COLON port ]
07662  * ttl               =  1*3DIGIT ; 0 to 255
07663  * \endcode
07664  */
07665 static struct sip_via *parse_via(const char *header)
07666 {
07667    struct sip_via *v = ast_calloc(1, sizeof(*v));
07668    char *via, *parm;
07669 
07670    if (!v) {
07671       return NULL;
07672    }
07673 
07674    v->via = ast_strdup(header);
07675    v->ttl = 1;
07676 
07677    via = v->via;
07678 
07679    if (ast_strlen_zero(via)) {
07680       ast_log(LOG_ERROR, "received request without a Via header\n");
07681       free_via(v);
07682       return NULL;
07683    }
07684 
07685    /* seperate the first via-parm */
07686    via = strsep(&via, ",");
07687 
07688    /* chop off sent-protocol */
07689    v->protocol = strsep(&via, " \t\r\n");
07690    if (ast_strlen_zero(v->protocol)) {
07691       ast_log(LOG_ERROR, "missing sent-protocol in Via header\n");
07692       free_via(v);
07693       return NULL;
07694    }
07695    v->protocol = ast_skip_blanks(v->protocol);
07696 
07697    if (via) {
07698       via = ast_skip_blanks(via);
07699    }
07700 
07701    /* chop off sent-by */
07702    v->sent_by = strsep(&via, "; \t\r\n");
07703    if (ast_strlen_zero(v->sent_by)) {
07704       ast_log(LOG_ERROR, "missing sent-by in Via header\n");
07705       free_via(v);
07706       return NULL;
07707    }
07708    v->sent_by = ast_skip_blanks(v->sent_by);
07709 
07710    /* store the port */
07711    if ((parm = strchr(v->sent_by, ':'))) {
07712       char *endptr;
07713 
07714       v->port = strtol(++parm, &endptr, 10);
07715    }
07716 
07717    /* evaluate any via-parms */
07718    while ((parm = strsep(&via, "; \t\r\n"))) {
07719       char *c;
07720       if ((c = strstr(parm, "maddr="))) {
07721          v->maddr = ast_skip_blanks(c + sizeof("maddr=") - 1);
07722       } else if ((c = strstr(parm, "branch="))) {
07723          v->branch = ast_skip_blanks(c + sizeof("branch=") - 1);
07724       } else if ((c = strstr(parm, "ttl="))) {
07725          char *endptr;
07726          c = ast_skip_blanks(c + sizeof("ttl=") - 1);
07727          v->ttl = strtol(c, &endptr, 10);
07728 
07729          /* make sure we got a valid ttl value */
07730          if (c == endptr) {
07731             v->ttl = 1;
07732          }
07733       }
07734    }
07735 
07736    return v;
07737 }
07738 
07739 /*!
07740  * \brief Check if an ip is an multicast IP.
07741  * \parm addr the address to check
07742  *
07743  * This function checks if an address is in the 224.0.0.0/4 network block.
07744  * \return non-zero if this is a multicast address
07745  */
07746 static int addr_is_multicast(struct in_addr *addr)
07747 {
07748    return ((ntohl(addr->s_addr) & 0xf0000000) == 0xe0000000);
07749 }
07750 
07751 /*!
07752  * \brief Process the Via header according to RFC 3261 section 18.2.2.
07753  * \param p a sip_pvt structure that will be modified according to the received
07754  * header
07755  * \param req a sip request with a Via header to process
07756  *
07757  * This function will update the destination of the response according to the
07758  * Via header in the request and RFC 3261 section 18.2.2. We do not have a
07759  * transport layer so we ignore certain values like the 'received' param (we
07760  * set the destination address to the addres the request came from in the
07761  * respprep() function).
07762  *
07763  * \retval -1 error
07764  * \retval 0 success
07765  */
07766 static int process_via(struct sip_pvt *p, const struct sip_request *req)
07767 {
07768    struct sip_via *via = parse_via(get_header(req, "Via"));
07769 
07770    if (!via) {
07771       ast_log(LOG_ERROR, "error processing via header\n");
07772       return -1;
07773    }
07774 
07775    if (via->maddr) {
07776       struct hostent *hp;
07777       struct ast_hostent ahp;
07778 
07779       hp = ast_gethostbyname(via->maddr, &ahp);
07780       if (hp == NULL)  {
07781          ast_log(LOG_WARNING, "Can't find address for maddr '%s'\n", via->maddr);
07782          ast_log(LOG_ERROR, "error processing via header\n");
07783          free_via(via);
07784          return -1;
07785       }
07786 
07787       p->sa.sin_family = AF_INET;
07788       memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
07789 
07790       if (addr_is_multicast(&p->sa.sin_addr)) {
07791          setsockopt(sipsock, IPPROTO_IP, IP_MULTICAST_TTL, &via->ttl, sizeof(via->ttl));
07792       }
07793    }
07794 
07795    p->sa.sin_port = htons(via->port ? via->port : STANDARD_SIP_PORT);
07796 
07797    free_via(via);
07798    return 0;
07799 }
07800 
07801 /*! \brief argument to the helper function to identify a call */
07802 struct find_call_cb_arg {
07803    enum sipmethod method;
07804    const char *callid;
07805    const char *fromtag;
07806    const char *totag;
07807    const char *tag;
07808 };
07809 
07810 /*!
07811  * code to determine whether this is the pvt that we are looking for.
07812  * Return FALSE if not found, true otherwise. p is unlocked.
07813  */
07814 static int find_call_cb(void *__pvt, void *__arg, int flags)
07815 {
07816    struct sip_pvt *p = __pvt;
07817    struct find_call_cb_arg *arg = __arg;
07818    /* In pedantic, we do not want packets with bad syntax to be connected to a PVT */
07819    int found = FALSE;
07820    
07821    if (!ast_strlen_zero(p->callid)) { /* XXX double check, do we allow match on empty p->callid ? */
07822       if (arg->method == SIP_REGISTER)
07823          found = (!strcmp(p->callid, arg->callid));
07824       else {
07825          found = !strcmp(p->callid, arg->callid);
07826          if (sip_cfg.pedanticsipchecking && found) {
07827             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);
07828          } 
07829       }
07830       
07831       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);
07832       
07833       /* If we get a new request within an existing to-tag - check the to tag as well */
07834       if (sip_cfg.pedanticsipchecking && found && arg->method != SIP_RESPONSE) { /* SIP Request */
07835          if (p->tag[0] == '\0' && arg->totag[0]) {
07836             /* We have no to tag, but they have. Wrong dialog */
07837             found = FALSE;
07838          } else if (arg->totag[0]) { /* Both have tags, compare them */
07839             if (strcmp(arg->totag, p->tag)) {
07840                found = FALSE; /* This is not our packet */
07841             }
07842          }
07843          if (!found)
07844             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);
07845       }
07846    }
07847    return found;
07848 }
07849 
07850 /*! \brief find or create a dialog structure for an incoming SIP message.
07851  * Connect incoming SIP message to current dialog or create new dialog structure
07852  * Returns a reference to the sip_pvt object, remember to give it back once done.
07853  *     Called by handle_request_do
07854  */
07855 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
07856 {
07857    struct sip_pvt *p = NULL;
07858    char *tag = "";   /* note, tag is never NULL */
07859    char totag[128];
07860    char fromtag[128];
07861    struct find_call_cb_arg arg;
07862    const char *callid = get_header(req, "Call-ID");
07863    const char *from = get_header(req, "From");
07864    const char *to = get_header(req, "To");
07865    const char *cseq = get_header(req, "Cseq");
07866    struct sip_pvt *sip_pvt_ptr;
07867 
07868    /* Call-ID, to, from and Cseq are required by RFC 3261. (Max-forwards and via too - ignored now) */
07869    /* get_header always returns non-NULL so we must use ast_strlen_zero() */
07870    if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
07871          ast_strlen_zero(from) || ast_strlen_zero(cseq))
07872       return NULL;   /* Invalid packet */
07873 
07874    arg.method = req->method;
07875    arg.callid = callid;
07876    arg.fromtag = fromtag;
07877    arg.totag = totag;
07878    arg.tag = ""; /* make sure tag is never NULL */
07879 
07880    if (sip_cfg.pedanticsipchecking) {
07881       /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
07882          we need more to identify a branch - so we have to check branch, from
07883          and to tags to identify a call leg.
07884          For Asterisk to behave correctly, you need to turn on pedanticsipchecking
07885          in sip.conf
07886          */
07887       if (gettag(req, "To", totag, sizeof(totag)))
07888          req->has_to_tag = 1; /* Used in handle_request/response */
07889       gettag(req, "From", fromtag, sizeof(fromtag));
07890 
07891       tag = (req->method == SIP_RESPONSE) ? totag : fromtag;
07892 
07893       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);
07894 
07895       /* All messages must always have From: tag */
07896       if (ast_strlen_zero(fromtag)) {
07897          ast_debug(5, "%s request has no from tag, dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
07898          return NULL;
07899       }
07900       /* reject requests that must always have a To: tag */
07901       if (ast_strlen_zero(totag) && (req->method == SIP_ACK || req->method == SIP_BYE || req->method == SIP_INFO )) {
07902          ast_debug(5, "%s must have a to tag. dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
07903          return NULL;
07904       }
07905    }
07906 
07907 restartsearch:
07908    if (!sip_cfg.pedanticsipchecking) {
07909       struct sip_pvt tmp_dialog = {
07910          .callid = callid,
07911       };       
07912       sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find in dialogs");
07913       if (sip_pvt_ptr) {  /* well, if we don't find it-- what IS in there? */
07914          /* Found the call */
07915          sip_pvt_lock(sip_pvt_ptr);
07916          return sip_pvt_ptr;
07917       }
07918    } else { /* in pedantic mode! -- do the fancy linear search */
07919       ao2_lock(dialogs);
07920       p = ao2_t_callback(dialogs, 0 /* single, data */, find_call_cb, &arg, "pedantic linear search for dialog");
07921       if (p) {
07922          if (sip_pvt_trylock(p)) {
07923             ao2_unlock(dialogs);
07924             usleep(1);
07925             p = dialog_unref(p, "pedantic linear search for dialog unref to restart search");
07926             goto restartsearch;
07927          }
07928          ao2_unlock(dialogs);
07929          return p;
07930       }
07931       ao2_unlock(dialogs);
07932    }
07933  
07934    /* See if the method is capable of creating a dialog */
07935    if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
07936       if (intended_method == SIP_REFER) {
07937          /* We do support REFER, but not outside of a dialog yet */
07938          transmit_response_using_temp(callid, sin, 1, intended_method, req, "603 Declined (no dialog)");
07939       } else if (intended_method == SIP_NOTIFY) {
07940          /* We do not support out-of-dialog NOTIFY either,
07941             like voicemail notification, so cancel that early */
07942          transmit_response_using_temp(callid, sin, 1, intended_method, req, "481 No subscription");
07943       } else {
07944          /* Ok, time to create a new SIP dialog object, a pvt */
07945          if ((p = sip_alloc(callid, sin, 1, intended_method, req)))  {
07946             /* Ok, we've created a dialog, let's go and process it */
07947             sip_pvt_lock(p);
07948          } else {
07949             /* We have a memory or file/socket error (can't allocate RTP sockets or something) so we're not
07950                getting a dialog from sip_alloc. 
07951    
07952                Without a dialog we can't retransmit and handle ACKs and all that, but at least
07953                send an error message.
07954    
07955                Sorry, we apologize for the inconvienience
07956             */
07957             transmit_response_using_temp(callid, sin, 1, intended_method, req, "500 Server internal error");
07958             ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
07959          }
07960       }
07961       return p; /* can be NULL */
07962    } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
07963       /* A method we do not support, let's take it on the volley */
07964       transmit_response_using_temp(callid, sin, 1, intended_method, req, "501 Method Not Implemented");
07965       ast_debug(2, "Got a request with unsupported SIP method.\n");
07966    } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
07967       /* This is a request outside of a dialog that we don't know about */
07968       transmit_response_using_temp(callid, sin, 1, intended_method, req, "481 Call leg/transaction does not exist");
07969       ast_debug(2, "That's odd...  Got a request in unknown dialog. Callid %s\n", callid ? callid : "<unknown>");
07970    }
07971    /* We do not respond to responses for dialogs that we don't know about, we just drop
07972       the session quickly */
07973    if (intended_method == SIP_RESPONSE)
07974       ast_debug(2, "That's odd...  Got a response on a call we don't know about. Callid %s\n", callid ? callid : "<unknown>");
07975 
07976    return NULL;
07977 }
07978 
07979 /*! \brief Parse register=> line in sip.conf and add to registry */
07980 static int sip_register(const char *value, int lineno)
07981 {
07982    struct sip_registry *reg;
07983    int portnum = 0;
07984    enum sip_transport transport = SIP_TRANSPORT_UDP;
07985    char buf[256] = "";
07986    char *userpart = NULL, *hostpart = NULL;
07987    /* register => [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] */
07988    AST_DECLARE_APP_ARGS(pre1,
07989       AST_APP_ARG(peer);
07990       AST_APP_ARG(userpart);
07991    );
07992    AST_DECLARE_APP_ARGS(pre2,
07993       AST_APP_ARG(transport);
07994       AST_APP_ARG(blank);
07995       AST_APP_ARG(userpart);
07996    );
07997    AST_DECLARE_APP_ARGS(user1,
07998       AST_APP_ARG(userpart);
07999       AST_APP_ARG(secret);
08000       AST_APP_ARG(authuser);
08001    );
08002    AST_DECLARE_APP_ARGS(host1,
08003       AST_APP_ARG(hostpart);
08004       AST_APP_ARG(expiry);
08005    );
08006    AST_DECLARE_APP_ARGS(host2,
08007       AST_APP_ARG(hostpart);
08008       AST_APP_ARG(extension);
08009    );
08010    AST_DECLARE_APP_ARGS(host3,
08011       AST_APP_ARG(host);
08012       AST_APP_ARG(port);
08013    );
08014 
08015    if (!value)
08016       return -1;
08017    ast_copy_string(buf, value, sizeof(buf));
08018 
08019    /*! register => [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry]
08020     * becomes
08021     *   userpart => [peer?][transport://]user[@domain][:secret[:authuser]]
08022     *   hostpart => host[:port][/extension][~expiry]
08023     */
08024    if ((hostpart = strrchr(buf, '@'))) {
08025       *hostpart++ = '\0';
08026       userpart = buf;
08027    }
08028 
08029    if (ast_strlen_zero(userpart) || ast_strlen_zero(hostpart)) {
08030       ast_log(LOG_WARNING, "Format for registration is [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] at line %d\n", lineno);
08031       return -1;
08032    }
08033 
08034    /*!
08035     * pre1.peer => peer
08036     * pre1.userpart => [transport://]user[@domain][:secret[:authuser]]
08037     * hostpart => host[:port][/extension][~expiry]
08038     */
08039    AST_NONSTANDARD_RAW_ARGS(pre1, userpart, '?');
08040    if (ast_strlen_zero(pre1.userpart)) {
08041       pre1.userpart = pre1.peer;
08042       pre1.peer = NULL;
08043    }
08044 
08045    /*!
08046     * pre1.peer => peer
08047     * pre2.transport = transport
08048     * pre2.userpart => user[@domain][:secret[:authuser]]
08049     * hostpart => host[:port][/extension][~expiry]
08050     */
08051    AST_NONSTANDARD_RAW_ARGS(pre2, pre1.userpart, '/');
08052    if (ast_strlen_zero(pre2.userpart)) {
08053       pre2.userpart = pre2.transport;
08054       pre2.transport = NULL;
08055    } else {
08056       pre2.transport[strlen(pre2.transport) - 1] = '\0'; /* Remove trailing : */
08057    }
08058 
08059    if (!ast_strlen_zero(pre2.blank)) {
08060       ast_log(LOG_WARNING, "Format for registration is [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] at line %d\n", lineno);
08061       return -1;
08062    }
08063 
08064    /*!
08065     * pre1.peer => peer
08066     * pre2.transport = transport
08067     * user1.userpart => user[@domain]
08068     * user1.secret => secret
08069     * user1.authuser => authuser
08070     * hostpart => host[:port][/extension][~expiry]
08071     */
08072    AST_NONSTANDARD_RAW_ARGS(user1, pre2.userpart, ':');
08073 
08074    /*!
08075     * pre1.peer => peer
08076     * pre2.transport = transport
08077     * user1.userpart => user[@domain]
08078     * user1.secret => secret
08079     * user1.authuser => authuser
08080     * host1.hostpart => host[:port][/extension]
08081     * host1.expiry => [expiry]
08082     */
08083    AST_NONSTANDARD_RAW_ARGS(host1, hostpart, '~');
08084 
08085    /*!
08086     * pre1.peer => peer
08087     * pre2.transport = transport
08088     * user1.userpart => user[@domain]
08089     * user1.secret => secret
08090     * user1.authuser => authuser
08091     * host2.hostpart => host[:port]
08092     * host2.extension => [extension]
08093     * host1.expiry => [expiry]
08094     */
08095    AST_NONSTANDARD_RAW_ARGS(host2, host1.hostpart, '/');
08096 
08097    /*!
08098     * pre1.peer => peer
08099     * pre2.transport = transport
08100     * user1.userpart => user[@domain]
08101     * user1.secret => secret
08102     * user1.authuser => authuser
08103     * host3.host => host
08104     * host3.port => port
08105     * host2.extension => extension
08106     * host1.expiry => expiry
08107     */
08108    AST_NONSTANDARD_RAW_ARGS(host3, host2.hostpart, ':');
08109 
08110    if (host3.port) {
08111       if (!(portnum = port_str2int(host3.port, 0))) {
08112          ast_log(LOG_NOTICE, "'%s' is not a valid port number on line %d of sip.conf. using default.\n", host3.port, lineno);
08113       }
08114    }
08115 
08116    /* set transport type */
08117    if (!pre2.transport) {
08118       transport = SIP_TRANSPORT_UDP;
08119    } else if (!strncasecmp(pre2.transport, "tcp", 3)) {
08120       transport = SIP_TRANSPORT_TCP;
08121    } else if (!strncasecmp(pre2.transport, "tls", 3)) {
08122       transport = SIP_TRANSPORT_TLS;
08123    } else if (!strncasecmp(pre2.transport, "udp", 3)) {
08124       transport = SIP_TRANSPORT_UDP;
08125    } else {
08126       transport = SIP_TRANSPORT_UDP;
08127       ast_log(LOG_NOTICE, "'%.3s' is not a valid transport type on line %d of sip.conf. defaulting to udp.\n", pre2.transport, lineno);
08128    }
08129 
08130    /* if no portnum specified, set default for transport */
08131    if (!portnum) {
08132       if (transport == SIP_TRANSPORT_TLS) {
08133          portnum = STANDARD_TLS_PORT;
08134       } else {
08135          portnum = STANDARD_SIP_PORT;
08136       }
08137    }
08138 
08139    if (!(reg = ast_calloc(1, sizeof(*reg)))) {
08140       ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
08141       return -1;
08142    }
08143 
08144    if (ast_string_field_init(reg, 256)) {
08145       ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry strings\n");
08146       ast_free(reg);
08147       return -1;
08148    }
08149 
08150    ast_atomic_fetchadd_int(&regobjs, 1);
08151    ASTOBJ_INIT(reg);
08152    ast_string_field_set(reg, callback, ast_strip_quoted(S_OR(host2.extension, "s"), "\"", "\""));
08153    ast_string_field_set(reg, username, ast_strip_quoted(S_OR(user1.userpart, ""), "\"", "\""));
08154    ast_string_field_set(reg, hostname, ast_strip_quoted(S_OR(host3.host, ""), "\"", "\""));
08155    ast_string_field_set(reg, authuser, ast_strip_quoted(S_OR(user1.authuser, ""), "\"", "\""));
08156    ast_string_field_set(reg, secret, ast_strip_quoted(S_OR(user1.secret, ""), "\"", "\""));
08157    ast_string_field_set(reg, peername, ast_strip_quoted(S_OR(pre1.peer, ""), "\"", "\""));
08158 
08159    reg->transport = transport;
08160    reg->timeout = reg->expire = -1;
08161    reg->refresh = reg->expiry = reg->configured_expiry = (host1.expiry ? atoi(ast_strip_quoted(host1.expiry, "\"", "\"")) : default_expiry);
08162    reg->portno = portnum;
08163    reg->callid_valid = FALSE;
08164    reg->ocseq = INITIAL_CSEQ;
08165    ASTOBJ_CONTAINER_LINK(&regl, reg); /* Add the new registry entry to the list */
08166    registry_unref(reg, "unref the reg pointer");   /* release the reference given by ASTOBJ_INIT. The container has another reference */
08167    return 0;
08168 }
08169 
08170 /*! \brief Parse mwi=> line in sip.conf and add to list */
08171 static int sip_subscribe_mwi(const char *value, int lineno)
08172 {
08173    struct sip_subscription_mwi *mwi;
08174    int portnum = 0;
08175    enum sip_transport transport = SIP_TRANSPORT_UDP;
08176    char buf[256] = "";
08177    char *username = NULL, *hostname = NULL, *secret = NULL, *authuser = NULL, *porta = NULL, *mailbox = NULL;
08178    
08179    if (!value) {
08180       return -1;
08181    }
08182    
08183    ast_copy_string(buf, value, sizeof(buf));
08184 
08185    sip_parse_host(buf, lineno, &username, &portnum, &transport);
08186    
08187    if ((hostname = strrchr(username, '@'))) {
08188       *hostname++ = '\0';
08189    }
08190    
08191    if ((secret = strchr(username, ':'))) {
08192       *secret++ = '\0';
08193       if ((authuser = strchr(secret, ':'))) {
08194          *authuser++ = '\0';
08195       }
08196    }
08197    
08198    if ((mailbox = strchr(hostname, '/'))) {
08199       *mailbox++ = '\0';
08200    }
08201 
08202    if (ast_strlen_zero(username) || ast_strlen_zero(hostname) || ast_strlen_zero(mailbox)) {
08203       ast_log(LOG_WARNING, "Format for MWI subscription is user[:secret[:authuser]]@host[:port][/mailbox] at line %d\n", lineno);
08204       return -1;
08205    }
08206    
08207    if ((porta = strchr(hostname, ':'))) {
08208       *porta++ = '\0';
08209       if (!(portnum = atoi(porta))) {
08210          ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
08211          return -1;
08212       }
08213    }
08214    
08215    if (!(mwi = ast_calloc(1, sizeof(*mwi)))) {
08216       return -1;
08217    }
08218    
08219    if (ast_string_field_init(mwi, 256)) {
08220       ast_free(mwi);
08221       return -1;
08222    }
08223    
08224    ASTOBJ_INIT(mwi);
08225    ast_string_field_set(mwi, username, username);
08226    if (secret) {
08227       ast_string_field_set(mwi, secret, secret);
08228    }
08229    if (authuser) {
08230       ast_string_field_set(mwi, authuser, authuser);
08231    }
08232    ast_string_field_set(mwi, hostname, hostname);
08233    ast_string_field_set(mwi, mailbox, mailbox);
08234    mwi->resub = -1;
08235    mwi->portno = portnum;
08236    mwi->transport = transport;
08237    
08238    ASTOBJ_CONTAINER_LINK(&submwil, mwi);
08239    ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
08240    
08241    return 0;
08242 }
08243 
08244 /*! \brief  Parse multiline SIP headers into one header
08245    This is enabled if pedanticsipchecking is enabled */
08246 static int lws2sws(char *msgbuf, int len) 
08247 {
08248    int h = 0, t = 0; 
08249    int lws = 0; 
08250 
08251    for (; h < len;) { 
08252       /* Eliminate all CRs */ 
08253       if (msgbuf[h] == '\r') { 
08254          h++; 
08255          continue; 
08256       } 
08257       /* Check for end-of-line */ 
08258       if (msgbuf[h] == '\n') { 
08259          /* Check for end-of-message */ 
08260          if (h + 1 == len) 
08261             break; 
08262          /* Check for a continuation line */ 
08263          if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') { 
08264             /* Merge continuation line */ 
08265             h++; 
08266             continue; 
08267          } 
08268          /* Propagate LF and start new line */ 
08269          msgbuf[t++] = msgbuf[h++]; 
08270          lws = 0;
08271          continue; 
08272       } 
08273       if (msgbuf[h] == ' ' || msgbuf[h] == '\t') { 
08274          if (lws) { 
08275             h++; 
08276             continue; 
08277          } 
08278          msgbuf[t++] = msgbuf[h++]; 
08279          lws = 1; 
08280          continue; 
08281       } 
08282       msgbuf[t++] = msgbuf[h++]; 
08283       if (lws) 
08284          lws = 0; 
08285    } 
08286    msgbuf[t] = '\0'; 
08287    return t; 
08288 }
08289 
08290 /*! \brief Parse a SIP message 
08291    \note this function is used both on incoming and outgoing packets
08292 */
08293 static int parse_request(struct sip_request *req)
08294 {
08295    char *c = req->data->str;
08296    ptrdiff_t *dst = req->header;
08297    int i = 0, lim = SIP_MAX_HEADERS - 1;
08298    unsigned int skipping_headers = 0;
08299    ptrdiff_t current_header_offset = 0;
08300    char *previous_header = "";
08301 
08302    req->header[0] = 0;
08303    req->headers = -1;   /* mark that we are working on the header */
08304    for (; *c; c++) {
08305       if (*c == '\r') {    /* remove \r */
08306          *c = '\0';
08307       } else if (*c == '\n') {   /* end of this line */
08308          *c = '\0';
08309          current_header_offset = (c + 1) - req->data->str;
08310          previous_header = req->data->str + dst[i];
08311          if (skipping_headers) {
08312             /* check to see if this line is blank; if so, turn off
08313                the skipping flag, so the next line will be processed
08314                as a body line */
08315             if (ast_strlen_zero(previous_header)) {
08316                skipping_headers = 0;
08317             }
08318             dst[i] = current_header_offset; /* record start of next line */
08319             continue;
08320          }
08321          if (sipdebug) {
08322             ast_debug(4, "%7s %2d [%3d]: %s\n",
08323                  req->headers < 0 ? "Header" : "Body",
08324                  i, (int) strlen(previous_header), previous_header);
08325          }
08326          if (ast_strlen_zero(previous_header) && req->headers < 0) {
08327             req->headers = i; /* record number of header lines */
08328             dst = req->line;  /* start working on the body */
08329             i = 0;
08330             lim = SIP_MAX_LINES - 1;
08331          } else { /* move to next line, check for overflows */
08332             if (i++ == lim) {
08333                /* if we're processing headers, then skip any remaining
08334                   headers and move on to processing the body, otherwise
08335                   we're done */
08336                if (req->headers != -1) {
08337                   break;
08338                } else {
08339                   req->headers = i;
08340                   dst = req->line;
08341                   i = 0;
08342                   lim = SIP_MAX_LINES - 1;
08343                   skipping_headers = 1;
08344                }
08345             }
08346          }
08347          dst[i] = current_header_offset; /* record start of next line */
08348       }
08349    }
08350 
08351    /* Check for last header or body line without CRLF. The RFC for SDP requires CRLF,
08352       but since some devices send without, we'll be generous in what we accept. However,
08353       if we've already reached the maximum number of lines for portion of the message
08354       we were parsing, we can't accept any more, so just ignore it.
08355    */
08356    previous_header = req->data->str + dst[i];
08357    if ((i < lim) && !ast_strlen_zero(previous_header)) {
08358       if (sipdebug) {
08359          ast_debug(4, "%7s %2d [%3d]: %s\n",
08360               req->headers < 0 ? "Header" : "Body",
08361               i, (int) strlen(previous_header), previous_header );
08362       }
08363       i++;
08364    }
08365 
08366    /* update count of header or body lines */
08367    if (req->headers >= 0) {   /* we are in the body */
08368       req->lines = i;
08369    } else {       /* no body */
08370       req->headers = i;
08371       req->lines = 0;
08372       /* req->data->used will be a NULL byte */
08373       req->line[0] = ast_str_strlen(req->data);
08374    }
08375 
08376    if (*c) {
08377       ast_log(LOG_WARNING, "Too many lines, skipping <%s>\n", c);
08378    }
08379 
08380    /* Split up the first line parts */
08381    return determine_firstline_parts(req);
08382 }
08383 
08384 /*!
08385   \brief Determine whether a SIP message contains an SDP in its body
08386   \param req the SIP request to process
08387   \return 1 if SDP found, 0 if not found
08388 
08389   Also updates req->sdp_start and req->sdp_count to indicate where the SDP
08390   lives in the message body.
08391 */
08392 static int find_sdp(struct sip_request *req)
08393 {
08394    const char *content_type;
08395    const char *content_length;
08396    const char *search;
08397    char *boundary;
08398    unsigned int x;
08399    int boundaryisquoted = FALSE;
08400    int found_application_sdp = FALSE;
08401    int found_end_of_headers = FALSE;
08402 
08403    content_length = get_header(req, "Content-Length");
08404 
08405    if (!ast_strlen_zero(content_length)) {
08406       if (sscanf(content_length, "%30u", &x) != 1) {
08407          ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
08408          return 0;
08409       }
08410 
08411       /* Content-Length of zero means there can't possibly be an
08412          SDP here, even if the Content-Type says there is */
08413       if (x == 0)
08414          return 0;
08415    }
08416 
08417    content_type = get_header(req, "Content-Type");
08418 
08419    /* if the body contains only SDP, this is easy */
08420    if (!strncasecmp(content_type, "application/sdp", 15)) {
08421       req->sdp_start = 0;
08422       req->sdp_count = req->lines;
08423       return req->lines ? 1 : 0;
08424    }
08425 
08426    /* if it's not multipart/mixed, there cannot be an SDP */
08427    if (strncasecmp(content_type, "multipart/mixed", 15))
08428       return 0;
08429 
08430    /* if there is no boundary marker, it's invalid */
08431    if ((search = strcasestr(content_type, ";boundary=")))
08432       search += 10;
08433    else if ((search = strcasestr(content_type, "; boundary=")))
08434       search += 11;
08435    else
08436       return 0;
08437 
08438    if (ast_strlen_zero(search))
08439       return 0;
08440 
08441    /* If the boundary is quoted with ", remove quote */
08442    if (*search == '\"')  {
08443       search++;
08444       boundaryisquoted = TRUE;
08445    }
08446 
08447    /* make a duplicate of the string, with two extra characters
08448       at the beginning */
08449    boundary = ast_strdupa(search - 2);
08450    boundary[0] = boundary[1] = '-';
08451    /* Remove final quote */
08452    if (boundaryisquoted)
08453       boundary[strlen(boundary) - 1] = '\0';
08454 
08455    /* search for the boundary marker, the empty line delimiting headers from
08456       sdp part and the end boundry if it exists */
08457 
08458    for (x = 0; x < (req->lines); x++) {
08459       char *line = REQ_OFFSET_TO_STR(req, line[x]);
08460       if (!strncasecmp(line, boundary, strlen(boundary))){
08461          if (found_application_sdp && found_end_of_headers) {
08462             req->sdp_count = (x - 1) - req->sdp_start;
08463             return 1;
08464          }
08465          found_application_sdp = FALSE;
08466       }
08467       if (!strcasecmp(line, "Content-Type: application/sdp"))
08468          found_application_sdp = TRUE;
08469       
08470       if (ast_strlen_zero(line)) {
08471          if (found_application_sdp && !found_end_of_headers){
08472             req->sdp_start = x;
08473             found_end_of_headers = TRUE;
08474          }
08475       }
08476    }
08477    if (found_application_sdp && found_end_of_headers) {
08478       req->sdp_count = x - req->sdp_start;
08479       return TRUE;
08480    }
08481    return FALSE;
08482 }
08483 
08484 /*! \brief Change hold state for a call */
08485 static void change_hold_state(struct sip_pvt *dialog, struct sip_request *req, int holdstate, int sendonly)
08486 {
08487    if (sip_cfg.notifyhold && (!holdstate || !ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD)))
08488       sip_peer_hold(dialog, holdstate);
08489    if (sip_cfg.callevents)
08490       manager_event(EVENT_FLAG_CALL, "Hold",
08491                "Status: %s\r\n"
08492                "Channel: %s\r\n"
08493                "Uniqueid: %s\r\n",
08494                holdstate ? "On" : "Off",
08495                dialog->owner->name,
08496                dialog->owner->uniqueid);
08497    append_history(dialog, holdstate ? "Hold" : "Unhold", "%s", req->data->str);
08498    if (!holdstate) { /* Put off remote hold */
08499       ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD);   /* Clear both flags */
08500       return;
08501    }
08502    /* No address for RTP, we're on hold */
08503 
08504    if (sendonly == 1)   /* One directional hold (sendonly/recvonly) */
08505       ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
08506    else if (sendonly == 2) /* Inactive stream */
08507       ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
08508    else
08509       ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
08510    return;
08511 }
08512 
08513 enum media_type {
08514    SDP_AUDIO,
08515    SDP_VIDEO,
08516    SDP_IMAGE,
08517    SDP_TEXT,
08518 };
08519 
08520 static int get_ip_and_port_from_sdp(struct sip_request *req, const enum media_type media, struct sockaddr_in *sin)
08521 {
08522    const char *m;
08523    const char *c;
08524    int miterator = req->sdp_start;
08525    int citerator = req->sdp_start;
08526    int x = 0;
08527    int numberofports;
08528    int len;
08529    char host[258] = ""; /*Initialize to empty so we will know if we have any input */
08530    struct ast_hostent audiohp;
08531    struct hostent *hp;
08532 
08533    c = get_sdp_iterate(&citerator, req, "c");
08534    if (sscanf(c, "IN IP4 %256s", host) != 1) {
08535       ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
08536       /* Continue since there may be a valid host in a c= line specific to the audio stream */
08537    }
08538    /* We only want the m and c lines for audio */
08539    for (m = get_sdp_iterate(&miterator, req, "m"); !ast_strlen_zero(m); m = get_sdp_iterate(&miterator, req, "m")) {
08540       if ((media == SDP_AUDIO && ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08541           (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0))) ||
08542          (media == SDP_VIDEO && ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08543           (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len > 0)))) {
08544          /* See if there's a c= line for this media stream.
08545           * XXX There is no guarantee that we'll be grabbing the c= line for this
08546           * particular media stream here. However, this is the same logic used in process_sdp.
08547           */
08548          c = get_sdp_iterate(&citerator, req, "c");
08549          if (!ast_strlen_zero(c)) {
08550             sscanf(c, "IN IP4 %256s", host);
08551          }
08552          break;
08553       }
08554    }
08555 
08556    if (ast_strlen_zero(host) || x == 0) {
08557       ast_log(LOG_WARNING, "Failed to read an alternate host or port in SDP. Expect %s problems\n", media == SDP_AUDIO ? "audio" : "video");
08558       return -1;
08559    }
08560 
08561    hp = ast_gethostbyname(host, &audiohp);
08562    if (!hp) {
08563       ast_log(LOG_WARNING, "Could not look up IP address of alternate hostname. Expect %s problems\n", media == SDP_AUDIO? "audio" : "video");
08564       return -1;
08565    }
08566 
08567    memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
08568    sin->sin_port = htons(x);
08569    return 0;
08570 }
08571 
08572 /*! \brief Process SIP SDP offer, select formats and activate RTP channels
08573    If offer is rejected, we will not change any properties of the call
08574    Return 0 on success, a negative value on errors.
08575    Must be called after find_sdp().
08576 */
08577 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
08578 {
08579    /* Iterators for SDP parsing */
08580    int start = req->sdp_start;
08581    int next = start;
08582    int iterator = start;
08583 
08584    /* Temporary vars for SDP parsing */
08585    char type = '\0';
08586    const char *value = NULL;
08587    const char *m = NULL;           /* SDP media offer */
08588    const char *nextm = NULL;
08589    int len = -1;
08590 
08591    /* Host information */
08592    struct ast_hostent sessionhp;
08593    struct ast_hostent audiohp;
08594    struct ast_hostent videohp;
08595    struct ast_hostent texthp;
08596    struct ast_hostent imagehp;
08597    struct hostent *hp = NULL; /*!< RTP Audio host IP */
08598    struct hostent *vhp = NULL;   /*!< RTP video host IP */
08599    struct hostent *thp = NULL;   /*!< RTP text host IP */
08600    struct hostent *ihp = NULL;     /*!< UDPTL host ip */
08601    int portno = -1;     /*!< RTP Audio port number */
08602    int vportno = -1;    /*!< RTP Video port number */
08603    int tportno = -1;    /*!< RTP Text port number */
08604    int udptlportno = -1;      /*!< UDPTL Image port number */
08605    struct sockaddr_in sin = { 0, }; /*!< media socket address */
08606    struct sockaddr_in vsin = { 0, };   /*!< video socket address */
08607    struct sockaddr_in isin = { 0, };   /*!< image socket address */
08608    struct sockaddr_in tsin = { 0, };   /*!< text socket address */
08609 
08610    /* Peer capability is the capability in the SDP, non codec is RFC2833 DTMF (101) */ 
08611    int peercapability = 0, peernoncodeccapability = 0;
08612    int vpeercapability = 0, vpeernoncodeccapability = 0;
08613    int tpeercapability = 0, tpeernoncodeccapability = 0;
08614 
08615    struct ast_rtp *newaudiortp, *newvideortp, *newtextrtp;
08616    int newjointcapability;          /* Negotiated capability */
08617    int newpeercapability;
08618    int newnoncodeccapability;
08619 
08620    const char *codecs;
08621    int codec;
08622 
08623    /* Others */
08624    int sendonly = -1;
08625    int vsendonly = -1;
08626    int numberofports;
08627    int numberofmediastreams = 0;
08628    int last_rtpmap_codec = 0;
08629    int red_data_pt[10];    /* For T.140 red */
08630    int red_num_gen = 0;    /* For T.140 red */
08631    char red_fmtp[100] = "empty"; /* For T.140 red */
08632    int debug = sip_debug_test_pvt(p);
08633 
08634    /* START UNKNOWN */
08635    char buf[SIPBUFSIZE];
08636    /* END UNKNOWN */
08637 
08638    /* Initial check */
08639    if (!p->rtp) {
08640       ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
08641       return -1;
08642    }
08643 
08644    /* Initialize the temporary RTP structures we use to evaluate the offer from the peer */
08645 #ifdef LOW_MEMORY
08646    newaudiortp = ast_threadstorage_get(&ts_audio_rtp, ast_rtp_alloc_size());
08647 #else
08648    newaudiortp = alloca(ast_rtp_alloc_size());
08649 #endif
08650    memset(newaudiortp, 0, ast_rtp_alloc_size());
08651    ast_rtp_new_init(newaudiortp);
08652    ast_rtp_pt_clear(newaudiortp);
08653 
08654 #ifdef LOW_MEMORY
08655    newvideortp = ast_threadstorage_get(&ts_video_rtp, ast_rtp_alloc_size());
08656 #else
08657    newvideortp = alloca(ast_rtp_alloc_size());
08658 #endif
08659    memset(newvideortp, 0, ast_rtp_alloc_size());
08660    ast_rtp_new_init(newvideortp);
08661    ast_rtp_pt_clear(newvideortp);
08662 
08663 #ifdef LOW_MEMORY
08664    newtextrtp = ast_threadstorage_get(&ts_text_rtp, ast_rtp_alloc_size());
08665 #else
08666    newtextrtp = alloca(ast_rtp_alloc_size());
08667 #endif
08668    memset(newtextrtp, 0, ast_rtp_alloc_size());
08669    ast_rtp_new_init(newtextrtp);
08670    ast_rtp_pt_clear(newtextrtp);
08671 
08672    /* Update our last rtprx when we receive an SDP, too */
08673    p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
08674 
08675    memset(p->offered_media, 0, sizeof(p->offered_media));
08676 
08677 
08678    /* default: novideo and notext set */
08679    p->novideo = TRUE;
08680    p->notext = TRUE;
08681 
08682    if (p->vrtp)
08683       ast_rtp_pt_clear(newvideortp);  /* Must be cleared in case no m=video line exists */
08684  
08685    if (p->trtp)
08686       ast_rtp_pt_clear(newtextrtp);  /* Must be cleared in case no m=text line exists */
08687    
08688    /* Scan for the first media stream (m=) line to limit scanning of globals */
08689    nextm = get_sdp_iterate(&next, req, "m");
08690    if (ast_strlen_zero(nextm)) {
08691       ast_log(LOG_WARNING, "Insufficient information for SDP (m= not found)\n");
08692       return -1;
08693    }
08694 
08695    /* Scan session level SDP parameters (lines before first media stream) */
08696    while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
08697       int processed = FALSE;
08698       switch (type) {
08699       case 'o':
08700          /* If we end up receiving SDP that doesn't actually modify the session we don't want to treat this as a fatal
08701           * error. We just want to ignore the SDP and let the rest of the packet be handled as normal.
08702           */
08703          if (!process_sdp_o(value, p))
08704             return (p->session_modify == FALSE) ? 0 : -1;
08705          break;
08706       case 'c':
08707          if (process_sdp_c(value, &sessionhp)) {
08708             processed = TRUE;
08709             hp = &sessionhp.hp;
08710             vhp = hp;
08711             thp = hp;
08712             ihp = hp;
08713          }
08714          break;
08715       case 'a':
08716          if (process_sdp_a_sendonly(value, &sendonly)) {
08717             processed = TRUE;
08718             vsendonly = sendonly;
08719          }
08720          else if (process_sdp_a_audio(value, p, newaudiortp, &last_rtpmap_codec))
08721             processed = TRUE;
08722          else if (process_sdp_a_video(value, p, newvideortp, &last_rtpmap_codec))
08723             processed = TRUE;
08724          else if (process_sdp_a_text(value, p, newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
08725             processed = TRUE;
08726          else if (process_sdp_a_image(value, p))
08727             processed = TRUE;
08728          break;
08729       }
08730 
08731       if (option_debug > 2)
08732          ast_log(LOG_DEBUG, "Processing session-level SDP %c=%s... %s\n", type, value, (processed == TRUE)? "OK." : "UNSUPPORTED.");
08733    }
08734 
08735 
08736 
08737    /* Scan media stream (m=) specific parameters loop */
08738    while (!ast_strlen_zero(nextm)) {
08739       int audio = FALSE;
08740       int video = FALSE;
08741       int image = FALSE;
08742       int text = FALSE;
08743       int x;
08744 
08745       numberofports = 1;
08746       len = -1;
08747       start = next;
08748       m = nextm;
08749       iterator = next;
08750       nextm = get_sdp_iterate(&next, req, "m");
08751 
08752       /* Search for audio media definition */
08753       if ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08754           (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
08755          audio = TRUE;
08756          p->offered_media[SDP_AUDIO].offered = TRUE;
08757          numberofmediastreams++;
08758          portno = x;
08759 
08760          /* Scan through the RTP payload types specified in a "m=" line: */
08761          codecs = m + len;
08762          ast_copy_string(p->offered_media[SDP_AUDIO].text, codecs, sizeof(p->offered_media[SDP_AUDIO].text));
08763          for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08764             if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08765                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08766                return -1;
08767             }
08768             if (debug)
08769                ast_verbose("Found RTP audio format %d\n", codec);
08770 
08771             ast_rtp_set_m_type(newaudiortp, codec);
08772          }
08773       /* Search for video media definition */
08774       } else if ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08775             (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len >= 0)) {
08776          video = TRUE;
08777          p->novideo = FALSE;
08778          p->offered_media[SDP_VIDEO].offered = TRUE;
08779          numberofmediastreams++;
08780          vportno = x;
08781 
08782          /* Scan through the RTP payload types specified in a "m=" line: */
08783          codecs = m + len;
08784          ast_copy_string(p->offered_media[SDP_VIDEO].text, codecs, sizeof(p->offered_media[SDP_VIDEO].text));
08785          for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08786             if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08787                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08788                return -1;
08789             }
08790             if (debug)
08791                ast_verbose("Found RTP video format %d\n", codec);
08792             ast_rtp_set_m_type(newvideortp, codec);
08793          }
08794       /* Search for text media definition */
08795       } else if ((sscanf(m, "text %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08796             (sscanf(m, "text %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
08797          text = TRUE;
08798          p->notext = FALSE;
08799          p->offered_media[SDP_TEXT].offered = TRUE;
08800          numberofmediastreams++;
08801          tportno = x;
08802 
08803          /* Scan through the RTP payload types specified in a "m=" line: */
08804          codecs = m + len;
08805          ast_copy_string(p->offered_media[SDP_TEXT].text, codecs, sizeof(p->offered_media[SDP_TEXT].text));
08806          for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08807             if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08808                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08809                return -1;
08810             }
08811             if (debug)
08812                ast_verbose("Found RTP text format %d\n", codec);
08813             ast_rtp_set_m_type(newtextrtp, codec);
08814          }
08815       /* Search for image media definition */
08816       } else if (p->udptl && ((sscanf(m, "image %30u udptl t38%n", &x, &len) == 1 && len > 0) ||
08817                (sscanf(m, "image %30u UDPTL t38%n", &x, &len) == 1 && len > 0) )) {
08818          image = TRUE;
08819          if (debug)
08820             ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
08821          p->offered_media[SDP_IMAGE].offered = TRUE;
08822          udptlportno = x;
08823          numberofmediastreams++;
08824 
08825          if (p->t38.state != T38_ENABLED) {
08826             memset(&p->t38.their_parms, 0, sizeof(p->t38.their_parms));
08827 
08828             /* default EC to none, the remote end should
08829              * respond with the EC they want to use */
08830             ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
08831          }
08832       } else {
08833          ast_log(LOG_WARNING, "Unsupported SDP media type in offer: %s\n", m);
08834          continue;
08835       }
08836 
08837       /* Check for number of ports */
08838       if (numberofports > 1)
08839          ast_log(LOG_WARNING, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports);
08840       
08841 
08842 
08843       /* Media stream specific parameters */
08844       while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
08845          int processed = FALSE;
08846 
08847          switch (type) {
08848          case 'c':
08849             if (audio) {
08850                if (process_sdp_c(value, &audiohp)) {
08851                   processed = TRUE;
08852                   hp = &audiohp.hp;
08853                }
08854             } else if (video) {
08855                if (process_sdp_c(value, &videohp)) {
08856                   processed = TRUE;
08857                   vhp = &videohp.hp;
08858                }
08859             } else if (text) {
08860                if (process_sdp_c(value, &texthp)) {
08861                   processed = TRUE;
08862                   thp = &texthp.hp;
08863                }
08864             } else if (image) {
08865                if (process_sdp_c(value, &imagehp)) {
08866                   processed = TRUE;
08867                   ihp = &imagehp.hp;
08868                }
08869             }
08870             break;
08871          case 'a':
08872             /* Audio specific scanning */
08873             if (audio) {
08874                if (process_sdp_a_sendonly(value, &sendonly))
08875                   processed = TRUE;
08876                else if (process_sdp_a_audio(value, p, newaudiortp, &last_rtpmap_codec))
08877                   processed = TRUE;
08878             }
08879             /* Video specific scanning */
08880             else if (video) {
08881                if (process_sdp_a_sendonly(value, &vsendonly))
08882                   processed = TRUE;
08883                else if (process_sdp_a_video(value, p, newvideortp, &last_rtpmap_codec))
08884                   processed = TRUE;
08885             }
08886             /* Text (T.140) specific scanning */
08887             else if (text) {
08888                if (process_sdp_a_text(value, p, newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
08889                   processed = TRUE;
08890             }
08891             /* Image (T.38 FAX) specific scanning */
08892             else if (image) {
08893                if (process_sdp_a_image(value, p))
08894                   processed = TRUE;
08895             }
08896             break;
08897          }
08898 
08899          if (option_debug > 2)
08900             ast_log(LOG_DEBUG, "Processing media-level (%s) SDP %c=%s... %s\n",
08901                   (audio == TRUE)? "audio" : (video == TRUE)? "video" : "image",
08902                   type, value,
08903                   (processed == TRUE)? "OK." : "UNSUPPORTED.");
08904       }
08905    }
08906 
08907 
08908    /* Sanity checks */
08909    if (!hp && !vhp && !thp && !ihp) {
08910       ast_log(LOG_WARNING, "Insufficient information in SDP (c=)...\n");
08911       return -1;
08912    }
08913 
08914    if (portno == -1 && vportno == -1 && udptlportno == -1  && tportno == -1)
08915       /* No acceptable offer found in SDP  - we have no ports */
08916       /* Do not change RTP or VRTP if this is a re-invite */
08917       return -2;
08918 
08919    if (numberofmediastreams > 3)
08920       /* We have too many fax, audio and/or video and/or text media streams, fail this offer */
08921       return -3;
08922 
08923    if (udptlportno == -1) {
08924       change_t38_state(p, T38_DISABLED);
08925    }
08926 
08927 
08928    /* Now gather all of the codecs that we are asked for: */
08929    ast_rtp_get_current_formats(newaudiortp, &peercapability, &peernoncodeccapability);
08930    ast_rtp_get_current_formats(newvideortp, &vpeercapability, &vpeernoncodeccapability);
08931    ast_rtp_get_current_formats(newtextrtp, &tpeercapability, &tpeernoncodeccapability);
08932 
08933    newjointcapability = p->capability & (peercapability | vpeercapability | tpeercapability);
08934    newpeercapability = (peercapability | vpeercapability | tpeercapability);
08935    newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
08936 
08937    if (debug) {
08938       /* shame on whoever coded this.... */
08939       char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE], s5[SIPBUFSIZE];
08940 
08941       ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s/text=%s, combined - %s\n",
08942              ast_getformatname_multiple(s1, SIPBUFSIZE, p->capability),
08943              ast_getformatname_multiple(s2, SIPBUFSIZE, peercapability),
08944              ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
08945              ast_getformatname_multiple(s4, SIPBUFSIZE, tpeercapability),
08946              ast_getformatname_multiple(s5, SIPBUFSIZE, newjointcapability));
08947 
08948       ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
08949              ast_rtp_lookup_mime_multiple(s1, SIPBUFSIZE, p->noncodeccapability, 0, 0),
08950              ast_rtp_lookup_mime_multiple(s2, SIPBUFSIZE, peernoncodeccapability, 0, 0),
08951              ast_rtp_lookup_mime_multiple(s3, SIPBUFSIZE, newnoncodeccapability, 0, 0));
08952    }
08953    if (!newjointcapability && (portno != -1)) {
08954       ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
08955       /* Do NOT Change current setting */
08956       return -1;
08957    }
08958 
08959    /* Setup audio address and port */
08960    if (p->rtp) {
08961       if (portno > 0) {
08962          sin.sin_family = AF_INET;
08963          sin.sin_port = htons(portno);
08964          memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
08965          ast_rtp_set_peer(p->rtp, &sin);
08966          if (debug)
08967             ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
08968          /* We are now ready to change the sip session and p->rtp and p->vrtp with the offered codecs, since                                                                                                    
08969             they are acceptable */
08970          p->jointcapability = newjointcapability;                /* Our joint codec profile for this call */
08971          p->peercapability = newpeercapability;                  /* The other sides capability in latest offer */
08972          p->jointnoncodeccapability = newnoncodeccapability;     /* DTMF capabilities */
08973 
08974          ast_rtp_pt_copy(p->rtp, newaudiortp);
08975 
08976          if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
08977             ast_clear_flag(&p->flags[0], SIP_DTMF);
08978             if (newnoncodeccapability & AST_RTP_DTMF) {
08979                /* XXX Would it be reasonable to drop the DSP at this point? XXX */
08980                ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
08981                /* Since RFC2833 is now negotiated we need to change some properties of the RTP stream */
08982                ast_rtp_setdtmf(p->rtp, 1);
08983                ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
08984             } else {
08985                ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
08986             }
08987          }
08988       } else if (udptlportno > 0) {
08989          if (debug)
08990             ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session.\n");
08991       } else {
08992          ast_rtp_stop(p->rtp);
08993          if (debug)
08994             ast_verbose("Peer doesn't provide audio\n");
08995       }
08996    }
08997 
08998    /* Setup video address and port */
08999    if (p->vrtp) {
09000       if (vportno > 0) {
09001          vsin.sin_family = AF_INET;
09002          vsin.sin_port = htons(vportno);
09003          memcpy(&vsin.sin_addr, vhp->h_addr, sizeof(vsin.sin_addr));
09004          ast_rtp_set_peer(p->vrtp, &vsin);
09005          if (debug) 
09006             ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(vsin.sin_addr), ntohs(vsin.sin_port));
09007          ast_rtp_pt_copy(p->vrtp, newvideortp);
09008       } else {
09009          ast_rtp_stop(p->vrtp);
09010          if (debug)
09011             ast_verbose("Peer doesn't provide video\n");
09012       }
09013    }
09014 
09015    /* Setup text address and port */
09016    if (p->trtp) {
09017       if (tportno > 0) {
09018          tsin.sin_family = AF_INET;
09019          tsin.sin_port = htons(tportno);
09020          memcpy(&tsin.sin_addr, thp->h_addr, sizeof(tsin.sin_addr));
09021          ast_rtp_set_peer(p->trtp, &tsin);
09022          if (debug) 
09023             ast_verbose("Peer T.140 RTP is at port %s:%d\n", ast_inet_ntoa(tsin.sin_addr), ntohs(tsin.sin_port));
09024          if ((p->jointcapability & AST_FORMAT_T140RED)) {
09025             p->red = 1;
09026             rtp_red_init(p->trtp, 300, red_data_pt, 2);
09027          } else {
09028             p->red = 0;
09029          }
09030          ast_rtp_pt_copy(p->trtp, newtextrtp);
09031       } else {
09032          ast_rtp_stop(p->trtp);
09033          if (debug)
09034             ast_verbose("Peer doesn't provide T.140\n");
09035       }
09036    }
09037    /* Setup image address and port */
09038    if (p->udptl) {
09039       if (udptlportno > 0) {
09040          isin.sin_family = AF_INET;
09041          isin.sin_port = htons(udptlportno);
09042          if (ast_test_flag(&p->flags[0], SIP_NAT) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
09043             struct sockaddr_in remote_address = { 0, };
09044             ast_rtp_get_peer(p->rtp, &remote_address);
09045             if (remote_address.sin_addr.s_addr) {
09046                memcpy(&isin, &remote_address, sizeof(isin));
09047                if (debug) {
09048                   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));
09049                }
09050             }
09051          } else {
09052             memcpy(&isin.sin_addr, ihp->h_addr, sizeof(isin.sin_addr));
09053          }
09054          ast_udptl_set_peer(p->udptl, &isin);
09055          if (debug)
09056             ast_debug(1,"Peer T.38 UDPTL is at port %s:%d\n", ast_inet_ntoa(isin.sin_addr), ntohs(isin.sin_port));
09057 
09058          /* verify the far max ifp can be calculated. this requires far max datagram to be set. */
09059          if (!ast_udptl_get_far_max_datagram(p->udptl)) {
09060             /* setting to zero will force a default if none was provided by the SDP */
09061             ast_udptl_set_far_max_datagram(p->udptl, 0);
09062          }
09063 
09064          /* Remote party offers T38, we need to update state */
09065          if ((t38action == SDP_T38_ACCEPT) &&
09066              (p->t38.state == T38_LOCAL_REINVITE)) {
09067             change_t38_state(p, T38_ENABLED);
09068          } else if ((t38action == SDP_T38_INITIATE) &&
09069                p->owner && p->lastinvite) {
09070             change_t38_state(p, T38_PEER_REINVITE); /* T38 Offered in re-invite from remote party */
09071             /* If fax detection is enabled then send us off to the fax extension */
09072             if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38)) {
09073                ast_channel_lock(p->owner);
09074                if (strcmp(p->owner->exten, "fax")) {
09075                   const char *target_context = S_OR(p->owner->macrocontext, p->owner->context);
09076                   ast_channel_unlock(p->owner);
09077                   if (ast_exists_extension(p->owner, target_context, "fax", 1, p->owner->cid.cid_num)) {
09078                      ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to peer T.38 re-INVITE\n", p->owner->name);
09079                      pbx_builtin_setvar_helper(p->owner, "FAXEXTEN", p->owner->exten);
09080                      if (ast_async_goto(p->owner, target_context, "fax", 1)) {
09081                         ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", p->owner->name, target_context);
09082                      }
09083                   } else {
09084                      ast_log(LOG_NOTICE, "T.38 re-INVITE detected but no fax extension\n");
09085                   }
09086                } else {
09087                   ast_channel_unlock(p->owner);
09088                }
09089             }
09090          }
09091       } else {
09092          ast_udptl_stop(p->udptl);
09093          if (debug)
09094             ast_debug(1, "Peer doesn't provide T.38 UDPTL\n");
09095       }
09096    }
09097 
09098    if ((portno == -1) && (p->t38.state != T38_DISABLED)) {
09099       ast_debug(3, "Have T.38 but no audio, accepting offer anyway\n");
09100                 return 0;
09101         }
09102 
09103    /* Ok, we're going with this offer */
09104    ast_debug(2, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcapability));
09105 
09106    if (!p->owner)    /* There's no open channel owning us so we can return here. For a re-invite or so, we proceed */
09107       return 0;
09108 
09109    ast_debug(4, "We have an owner, now see if we need to change this call\n");
09110 
09111    if (!(p->owner->nativeformats & p->jointcapability) && (p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
09112       if (debug) {
09113          char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
09114          ast_debug(1, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n", 
09115             ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcapability),
09116             ast_getformatname_multiple(s2, SIPBUFSIZE, p->owner->nativeformats));
09117       }
09118       p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability) | (p->capability & tpeercapability);
09119       ast_set_read_format(p->owner, p->owner->readformat);
09120       ast_set_write_format(p->owner, p->owner->writeformat);
09121    }
09122    
09123    if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)
09124          && (sin.sin_addr.s_addr || vsin.sin_addr.s_addr ||
09125          isin.sin_addr.s_addr || tsin.sin_addr.s_addr)
09126          && (!sendonly || sendonly == -1)) {
09127       ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
09128       /* Activate a re-invite */
09129       ast_queue_frame(p->owner, &ast_null_frame);
09130       change_hold_state(p, req, FALSE, sendonly);
09131    } else if (!(sin.sin_addr.s_addr || vsin.sin_addr.s_addr ||
09132          isin.sin_addr.s_addr || tsin.sin_addr.s_addr)
09133          || (sendonly && sendonly != -1)) {
09134       ast_queue_control_data(p->owner, AST_CONTROL_HOLD, 
09135                    S_OR(p->mohsuggest, NULL),
09136                    !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
09137       if (sendonly)
09138          ast_rtp_stop(p->rtp);
09139       /* RTCP needs to go ahead, even if we're on hold!!! */
09140       /* Activate a re-invite */
09141       ast_queue_frame(p->owner, &ast_null_frame);
09142       change_hold_state(p, req, TRUE, sendonly);
09143    }
09144    
09145    return 0;
09146 }
09147 
09148 static int process_sdp_o(const char *o, struct sip_pvt *p)
09149 {
09150    char *o_copy;
09151    char *token;
09152    int64_t rua_version;
09153 
09154    /* Store the SDP version number of remote UA. This will allow us to
09155    distinguish between session modifications and session refreshes. If
09156    the remote UA does not send an incremented SDP version number in a
09157    subsequent RE-INVITE then that means its not changing media session.
09158    The RE-INVITE may have been sent to update connected party, remote
09159    target or to refresh the session (Session-Timers).  Asterisk must not
09160    change media session and increment its own version number in answer
09161    SDP in this case. */
09162 
09163    p->session_modify = TRUE;
09164 
09165    if (ast_strlen_zero(o)) {
09166       ast_log(LOG_WARNING, "SDP syntax error. SDP without an o= line\n");
09167       return FALSE;
09168    }
09169 
09170    o_copy = ast_strdupa(o);
09171    token = strsep(&o_copy, " ");  /* Skip username   */
09172    if (!o_copy) {
09173       ast_log(LOG_WARNING, "SDP syntax error in o= line username\n");
09174       return FALSE;
09175    }
09176    token = strsep(&o_copy, " ");  /* Skip session-id */
09177    if (!o_copy) {
09178       ast_log(LOG_WARNING, "SDP syntax error in o= line session-id\n");
09179       return FALSE;
09180    }
09181    token = strsep(&o_copy, " ");  /* Version         */
09182    if (!o_copy) {
09183       ast_log(LOG_WARNING, "SDP syntax error in o= line\n");
09184       return FALSE;
09185    }
09186    if (!sscanf(token, "%30" SCNd64, &rua_version)) {
09187       ast_log(LOG_WARNING, "SDP syntax error in o= line version\n");
09188       return FALSE;
09189    }
09190 
09191    /* we need to check the SDP version number the other end sent us;
09192     * our rules for deciding what to accept are a bit complex.
09193     *
09194     * 1) if 'ignoresdpversion' has been set for this dialog, then
09195     *    we will just accept whatever they sent and assume it is
09196     *    a modification of the session, even if it is not
09197     * 2) otherwise, if this is the first SDP we've seen from them
09198     *    we accept it
09199     * 3) otherwise, if the new SDP version number is higher than the
09200     *    old one, we accept it
09201     * 4) otherwise, if this SDP is in response to us requesting a switch
09202     *    to T.38, we accept the SDP, but also generate a warning message
09203     *    that this peer should have the 'ignoresdpversion' option set,
09204     *    because it is not following the SDP offer/answer RFC; if we did
09205     *    not request a switch to T.38, then we stop parsing the SDP, as it
09206     *    has not changed from the previous version
09207     */
09208 
09209    if (ast_test_flag(&p->flags[1], SIP_PAGE2_IGNORESDPVERSION) ||
09210        (p->sessionversion_remote < 0) ||
09211        (p->sessionversion_remote < rua_version)) {
09212       p->sessionversion_remote = rua_version;
09213    } else {
09214       if (p->t38.state == T38_LOCAL_REINVITE) {
09215          p->sessionversion_remote = rua_version;
09216          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);
09217       } else {
09218          p->session_modify = FALSE;
09219          ast_debug(2, "Call %s responded to our reinvite without changing SDP version; ignoring SDP.\n", p->callid);
09220          return FALSE;
09221       }
09222    }
09223 
09224    return TRUE;
09225 }
09226 
09227 static int process_sdp_c(const char *c, struct ast_hostent *ast_hp)
09228 {
09229    char host[258];
09230    struct hostent *hp;
09231 
09232    /* Check for Media-description-level-address */
09233    if (sscanf(c, "IN IP4 %255s", host) != 1) {
09234       ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
09235       return FALSE;
09236    } else {
09237       if (!(hp = ast_gethostbyname(host, ast_hp))) {
09238          ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in c= line, '%s'\n", c);
09239          return FALSE;
09240       }
09241       return TRUE;
09242    }
09243    return FALSE;
09244 }
09245 
09246 static int process_sdp_a_sendonly(const char *a, int *sendonly)
09247 {
09248    int found = FALSE;
09249 
09250    if (!strcasecmp(a, "sendonly")) {
09251       if (*sendonly == -1)
09252          *sendonly = 1;
09253       found = TRUE;
09254    } else if (!strcasecmp(a, "inactive")) {
09255       if (*sendonly == -1)
09256          *sendonly = 2;
09257       found = TRUE;
09258    }  else if (!strcasecmp(a, "sendrecv")) {
09259       if (*sendonly == -1)
09260          *sendonly = 0;
09261       found = TRUE;
09262    }
09263    return found;
09264 }
09265 
09266 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp *newaudiortp, int *last_rtpmap_codec)
09267 {
09268    int found = FALSE;
09269    int codec;
09270    char mimeSubtype[128];
09271    char fmtp_string[64];
09272    unsigned int sample_rate;
09273    int debug = sip_debug_test_pvt(p);
09274 
09275    if (!strncasecmp(a, "ptime", 5)) {
09276       char *tmp = strrchr(a, ':');
09277       long int framing = 0;
09278       if (tmp) {
09279          tmp++;
09280          framing = strtol(tmp, NULL, 10);
09281          if (framing == LONG_MIN || framing == LONG_MAX) {
09282             framing = 0;
09283             ast_debug(1, "Can't read framing from SDP: %s\n", a);
09284          }
09285       }
09286       if (framing && p->autoframing) {
09287          struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
09288          int codec_n;
09289          int format = 0;
09290          for (codec_n = 0; codec_n < MAX_RTP_PT; codec_n++) {
09291             format = ast_rtp_codec_getformat(codec_n);
09292             if (!format)   /* non-codec or not found */
09293                continue;
09294             if (option_debug)
09295                ast_log(LOG_DEBUG, "Setting framing for %d to %ld\n", format, framing);
09296             ast_codec_pref_setsize(pref, format, framing);
09297          }
09298          ast_rtp_codec_setpref(p->rtp, pref);
09299       }
09300       found = TRUE;
09301    } else if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
09302       /* We have a rtpmap to handle */
09303       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
09304          if (ast_rtp_set_rtpmap_type_rate(newaudiortp, codec, "audio", mimeSubtype,
09305              ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0, sample_rate) != -1) {
09306             if (debug)
09307                ast_verbose("Found audio description format %s for ID %d\n", mimeSubtype, codec);
09308             //found_rtpmap_codecs[last_rtpmap_codec] = codec;
09309             (*last_rtpmap_codec)++;
09310             found = TRUE;
09311          } else {
09312             ast_rtp_unset_m_type(newaudiortp, codec);
09313             if (debug)
09314                ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
09315          }
09316       } else {
09317          if (debug)
09318             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
09319       }
09320    } else if (sscanf(a, "fmtp: %30u %63s", &codec, fmtp_string) == 2) {
09321       struct rtpPayloadType payload;
09322 
09323       payload = ast_rtp_lookup_pt(newaudiortp, codec);
09324       if (payload.code && payload.isAstFormat) {
09325          unsigned int bit_rate;
09326 
09327          switch (payload.code) {
09328          case AST_FORMAT_SIREN7:
09329             if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
09330                if (bit_rate != 32000) {
09331                   ast_log(LOG_WARNING, "Got Siren7 offer at %d bps, but only 32000 bps supported; ignoring.\n", bit_rate);
09332                   ast_rtp_unset_m_type(newaudiortp, codec);
09333                } else {
09334                   found = TRUE;
09335                }
09336             }
09337             break;
09338          case AST_FORMAT_SIREN14:
09339             if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
09340                if (bit_rate != 48000) {
09341                   ast_log(LOG_WARNING, "Got Siren14 offer at %d bps, but only 48000 bps supported; ignoring.\n", bit_rate);
09342                   ast_rtp_unset_m_type(newaudiortp, codec);
09343                } else {
09344                   found = TRUE;
09345                }
09346             }
09347             break;
09348          }
09349       }
09350    }
09351 
09352    return found;
09353 }
09354 
09355 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp *newvideortp, int *last_rtpmap_codec)
09356 {
09357    int found = FALSE;
09358    int codec;
09359    char mimeSubtype[128];
09360    unsigned int sample_rate;
09361    int debug = sip_debug_test_pvt(p);
09362 
09363    if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
09364       /* We have a rtpmap to handle */
09365       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
09366          /* Note: should really look at the '#chans' params too */
09367          if (!strncasecmp(mimeSubtype, "H26", 3) || !strncasecmp(mimeSubtype, "MP4", 3)) {
09368             if (ast_rtp_set_rtpmap_type_rate(newvideortp, codec, "video", mimeSubtype, 0, sample_rate) != -1) {
09369                if (debug)
09370                   ast_verbose("Found video description format %s for ID %d\n", mimeSubtype, codec);
09371                //found_rtpmap_codecs[last_rtpmap_codec] = codec;
09372                (*last_rtpmap_codec)++;
09373                found = TRUE;
09374             } else {
09375                ast_rtp_unset_m_type(newvideortp, codec);
09376                if (debug) 
09377                   ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
09378             }
09379          }
09380       } else {
09381          if (debug)
09382             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
09383       }
09384    }
09385 
09386    return found;
09387 }
09388 
09389 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)
09390 {
09391    int found = FALSE;
09392    int codec;
09393    char mimeSubtype[128];
09394    unsigned int sample_rate;
09395    char *red_cp;
09396    int debug = sip_debug_test_pvt(p);
09397 
09398    if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
09399       /* We have a rtpmap to handle */
09400       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
09401          if (!strncasecmp(mimeSubtype, "T140", 4)) { /* Text */
09402             if (p->trtp) {
09403                /* ast_verbose("Adding t140 mimeSubtype to textrtp struct\n"); */
09404                ast_rtp_set_rtpmap_type(newtextrtp, codec, "text", mimeSubtype, 0);
09405                found = TRUE;
09406             }
09407          } else if (!strncasecmp(mimeSubtype, "RED", 3)) { /* Text with Redudancy */
09408             if (p->trtp) {
09409                ast_rtp_set_rtpmap_type(newtextrtp, codec, "text", mimeSubtype, 0);
09410                sprintf(red_fmtp, "fmtp:%d ", codec); 
09411                if (debug)
09412                   ast_verbose("RED submimetype has payload type: %d\n", codec);
09413                found = TRUE;
09414             }
09415          }
09416       } else {
09417          if (debug)
09418             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
09419       }
09420    } else if (!strncmp(a, red_fmtp, strlen(red_fmtp))) {
09421       /* count numbers of generations in fmtp */
09422       red_cp = &red_fmtp[strlen(red_fmtp)];
09423       strncpy(red_fmtp, a, 100);
09424 
09425       sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
09426       red_cp = strtok(red_cp, "/");
09427       while (red_cp && (*red_num_gen)++ < RED_MAX_GENERATION) {
09428          sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
09429          red_cp = strtok(NULL, "/");
09430       }
09431       red_cp = red_fmtp;
09432       found = TRUE;
09433    }
09434 
09435    return found;
09436 }
09437 
09438 static int process_sdp_a_image(const char *a, struct sip_pvt *p)
09439 {
09440    int found = FALSE;
09441    char s[256];
09442    unsigned int x;
09443 
09444    if ((sscanf(a, "T38FaxMaxBuffer:%30u", &x) == 1)) {
09445       ast_debug(3, "MaxBufferSize:%d\n", x);
09446       found = TRUE;
09447    } else if ((sscanf(a, "T38MaxBitRate:%30u", &x) == 1) || (sscanf(a, "T38FaxMaxRate:%30u", &x) == 1)) {
09448       ast_debug(3, "T38MaxBitRate: %d\n", x);
09449       switch (x) {
09450       case 14400:
09451          p->t38.their_parms.rate = AST_T38_RATE_14400;
09452          break;
09453       case 12000:
09454          p->t38.their_parms.rate = AST_T38_RATE_12000;
09455          break;
09456       case 9600:
09457          p->t38.their_parms.rate = AST_T38_RATE_9600;
09458          break;
09459       case 7200:
09460          p->t38.their_parms.rate = AST_T38_RATE_7200;
09461          break;
09462       case 4800:
09463          p->t38.their_parms.rate = AST_T38_RATE_4800;
09464          break;
09465       case 2400:
09466          p->t38.their_parms.rate = AST_T38_RATE_2400;
09467          break;
09468       }
09469       found = TRUE;
09470    } else if ((sscanf(a, "T38FaxVersion:%30u", &x) == 1)) {
09471       ast_debug(3, "FaxVersion: %u\n", x);
09472       p->t38.their_parms.version = x;
09473       found = TRUE;
09474    } else if ((sscanf(a, "T38FaxMaxDatagram:%30u", &x) == 1) || (sscanf(a, "T38MaxDatagram:%30u", &x) == 1)) {
09475       /* override the supplied value if the configuration requests it */
09476       if (((signed int) p->t38_maxdatagram >= 0) && ((unsigned int) p->t38_maxdatagram > x)) {
09477          ast_debug(1, "Overriding T38FaxMaxDatagram '%d' with '%d'\n", x, p->t38_maxdatagram);
09478          x = p->t38_maxdatagram;
09479       }
09480       ast_debug(3, "FaxMaxDatagram: %u\n", x);
09481       ast_udptl_set_far_max_datagram(p->udptl, x);
09482       found = TRUE;
09483    } else if ((strncmp(a, "T38FaxFillBitRemoval", 20) == 0)) {
09484       if (sscanf(a, "T38FaxFillBitRemoval:%30u", &x) == 1) {
09485          ast_debug(3, "FillBitRemoval: %d\n", x);
09486          if (x == 1) {
09487             p->t38.their_parms.fill_bit_removal = TRUE;
09488          }
09489       } else {
09490          ast_debug(3, "FillBitRemoval\n");
09491          p->t38.their_parms.fill_bit_removal = TRUE;
09492       }
09493       found = TRUE;
09494    } else if ((strncmp(a, "T38FaxTranscodingMMR", 20) == 0)) {
09495       if (sscanf(a, "T38FaxTranscodingMMR:%30u", &x) == 1) {
09496          ast_debug(3, "Transcoding MMR: %d\n", x);
09497          if (x == 1) {
09498             p->t38.their_parms.transcoding_mmr = TRUE;
09499          }
09500       } else {
09501          ast_debug(3, "Transcoding MMR\n");
09502          p->t38.their_parms.transcoding_mmr = TRUE;
09503       }
09504       found = TRUE;
09505    } else if ((strncmp(a, "T38FaxTranscodingJBIG", 21) == 0)) {
09506       if (sscanf(a, "T38FaxTranscodingJBIG:%30u", &x) == 1) {
09507          ast_debug(3, "Transcoding JBIG: %d\n", x);
09508          if (x == 1) {
09509             p->t38.their_parms.transcoding_jbig = TRUE;
09510          }
09511       } else {
09512          ast_debug(3, "Transcoding JBIG\n");
09513          p->t38.their_parms.transcoding_jbig = TRUE;
09514       }
09515       found = TRUE;
09516    } else if ((sscanf(a, "T38FaxRateManagement:%255s", s) == 1)) {
09517       ast_debug(3, "RateManagement: %s\n", s);
09518       if (!strcasecmp(s, "localTCF"))
09519          p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_LOCAL_TCF;
09520       else if (!strcasecmp(s, "transferredTCF"))
09521          p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF;
09522       found = TRUE;
09523    } else if ((sscanf(a, "T38FaxUdpEC:%255s", s) == 1)) {
09524       ast_debug(3, "UDP EC: %s\n", s);
09525       if (!strcasecmp(s, "t38UDPRedundancy")) {
09526          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
09527       } else if (!strcasecmp(s, "t38UDPFEC")) {
09528          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
09529       } else {
09530          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
09531       }
09532       found = TRUE;
09533    }
09534 
09535    return found;
09536 }
09537 
09538 
09539 #ifdef LOW_MEMORY
09540 static void ts_ast_rtp_destroy(void *data)
09541 {
09542     struct ast_rtp *tmp = data;
09543     ast_rtp_destroy(tmp);
09544 }
09545 #endif
09546 
09547 /*! \brief Add "Supported" header to sip message.  Since some options may
09548  *  be disabled in the config, the sip_pvt must be inspected to determine what
09549  *  is supported for this dialog. */
09550 static int add_supported_header(struct sip_pvt *pvt, struct sip_request *req)
09551 {
09552    int res;
09553    if (st_get_mode(pvt, 0) != SESSION_TIMER_MODE_REFUSE) {
09554       res = add_header(req, "Supported", "replaces, timer");
09555    } else {
09556       res = add_header(req, "Supported", "replaces");
09557    }
09558    return res;
09559 }
09560 
09561 /*! \brief Add header to SIP message */
09562 static int add_header(struct sip_request *req, const char *var, const char *value)
09563 {
09564    if (req->headers == SIP_MAX_HEADERS) {
09565       ast_log(LOG_WARNING, "Out of SIP header space\n");
09566       return -1;
09567    }
09568 
09569    if (req->lines) {
09570       ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
09571       return -1;
09572    }
09573 
09574    if (sip_cfg.compactheaders) {
09575       var = find_alias(var, var);
09576    }
09577 
09578    ast_str_append(&req->data, 0, "%s: %s\r\n", var, value);
09579    req->header[req->headers] = req->len;
09580 
09581    req->len = ast_str_strlen(req->data);
09582    req->headers++;
09583 
09584    return 0;   
09585 }
09586 
09587 /*! \brief Add 'Content-Length' header and content to SIP message */
09588 static int finalize_content(struct sip_request *req)
09589 {
09590    char clen[10];
09591 
09592    if (req->lines) {
09593       ast_log(LOG_WARNING, "finalize_content() called on a message that has already been finalized\n");
09594       return -1;
09595    }
09596 
09597    snprintf(clen, sizeof(clen), "%zd", ast_str_strlen(req->content));
09598    add_header(req, "Content-Length", clen);
09599 
09600    if (ast_str_strlen(req->content)) {
09601       ast_str_append(&req->data, 0, "\r\n%s", ast_str_buffer(req->content));
09602       req->len = ast_str_strlen(req->data);
09603    }
09604    req->lines = ast_str_strlen(req->content) ? 1 : 0;
09605    return 0;
09606 }
09607 
09608 /*! \brief Add content (not header) to SIP message */
09609 static int add_content(struct sip_request *req, const char *line)
09610 {
09611    if (req->lines) {
09612       ast_log(LOG_WARNING, "Can't add more content when the content has been finalized\n");
09613       return -1;
09614    }
09615 
09616    ast_str_append(&req->content, 0, "%s", line);
09617    return 0;
09618 }
09619 
09620 /*! \brief Copy one header field from one request to another */
09621 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
09622 {
09623    const char *tmp = get_header(orig, field);
09624 
09625    if (!ast_strlen_zero(tmp)) /* Add what we're responding to */
09626       return add_header(req, field, tmp);
09627    ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
09628    return -1;
09629 }
09630 
09631 /*! \brief Copy all headers from one request to another */
09632 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
09633 {
09634    int start = 0;
09635    int copied = 0;
09636    for (;;) {
09637       const char *tmp = __get_header(orig, field, &start);
09638 
09639       if (ast_strlen_zero(tmp))
09640          break;
09641       /* Add what we're responding to */
09642       add_header(req, field, tmp);
09643       copied++;
09644    }
09645    return copied ? 0 : -1;
09646 }
09647 
09648 /*! \brief Copy SIP VIA Headers from the request to the response
09649 \note If the client indicates that it wishes to know the port we received from,
09650    it adds ;rport without an argument to the topmost via header. We need to
09651    add the port number (from our point of view) to that parameter.
09652 \verbatim
09653    We always add ;received=<ip address> to the topmost via header.
09654 \endverbatim
09655    Received: RFC 3261, rport RFC 3581 */
09656 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
09657 {
09658    int copied = 0;
09659    int start = 0;
09660 
09661    for (;;) {
09662       char new[512];
09663       const char *oh = __get_header(orig, field, &start);
09664 
09665       if (ast_strlen_zero(oh))
09666          break;
09667 
09668       if (!copied) { /* Only check for empty rport in topmost via header */
09669          char leftmost[512], *others, *rport;
09670 
09671          /* Only work on leftmost value */
09672          ast_copy_string(leftmost, oh, sizeof(leftmost));
09673          others = strchr(leftmost, ',');
09674          if (others)
09675              *others++ = '\0';
09676 
09677          /* Find ;rport;  (empty request) */
09678          rport = strstr(leftmost, ";rport");
09679          if (rport && *(rport+6) == '=') 
09680             rport = NULL;     /* We already have a parameter to rport */
09681 
09682          /* Check rport if NAT=yes or NAT=rfc3581 (which is the default setting)  */
09683          if (rport && ((ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_ALWAYS) || (ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_RFC3581))) {
09684             /* We need to add received port - rport */
09685             char *end;
09686 
09687             rport = strstr(leftmost, ";rport");
09688 
09689             if (rport) {
09690                end = strchr(rport + 1, ';');
09691                if (end)
09692                   memmove(rport, end, strlen(end) + 1);
09693                else
09694                   *rport = '\0';
09695             }
09696 
09697             /* Add rport to first VIA header if requested */
09698             snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
09699                leftmost, ast_inet_ntoa(p->recv.sin_addr),
09700                ntohs(p->recv.sin_port),
09701                others ? "," : "", others ? others : "");
09702          } else {
09703             /* We should *always* add a received to the topmost via */
09704             snprintf(new, sizeof(new), "%s;received=%s%s%s",
09705                leftmost, ast_inet_ntoa(p->recv.sin_addr),
09706                others ? "," : "", others ? others : "");
09707          }
09708          oh = new;   /* the header to copy */
09709       }  /* else add the following via headers untouched */
09710       add_header(req, field, oh);
09711       copied++;
09712    }
09713    if (!copied) {
09714       ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
09715       return -1;
09716    }
09717    return 0;
09718 }
09719 
09720 /*! \brief Add route header into request per learned route */
09721 static void add_route(struct sip_request *req, struct sip_route *route)
09722 {
09723    char r[SIPBUFSIZE*2], *p;
09724    int n, rem = sizeof(r);
09725 
09726    if (!route)
09727       return;
09728 
09729    p = r;
09730    for (;route ; route = route->next) {
09731       n = strlen(route->hop);
09732       if (rem < n+3) /* we need room for ",<route>" */
09733          break;
09734       if (p != r) {  /* add a separator after fist route */
09735          *p++ = ',';
09736          --rem;
09737       }
09738       *p++ = '<';
09739       ast_copy_string(p, route->hop, rem); /* cannot fail */
09740       p += n;
09741       *p++ = '>';
09742       rem -= (n+2);
09743    }
09744    *p = '\0';
09745    add_header(req, "Route", r);
09746 }
09747 
09748 /*! \brief Set destination from SIP URI 
09749  *
09750  * Parse uri to h (host) and port - uri is already just the part inside the <> 
09751  * general form we are expecting is sip[s]:username[:password][;parameter]@host[:port][;...] 
09752  * If there's a port given, turn NAPTR/SRV off. NAPTR might indicate SIPS preference even
09753  * for SIP: uri's
09754  *
09755  * If there's a sips: uri scheme, TLS will be required. 
09756  */
09757 static void set_destination(struct sip_pvt *p, char *uri)
09758 {
09759    char *h, *maddr, hostname[256];
09760    int port, hn;
09761    struct hostent *hp;
09762    struct ast_hostent ahp;
09763    int debug=sip_debug_test_pvt(p);
09764    int tls_on = FALSE;
09765    int use_dns = sip_cfg.srvlookup;
09766 
09767    if (debug)
09768       ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
09769 
09770    /* Find and parse hostname */
09771    h = strchr(uri, '@');
09772    if (h)
09773       ++h;
09774    else {
09775       h = uri;
09776       if (!strncasecmp(h, "sip:", 4)) {
09777          h += 4;
09778       } else if (!strncasecmp(h, "sips:", 5)) {
09779          h += 5;
09780          tls_on = TRUE;
09781       }
09782    }
09783    hn = strcspn(h, ":;>") + 1;
09784    if (hn > sizeof(hostname)) 
09785       hn = sizeof(hostname);
09786    ast_copy_string(hostname, h, hn);
09787    /* XXX bug here if string has been trimmed to sizeof(hostname) */
09788    h += hn - 1;
09789 
09790    /* Is "port" present? if not default to STANDARD_SIP_PORT */
09791    if (*h == ':') {
09792       /* Parse port */
09793       ++h;
09794       port = strtol(h, &h, 10);
09795       use_dns = FALSE;
09796    } else
09797       port = tls_on ? STANDARD_TLS_PORT : STANDARD_SIP_PORT;
09798 
09799    /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
09800    maddr = strstr(h, "maddr=");
09801    if (maddr) {
09802       maddr += 6;
09803       hn = strspn(maddr, "0123456789.") + 1;
09804       if (hn > sizeof(hostname))
09805          hn = sizeof(hostname);
09806       ast_copy_string(hostname, maddr, hn);
09807    }
09808 
09809    /*! \todo XXX If we have use_dns on, then look for NAPTR/SRV, otherwise, just look for A records */
09810    
09811    hp = ast_gethostbyname(hostname, &ahp);
09812    if (hp == NULL)  {
09813       ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
09814       return;
09815    }
09816    p->sa.sin_family = AF_INET;
09817    memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
09818    p->sa.sin_port = htons(port);
09819    if (debug)
09820       ast_verbose("set_destination: set destination to %s, port %d\n", ast_inet_ntoa(p->sa.sin_addr), port);
09821 }
09822 
09823 /*! \brief Initialize SIP response, based on SIP request */
09824 static int init_resp(struct sip_request *resp, const char *msg)
09825 {
09826    /* Initialize a response */
09827    memset(resp, 0, sizeof(*resp));
09828    resp->method = SIP_RESPONSE;
09829    if (!(resp->data = ast_str_create(SIP_MIN_PACKET)))
09830       goto e_return;
09831    if (!(resp->content = ast_str_create(SIP_MIN_PACKET)))
09832       goto e_free_data;
09833    resp->header[0] = 0;
09834    ast_str_set(&resp->data, 0, "SIP/2.0 %s\r\n", msg);
09835    resp->len = resp->data->used;
09836    resp->headers++;
09837    return 0;
09838 
09839 e_free_data:
09840    ast_free(resp->data);
09841    resp->data = NULL;
09842 e_return:
09843    return -1;
09844 }
09845 
09846 /*! \brief Initialize SIP request */
09847 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
09848 {
09849    /* Initialize a request */
09850    memset(req, 0, sizeof(*req));
09851    if (!(req->data = ast_str_create(SIP_MIN_PACKET)))
09852       goto e_return;
09853    if (!(req->content = ast_str_create(SIP_MIN_PACKET)))
09854       goto e_free_data;
09855    req->method = sipmethod;
09856    req->header[0] = 0;
09857    ast_str_set(&req->data, 0, "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
09858    req->len = ast_str_strlen(req->data);
09859    req->headers++;
09860    return 0;
09861 
09862 e_free_data:
09863    ast_free(req->data);
09864    req->data = NULL;
09865 e_return:
09866    return -1;
09867 }
09868 
09869 /*! \brief Deinitialize SIP response/request */
09870 static void deinit_req(struct sip_request *req)
09871 {
09872    if (req->data) {
09873       ast_free(req->data);
09874       req->data = NULL;
09875    }
09876    if (req->content) {
09877       ast_free(req->content);
09878       req->content = NULL;
09879    }
09880 }
09881 
09882 
09883 /*! \brief Test if this response needs a contact header */
09884 static inline int resp_needs_contact(const char *msg, enum sipmethod method) {
09885    /* Requirements for Contact header inclusion in responses generated
09886     * from the header tables found in the following RFCs.  Where the
09887     * Contact header was marked mandatory (m) or optional (o) this
09888     * function returns 1.
09889     *
09890     * - RFC 3261 (ACK, BYE, CANCEL, INVITE, OPTIONS, REGISTER)
09891     * - RFC 2976 (INFO)
09892     * - RFC 3262 (PRACK)
09893     * - RFC 3265 (SUBSCRIBE, NOTIFY)
09894     * - RFC 3311 (UPDATE)
09895     * - RFC 3428 (MESSAGE)
09896     * - RFC 3515 (REFER)
09897     * - RFC 3903 (PUBLISH)
09898     */
09899 
09900    switch (method) {
09901       /* 1xx, 2xx, 3xx, 485 */
09902       case SIP_INVITE:
09903       case SIP_UPDATE:
09904       case SIP_SUBSCRIBE:
09905       case SIP_NOTIFY:
09906          if ((msg[0] >= '1' && msg[0] <= '3') || !strncmp(msg, "485", 3))
09907             return 1;
09908          break;
09909 
09910       /* 2xx, 3xx, 485 */
09911       case SIP_REGISTER:
09912       case SIP_OPTIONS:
09913          if (msg[0] == '2' || msg[0] == '3' || !strncmp(msg, "485", 3))
09914             return 1;
09915          break;
09916 
09917       /* 3xx, 485 */
09918       case SIP_BYE:
09919       case SIP_PRACK:
09920       case SIP_MESSAGE:
09921       case SIP_PUBLISH:
09922          if (msg[0] == '3' || !strncmp(msg, "485", 3))
09923             return 1;
09924          break;
09925 
09926       /* 2xx, 3xx, 4xx, 5xx, 6xx */
09927       case SIP_REFER:
09928          if (msg[0] >= '2' && msg[0] <= '6')
09929             return 1;
09930          break;
09931 
09932       /* contact will not be included for everything else */
09933       case SIP_ACK:
09934       case SIP_CANCEL:
09935       case SIP_INFO:
09936       case SIP_PING:
09937       default:
09938          return 0;
09939    }
09940    return 0;
09941 }
09942 
09943 /*! \brief Prepare SIP response packet */
09944 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
09945 {
09946    char newto[256];
09947    const char *ot;
09948 
09949    init_resp(resp, msg);
09950    copy_via_headers(p, resp, req, "Via");
09951    if (msg[0] == '1' || msg[0] == '2')
09952       copy_all_header(resp, req, "Record-Route");
09953    copy_header(resp, req, "From");
09954    ot = get_header(req, "To");
09955    if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
09956       /* Add the proper tag if we don't have it already.  If they have specified
09957          their tag, use it.  Otherwise, use our own tag */
09958       if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
09959          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
09960       else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
09961          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
09962       else
09963          ast_copy_string(newto, ot, sizeof(newto));
09964       ot = newto;
09965    }
09966    add_header(resp, "To", ot);
09967    copy_header(resp, req, "Call-ID");
09968    copy_header(resp, req, "CSeq");
09969    if (!ast_strlen_zero(global_useragent))
09970       add_header(resp, "Server", global_useragent);
09971    add_header(resp, "Allow", ALLOWED_METHODS);
09972    add_supported_header(p, resp);
09973 
09974    /* If this is an invite, add Session-Timers related headers if the feature is active for this session */
09975    if (p->method == SIP_INVITE && p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE) {
09976       char se_hdr[256];
09977       snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval, 
09978          strefresher2str(p->stimer->st_ref));
09979       add_header(resp, "Session-Expires", se_hdr);
09980    }
09981 
09982    if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
09983       /* For registration responses, we also need expiry and
09984          contact info */
09985       char tmp[256];
09986 
09987       snprintf(tmp, sizeof(tmp), "%d", p->expiry);
09988       add_header(resp, "Expires", tmp);
09989       if (p->expiry) {  /* Only add contact if we have an expiry time */
09990          char contact[SIPBUFSIZE];
09991          const char *contact_uri = p->method == SIP_SUBSCRIBE ? p->our_contact : p->fullcontact;
09992          char *brackets = strchr(contact_uri, '<');
09993          snprintf(contact, sizeof(contact), "%s%s%s;expires=%d", brackets ? "" : "<", contact_uri, brackets ? "" : ">", p->expiry);
09994          add_header(resp, "Contact", contact);  /* Not when we unregister */
09995       }
09996    } else if (!ast_strlen_zero(p->our_contact) && resp_needs_contact(msg, p->method)) {
09997       add_header(resp, "Contact", p->our_contact);
09998    }
09999 
10000    if (!ast_strlen_zero(p->url)) {
10001       add_header(resp, "Access-URL", p->url);
10002       ast_string_field_set(p, url, NULL);
10003    }
10004 
10005    /* default to routing the response to the address where the request
10006     * came from.  Since we don't have a transport layer, we do this here.
10007     * The process_via() function will update the port to either the port
10008     * specified in the via header or the default port later on (per RFC
10009     * 3261 section 18.2.2).
10010     */
10011    p->sa = p->recv;
10012 
10013    if (process_via(p, req)) {
10014       ast_log(LOG_WARNING, "error processing via header, will send response to originating address\n");
10015    }
10016 
10017    return 0;
10018 }
10019 
10020 /*! \brief Initialize a SIP request message (not the initial one in a dialog) */
10021 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch)
10022 {
10023    struct sip_request *orig = &p->initreq;
10024    char stripped[80];
10025    char tmp[80];
10026    char newto[256];
10027    const char *c;
10028    const char *ot, *of;
10029    int is_strict = FALSE;     /*!< Strict routing flag */
10030    int is_outbound = ast_test_flag(&p->flags[0], SIP_OUTGOING);   /* Session direction */
10031 
10032    memset(req, 0, sizeof(struct sip_request));
10033    
10034    snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
10035    
10036    if (!seqno) {
10037       p->ocseq++;
10038       seqno = p->ocseq;
10039    }
10040    
10041    /* A CANCEL must have the same branch as the INVITE that it is canceling. */
10042    if (sipmethod == SIP_CANCEL) {
10043       p->branch = p->invite_branch;
10044       build_via(p);
10045    } else if (newbranch && (sipmethod == SIP_INVITE)) {
10046       p->branch ^= ast_random();
10047       p->invite_branch = p->branch;
10048       build_via(p);
10049    } else if (newbranch) {
10050       p->branch ^= ast_random();
10051       build_via(p);
10052    }
10053 
10054    /* Check for strict or loose router */
10055    if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop, ";lr") == NULL) {
10056       is_strict = TRUE;
10057       if (sipdebug)
10058          ast_debug(1, "Strict routing enforced for session %s\n", p->callid);
10059    }
10060    
10061    if (sipmethod == SIP_CANCEL)
10062       c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2); /* Use original URI */
10063    else if (sipmethod == SIP_ACK) {
10064       /* Use URI from Contact: in 200 OK (if INVITE) 
10065       (we only have the contacturi on INVITEs) */
10066       if (!ast_strlen_zero(p->okcontacturi))
10067          c = is_strict ? p->route->hop : p->okcontacturi;
10068       else
10069          c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
10070    } else if (!ast_strlen_zero(p->okcontacturi)) 
10071       c = is_strict ? p->route->hop : p->okcontacturi; /* Use for BYE or REINVITE */
10072    else if (!ast_strlen_zero(p->uri)) 
10073       c = p->uri;
10074    else {
10075       char *n;
10076       /* We have no URI, use To: or From:  header as URI (depending on direction) */
10077       ast_copy_string(stripped, get_header(orig, is_outbound ? "To" : "From"),
10078             sizeof(stripped));
10079       n = get_in_brackets(stripped);
10080       c = remove_uri_parameters(n);
10081    }  
10082    init_req(req, sipmethod, c);
10083 
10084    snprintf(tmp, sizeof(tmp), "%d %s", seqno, sip_methods[sipmethod].text);
10085 
10086    add_header(req, "Via", p->via);
10087    if (p->route) {
10088       set_destination(p, p->route->hop);
10089       add_route(req, is_strict ? p->route->next : p->route);
10090    }
10091    add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
10092 
10093    ot = get_header(orig, "To");
10094    of = get_header(orig, "From");
10095 
10096    /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
10097       as our original request, including tag (or presumably lack thereof) */
10098    if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
10099       /* Add the proper tag if we don't have it already.  If they have specified
10100          their tag, use it.  Otherwise, use our own tag */
10101       if (is_outbound && !ast_strlen_zero(p->theirtag))
10102          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
10103       else if (!is_outbound)
10104          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
10105       else
10106          snprintf(newto, sizeof(newto), "%s", ot);
10107       ot = newto;
10108    }
10109 
10110    if (is_outbound) {
10111       add_header(req, "From", of);
10112       add_header(req, "To", ot);
10113    } else {
10114       add_header(req, "From", ot);
10115       add_header(req, "To", of);
10116    }
10117    /* Do not add Contact for MESSAGE, BYE and Cancel requests */
10118    if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
10119       add_header(req, "Contact", p->our_contact);
10120 
10121    copy_header(req, orig, "Call-ID");
10122    add_header(req, "CSeq", tmp);
10123 
10124    if (!ast_strlen_zero(global_useragent))
10125       add_header(req, "User-Agent", global_useragent);
10126 
10127    if (!ast_strlen_zero(p->rpid))
10128       add_header(req, "Remote-Party-ID", p->rpid);
10129 
10130    if (!ast_strlen_zero(p->url)) {
10131       add_header(req, "Access-URL", p->url);
10132       ast_string_field_set(p, url, NULL);
10133    }
10134 
10135    /* Add Session-Timers related headers if the feature is active for this session.
10136       An exception to this behavior is the ACK request. Since Asterisk never requires 
10137       session-timers support from a remote end-point (UAS) in an INVITE, it must 
10138       not send 'Require: timer' header in the ACK request. 
10139       This should only be added in the INVITE transactions, not MESSAGE or REFER or other
10140       in-dialog messages.
10141    */
10142    if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE 
10143        && sipmethod == SIP_INVITE) {
10144       char se_hdr[256];
10145       snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval, 
10146          strefresher2str(p->stimer->st_ref));
10147       add_header(req, "Session-Expires", se_hdr);
10148       snprintf(se_hdr, sizeof(se_hdr), "%d", st_get_se(p, FALSE));
10149       add_header(req, "Min-SE", se_hdr);
10150    }
10151 
10152    return 0;
10153 }
10154 
10155 /*! \brief Base transmit response function */
10156 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
10157 {
10158    struct sip_request resp;
10159    int seqno = 0;
10160 
10161    if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
10162       ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
10163       return -1;
10164    }
10165    respprep(&resp, p, msg, req);
10166    /* If we are cancelling an incoming invite for some reason, add information
10167       about the reason why we are doing this in clear text */
10168    if (p->method == SIP_INVITE && msg[0] != '1' && p->owner && p->owner->hangupcause) {
10169       char buf[10];
10170 
10171       add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
10172       snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
10173       add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
10174    }
10175    return send_response(p, &resp, reliable, seqno);
10176 }
10177 
10178 static int temp_pvt_init(void *data)
10179 {
10180    struct sip_pvt *p = data;
10181 
10182    p->do_history = 0;   /* XXX do we need it ? isn't already all 0 ? */
10183    return ast_string_field_init(p, 512);
10184 }
10185 
10186 static void temp_pvt_cleanup(void *data)
10187 {
10188    struct sip_pvt *p = data;
10189 
10190    ast_string_field_free_memory(p);
10191 
10192    ast_free(data);
10193 }
10194 
10195 /*! \brief Transmit response, no retransmits, using a temporary pvt structure */
10196 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)
10197 {
10198    struct sip_pvt *p = NULL;
10199 
10200    if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
10201       ast_log(LOG_ERROR, "Failed to get temporary pvt\n");
10202       return -1;
10203    }
10204 
10205    /* XXX the structure may be dirty from previous usage.
10206     * Here we should state clearly how we should reinitialize it
10207     * before using it.
10208     * E.g. certainly the threadstorage should be left alone,
10209     * but other thihngs such as flags etc. maybe need cleanup ?
10210     */
10211     
10212    /* Initialize the bare minimum */
10213    p->method = intended_method;
10214 
10215    if (!sin)
10216       p->ourip = internip;
10217    else {
10218       p->sa = *sin;
10219       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
10220    }
10221 
10222    p->branch = ast_random();
10223    make_our_tag(p->tag, sizeof(p->tag));
10224    p->ocseq = INITIAL_CSEQ;
10225 
10226    if (useglobal_nat && sin) {
10227       ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
10228       p->recv = *sin;
10229       do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
10230    }
10231 
10232    ast_string_field_set(p, fromdomain, default_fromdomain);
10233    build_via(p);
10234    ast_string_field_set(p, callid, callid);
10235 
10236    copy_socket_data(&p->socket, &req->socket);
10237 
10238    /* Use this temporary pvt structure to send the message */
10239    __transmit_response(p, msg, req, XMIT_UNRELIABLE);
10240 
10241    /* Free the string fields, but not the pool space */
10242    ast_string_field_init(p, 0);
10243 
10244    return 0;
10245 }
10246 
10247 /*! \brief Transmit response, no retransmits */
10248 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req) 
10249 {
10250    return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
10251 }
10252 
10253 /*! \brief Transmit response, no retransmits */
10254 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported) 
10255 {
10256    struct sip_request resp;
10257    respprep(&resp, p, msg, req);
10258    append_date(&resp);
10259    add_header(&resp, "Unsupported", unsupported);
10260    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10261 }
10262 
10263 /*! \brief Transmit 422 response with Min-SE header (Session-Timers)  */
10264 static int transmit_response_with_minse(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minse_int)
10265 {
10266    struct sip_request resp;
10267    char minse_str[20];
10268 
10269    respprep(&resp, p, msg, req);
10270    append_date(&resp);
10271 
10272    snprintf(minse_str, sizeof(minse_str), "%d", minse_int);
10273    add_header(&resp, "Min-SE", minse_str);
10274    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10275 }
10276 
10277 
10278 /*! \brief Transmit response, Make sure you get an ACK
10279    This is only used for responses to INVITEs, where we need to make sure we get an ACK
10280 */
10281 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
10282 {
10283    return __transmit_response(p, msg, req, req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL);
10284 }
10285 
10286 /*! \brief Append date to SIP message */
10287 static void append_date(struct sip_request *req)
10288 {
10289    char tmpdat[256];
10290    struct tm tm;
10291    time_t t = time(NULL);
10292 
10293    gmtime_r(&t, &tm);
10294    strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
10295    add_header(req, "Date", tmpdat);
10296 }
10297 
10298 /*! \brief Append date and content length before transmitting response */
10299 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
10300 {
10301    struct sip_request resp;
10302    respprep(&resp, p, msg, req);
10303    append_date(&resp);
10304    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10305 }
10306 
10307 /*! \brief Append Accept header, content length before transmitting response */
10308 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
10309 {
10310    struct sip_request resp;
10311    respprep(&resp, p, msg, req);
10312    add_header(&resp, "Accept", "application/sdp");
10313    return send_response(p, &resp, reliable, 0);
10314 }
10315 
10316 /*! \brief Respond with authorization request */
10317 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)
10318 {
10319    struct sip_request resp;
10320    char tmp[512];
10321    int seqno = 0;
10322 
10323    if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
10324       ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
10325       return -1;
10326    }
10327    /* Stale means that they sent us correct authentication, but 
10328       based it on an old challenge (nonce) */
10329    snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", sip_cfg.realm, randdata, stale ? ", stale=true" : "");
10330    respprep(&resp, p, msg, req);
10331    add_header(&resp, header, tmp);
10332    append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
10333    return send_response(p, &resp, reliable, seqno);
10334 }
10335 
10336 /* Only use a static string for the msg, here! */
10337 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp)
10338 {
10339    int res;
10340 
10341    if (!(res = with_sdp ? transmit_response_with_sdp(p, msg, req, XMIT_UNRELIABLE, FALSE) : transmit_response(p, msg, req))) {
10342       p->last_provisional = msg;
10343       update_provisional_keepalive(p, with_sdp);
10344    }
10345 
10346    return res;
10347 }
10348 
10349 /*! \brief Add text body to SIP message */
10350 static int add_text(struct sip_request *req, const char *text)
10351 {
10352    /* XXX Convert \n's to \r\n's XXX */
10353    add_header(req, "Content-Type", "text/plain;charset=UTF-8");
10354    add_content(req, text);
10355    return 0;
10356 }
10357 
10358 /*! \brief Add DTMF INFO tone to sip message 
10359    Mode =   0 for application/dtmf-relay (Cisco)
10360       1 for application/dtmf
10361 */
10362 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode)
10363 {
10364    char tmp[256];
10365    int event;
10366    if (mode) {
10367       /* Application/dtmf short version used by some implementations */
10368       if (digit == '*')
10369          event = 10;
10370       else if (digit == '#')
10371          event = 11;
10372       else if ((digit >= 'A') && (digit <= 'D'))
10373          event = 12 + digit - 'A';
10374       else
10375          event = atoi(&digit);
10376       snprintf(tmp, sizeof(tmp), "%d\r\n", event);
10377       add_header(req, "Content-Type", "application/dtmf");
10378       add_content(req, tmp);
10379    } else {
10380       /* Application/dtmf-relay as documented by Cisco */
10381       snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
10382       add_header(req, "Content-Type", "application/dtmf-relay");
10383       add_content(req, tmp);
10384    }
10385    return 0;
10386 }
10387 
10388 /*! \brief add XML encoded media control with update 
10389    \note XML: The only way to turn 0 bits of information into a few hundred. (markster) */
10390 static int add_vidupdate(struct sip_request *req)
10391 {
10392    const char *xml_is_a_huge_waste_of_space =
10393       "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
10394       " <media_control>\r\n"
10395       "  <vc_primitive>\r\n"
10396       "   <to_encoder>\r\n"
10397       "    <picture_fast_update>\r\n"
10398       "    </picture_fast_update>\r\n"
10399       "   </to_encoder>\r\n"
10400       "  </vc_primitive>\r\n"
10401       " </media_control>\r\n";
10402    add_header(req, "Content-Type", "application/media_control+xml");
10403    add_content(req, xml_is_a_huge_waste_of_space);
10404    return 0;
10405 }
10406 
10407 /*! \brief Add codec offer to SDP offer/answer body in INVITE or 200 OK */
10408 static void add_codec_to_sdp(const struct sip_pvt *p, int codec,
10409               struct ast_str **m_buf, struct ast_str **a_buf,
10410               int debug, int *min_packet_size)
10411 {
10412    int rtp_code;
10413    struct ast_format_list fmt;
10414 
10415 
10416    if (debug)
10417       ast_verbose("Adding codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
10418    if ((rtp_code = ast_rtp_lookup_code(p->rtp, 1, codec)) == -1)
10419       return;
10420 
10421    if (p->rtp) {
10422       struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
10423       fmt = ast_codec_pref_getsize(pref, codec);
10424    } 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 */
10425       return;
10426    ast_str_append(m_buf, 0, " %d", rtp_code);
10427    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10428              ast_rtp_lookup_mime_subtype(1, codec,
10429                      ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
10430              ast_rtp_lookup_sample_rate(1, codec));
10431 
10432    switch (codec) {
10433    case AST_FORMAT_G729A:
10434       /* Indicate that we don't support VAD (G.729 annex B) */
10435       ast_str_append(a_buf, 0, "a=fmtp:%d annexb=no\r\n", rtp_code);
10436       break;
10437    case AST_FORMAT_G723_1:
10438       /* Indicate that we don't support VAD (G.723.1 annex A) */
10439       ast_str_append(a_buf, 0, "a=fmtp:%d annexa=no\r\n", rtp_code);
10440       break;
10441    case AST_FORMAT_ILBC:
10442       /* Add information about us using only 20/30 ms packetization */
10443       ast_str_append(a_buf, 0, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
10444       break;
10445    case AST_FORMAT_SIREN7:
10446       /* Indicate that we only expect 32Kbps */
10447       ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=32000\r\n", rtp_code);
10448       break;
10449    case AST_FORMAT_SIREN14:
10450       /* Indicate that we only expect 48Kbps */
10451       ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=48000\r\n", rtp_code);
10452       break;
10453    }
10454 
10455    if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
10456       *min_packet_size = fmt.cur_ms;
10457 
10458    /* Our first codec packetization processed cannot be zero */
10459    if ((*min_packet_size)==0 && fmt.cur_ms)
10460       *min_packet_size = fmt.cur_ms;
10461 }
10462 
10463 /*! \brief Add video codec offer to SDP offer/answer body in INVITE or 200 OK */
10464 /* This is different to the audio one now so we can add more caps later */
10465 static void add_vcodec_to_sdp(const struct sip_pvt *p, int codec,
10466               struct ast_str **m_buf, struct ast_str **a_buf,
10467               int debug, int *min_packet_size)
10468 {
10469    int rtp_code;
10470 
10471    if (!p->vrtp)
10472       return;
10473 
10474    if (debug)
10475       ast_verbose("Adding video codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
10476 
10477    if ((rtp_code = ast_rtp_lookup_code(p->vrtp, 1, codec)) == -1)
10478       return;
10479 
10480    ast_str_append(m_buf, 0, " %d", rtp_code);
10481    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10482              ast_rtp_lookup_mime_subtype(1, codec, 0),
10483              ast_rtp_lookup_sample_rate(1, codec));
10484    /* Add fmtp code here */
10485 }
10486 
10487 /*! \brief Add text codec offer to SDP offer/answer body in INVITE or 200 OK */
10488 static void add_tcodec_to_sdp(const struct sip_pvt *p, int codec,
10489               struct ast_str **m_buf, struct ast_str **a_buf,
10490               int debug, int *min_packet_size)
10491 {
10492    int rtp_code;
10493 
10494    if (!p->trtp)
10495       return;
10496 
10497    if (debug)
10498       ast_verbose("Adding text codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
10499 
10500    if ((rtp_code = ast_rtp_lookup_code(p->trtp, 1, codec)) == -1)
10501       return;
10502 
10503    ast_str_append(m_buf, 0, " %d", rtp_code);
10504    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10505              ast_rtp_lookup_mime_subtype(1, codec, 0),
10506              ast_rtp_lookup_sample_rate(1, codec));
10507    /* Add fmtp code here */
10508 
10509    if (codec == AST_FORMAT_T140RED) {
10510       ast_str_append(a_buf, 0, "a=fmtp:%d %d/%d/%d\r\n", rtp_code,
10511           ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140),
10512           ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140),
10513           ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140));
10514 
10515    }
10516 }
10517 
10518 
10519 /*! \brief Get Max T.38 Transmission rate from T38 capabilities */
10520 static unsigned int t38_get_rate(enum ast_control_t38_rate rate)
10521 {
10522    switch (rate) {
10523    case AST_T38_RATE_2400:
10524       return 2400;
10525    case AST_T38_RATE_4800:
10526       return 4800;
10527    case AST_T38_RATE_7200:
10528       return 7200;
10529    case AST_T38_RATE_9600:
10530       return 9600;
10531    case AST_T38_RATE_12000:
10532       return 12000;
10533    case AST_T38_RATE_14400:
10534       return 14400;
10535    default:
10536       return 0;
10537    }
10538 }
10539 
10540 /*! \brief Add RFC 2833 DTMF offer to SDP */
10541 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
10542             struct ast_str **m_buf, struct ast_str **a_buf,
10543             int debug)
10544 {
10545    int rtp_code;
10546 
10547    if (debug)
10548       ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype(0, format, 0));
10549    if ((rtp_code = ast_rtp_lookup_code(p->rtp, 0, format)) == -1)
10550       return;
10551 
10552    ast_str_append(m_buf, 0, " %d", rtp_code);
10553    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10554              ast_rtp_lookup_mime_subtype(0, format, 0),
10555              ast_rtp_lookup_sample_rate(0, format));
10556    if (format == AST_RTP_DTMF)   /* Indicate we support DTMF and FLASH... */
10557       ast_str_append(a_buf, 0, "a=fmtp:%d 0-16\r\n", rtp_code);
10558 }
10559 
10560 /*! \brief Set all IP media addresses for this call 
10561    \note called from add_sdp()
10562 */
10563 static void get_our_media_address(struct sip_pvt *p, int needvideo,
10564    struct sockaddr_in *sin, struct sockaddr_in *vsin, struct sockaddr_in *tsin,
10565    struct sockaddr_in *dest, struct sockaddr_in *vdest)
10566 {
10567    /* First, get our address */
10568    ast_rtp_get_us(p->rtp, sin);
10569    if (p->vrtp)
10570       ast_rtp_get_us(p->vrtp, vsin);
10571    if (p->trtp)
10572       ast_rtp_get_us(p->trtp, tsin);
10573 
10574    /* Now, try to figure out where we want them to send data */
10575    /* Is this a re-invite to move the media out, then use the original offer from caller  */
10576    if (p->redirip.sin_addr.s_addr) {   /* If we have a redirection IP, use it */
10577       dest->sin_port = p->redirip.sin_port;
10578       dest->sin_addr = p->redirip.sin_addr;
10579    } else {
10580       dest->sin_addr = p->ourip.sin_addr;
10581       dest->sin_port = sin->sin_port;
10582    }
10583    if (needvideo) {
10584       /* Determine video destination */
10585       if (p->vredirip.sin_addr.s_addr) {
10586          vdest->sin_addr = p->vredirip.sin_addr;
10587          vdest->sin_port = p->vredirip.sin_port;
10588       } else {
10589          vdest->sin_addr = p->ourip.sin_addr;
10590          vdest->sin_port = vsin->sin_port;
10591       }
10592    }
10593 
10594 }
10595 
10596 /*! \brief Add Session Description Protocol message 
10597 
10598     If oldsdp is TRUE, then the SDP version number is not incremented. This mechanism
10599     is used in Session-Timers where RE-INVITEs are used for refreshing SIP sessions 
10600     without modifying the media session in any way. 
10601 */
10602 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38)
10603 {
10604    int alreadysent = 0;
10605    int doing_directmedia = FALSE;
10606 
10607    struct sockaddr_in sin;
10608    struct sockaddr_in vsin;
10609    struct sockaddr_in tsin;
10610    struct sockaddr_in dest;
10611    struct sockaddr_in udptlsin;
10612    struct sockaddr_in vdest = { 0, };
10613    struct sockaddr_in tdest = { 0, };
10614    struct sockaddr_in udptldest = { 0, };
10615 
10616    /* SDP fields */
10617    char *version =   "v=0\r\n";     /* Protocol version */
10618    char subject[256];            /* Subject of the session */
10619    char owner[256];           /* Session owner/creator */
10620    char connection[256];            /* Connection data */
10621    char *session_time = "t=0 0\r\n";         /* Time the session is active */
10622    char bandwidth[256] = "";        /* Max bitrate */
10623    char *hold = "";
10624    struct ast_str *m_audio = ast_str_alloca(256);  /* Media declaration line for audio */
10625    struct ast_str *m_video = ast_str_alloca(256);  /* Media declaration line for video */
10626    struct ast_str *m_text = ast_str_alloca(256);   /* Media declaration line for text */
10627    struct ast_str *m_modem = ast_str_alloca(256);  /* Media declaration line for modem */
10628    struct ast_str *a_audio = ast_str_alloca(1024); /* Attributes for audio */
10629    struct ast_str *a_video = ast_str_alloca(1024); /* Attributes for video */
10630    struct ast_str *a_text = ast_str_alloca(1024);  /* Attributes for text */
10631    struct ast_str *a_modem = ast_str_alloca(1024); /* Attributes for modem */
10632 
10633    int x;
10634    int capability = 0;
10635    int needaudio = FALSE;
10636    int needvideo = FALSE;
10637    int needtext = FALSE;
10638    int debug = sip_debug_test_pvt(p);
10639    int min_audio_packet_size = 0;
10640    int min_video_packet_size = 0;
10641    int min_text_packet_size = 0;
10642 
10643    char codecbuf[SIPBUFSIZE];
10644    char buf[SIPBUFSIZE];
10645    char dummy_answer[256];
10646 
10647    /* Set the SDP session name */
10648    snprintf(subject, sizeof(subject), "s=%s\r\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
10649 
10650    if (!p->rtp) {
10651       ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
10652       return AST_FAILURE;
10653    }
10654    /* XXX We should not change properties in the SIP dialog until 
10655       we have acceptance of the offer if this is a re-invite */
10656 
10657    /* Set RTP Session ID and version */
10658    if (!p->sessionid) {
10659       p->sessionid = (int)ast_random();
10660       p->sessionversion = p->sessionid;
10661    } else {
10662       if (oldsdp == FALSE)
10663          p->sessionversion++;
10664    }
10665 
10666    if (add_audio) {
10667       doing_directmedia = (p->redirip.sin_addr.s_addr && p->redircodecs) ? TRUE : FALSE;
10668       /* Check if we need video in this call */
10669       if ((p->jointcapability & AST_FORMAT_VIDEO_MASK) && !p->novideo) {
10670          if (doing_directmedia && !(p->jointcapability & AST_FORMAT_VIDEO_MASK & p->redircodecs)) {
10671             ast_debug(2, "This call needs video offers, but caller probably did not offer it!\n");
10672          } else if (p->vrtp) {
10673             needvideo = TRUE;
10674             ast_debug(2, "This call needs video offers!\n");
10675          } else {
10676             ast_debug(2, "This call needs video offers, but there's no video support enabled!\n");
10677          }
10678       }
10679       /* Check if we need text in this call */
10680       if ((p->jointcapability & AST_FORMAT_TEXT_MASK) && !p->notext) {
10681          if (sipdebug_text)
10682             ast_verbose("We think we can do text\n");
10683          if (p->trtp) {
10684             if (sipdebug_text) {
10685                ast_verbose("And we have a text rtp object\n");
10686             }
10687             needtext = TRUE;
10688             ast_debug(2, "This call needs text offers! \n");
10689          } else {
10690             ast_debug(2, "This call needs text offers, but there's no text support enabled ! \n");
10691          }
10692       }
10693    }
10694 
10695    get_our_media_address(p, needvideo, &sin, &vsin, &tsin, &dest, &vdest);
10696 
10697    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));
10698    snprintf(connection, sizeof(connection), "c=IN IP4 %s\r\n", ast_inet_ntoa(dest.sin_addr));
10699 
10700    if (add_audio) {
10701       if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR) {
10702          hold = "a=recvonly\r\n";
10703          doing_directmedia = FALSE;
10704       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE) {
10705          hold = "a=inactive\r\n";
10706          doing_directmedia = FALSE;
10707       } else {
10708          hold = "a=sendrecv\r\n";
10709       }
10710 
10711       capability = p->jointcapability;
10712 
10713       /* XXX note, Video and Text are negated - 'true' means 'no' */
10714       ast_debug(1, "** Our capability: %s Video flag: %s Text flag: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability), 
10715            p->novideo ? "True" : "False", p->notext ? "True" : "False");
10716       ast_debug(1, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));
10717 
10718       if (doing_directmedia) {
10719          capability &= p->redircodecs;
10720          ast_debug(1, "** Our native-bridge filtered capablity: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability));
10721       }
10722 
10723       /* Check if we need audio */
10724       if (capability & AST_FORMAT_AUDIO_MASK)
10725          needaudio = TRUE;
10726 
10727       if (debug) 
10728          ast_verbose("Audio is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(sin.sin_port)); 
10729 
10730       /* Ok, we need video. Let's add what we need for video and set codecs.
10731          Video is handled differently than audio since we can not transcode. */
10732       if (needvideo) {
10733          ast_str_append(&m_video, 0, "m=video %d RTP/AVP", ntohs(vdest.sin_port));
10734 
10735          /* Build max bitrate string */
10736          if (p->maxcallbitrate)
10737             snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
10738          if (debug) 
10739             ast_verbose("Video is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(vdest.sin_port));  
10740       }
10741 
10742       /* Ok, we need text. Let's add what we need for text and set codecs.
10743          Text is handled differently than audio since we can not transcode. */
10744       if (needtext) {
10745          if (sipdebug_text)
10746             ast_verbose("Lets set up the text sdp\n");
10747          /* Determine text destination */
10748          if (p->tredirip.sin_addr.s_addr) {
10749             tdest.sin_addr = p->tredirip.sin_addr;
10750             tdest.sin_port = p->tredirip.sin_port;
10751          } else {
10752             tdest.sin_addr = p->ourip.sin_addr;
10753             tdest.sin_port = tsin.sin_port;
10754          }
10755          ast_str_append(&m_text, 0, "m=text %d RTP/AVP", ntohs(tdest.sin_port));
10756          if (debug) /* XXX should I use tdest below ? */
10757             ast_verbose("Text is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(tsin.sin_port)); 
10758 
10759       }
10760 
10761       /* Start building generic SDP headers */
10762 
10763       /* We break with the "recommendation" and send our IP, in order that our
10764          peer doesn't have to ast_gethostbyname() us */
10765 
10766       ast_str_append(&m_audio, 0, "m=audio %d RTP/AVP", ntohs(dest.sin_port));
10767 
10768       /* Now, start adding audio codecs. These are added in this order:
10769          - First what was requested by the calling channel
10770          - Then preferences in order from sip.conf device config for this peer/user
10771          - Then other codecs in capabilities, including video
10772       */
10773 
10774       /* Prefer the audio codec we were requested to use, first, no matter what 
10775          Note that p->prefcodec can include video codecs, so mask them out
10776       */
10777       if (capability & p->prefcodec) {
10778          int codec = p->prefcodec & AST_FORMAT_AUDIO_MASK;
10779 
10780          add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
10781          alreadysent |= codec;
10782       }
10783 
10784       /* Start by sending our preferred audio/video codecs */
10785       for (x = 0; x < 32; x++) {
10786          int codec;
10787 
10788          if (!(codec = ast_codec_pref_index(&p->prefs, x)))
10789             break; 
10790 
10791          if (!(capability & codec))
10792             continue;
10793 
10794          if (alreadysent & codec)
10795             continue;
10796 
10797          add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
10798          alreadysent |= codec;
10799       }
10800 
10801       /* Now send any other common audio and video codecs, and non-codec formats: */
10802       for (x = 1; x <= (needtext ? AST_FORMAT_TEXT_MASK : (needvideo ? AST_FORMAT_VIDEO_MASK : AST_FORMAT_AUDIO_MASK)); x <<= 1) {
10803          if (!(capability & x))  /* Codec not requested */
10804             continue;
10805 
10806          if (alreadysent & x) /* Already added to SDP */
10807             continue;
10808 
10809          if (x & AST_FORMAT_AUDIO_MASK)
10810             add_codec_to_sdp(p, x, &m_audio, &a_audio, debug, &min_audio_packet_size);
10811          else if (x & AST_FORMAT_VIDEO_MASK)
10812             add_vcodec_to_sdp(p, x, &m_video, &a_video, debug, &min_video_packet_size);
10813          else if (x & AST_FORMAT_TEXT_MASK)
10814             add_tcodec_to_sdp(p, x, &m_text, &a_text, debug, &min_text_packet_size);
10815       }
10816 
10817       /* Now add DTMF RFC2833 telephony-event as a codec */
10818       for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
10819          if (!(p->jointnoncodeccapability & x))
10820             continue;
10821 
10822          add_noncodec_to_sdp(p, x, &m_audio, &a_audio, debug);
10823       }
10824 
10825       ast_debug(3, "-- Done with adding codecs to SDP\n");
10826 
10827       if (!p->owner || !ast_internal_timing_enabled(p->owner))
10828          ast_str_append(&a_audio, 0, "a=silenceSupp:off - - - -\r\n");
10829 
10830       if (min_audio_packet_size)
10831          ast_str_append(&a_audio, 0, "a=ptime:%d\r\n", min_audio_packet_size);
10832 
10833       /* XXX don't think you can have ptime for video */
10834       if (min_video_packet_size)
10835          ast_str_append(&a_video, 0, "a=ptime:%d\r\n", min_video_packet_size);
10836 
10837       /* XXX don't think you can have ptime for text */
10838       if (min_text_packet_size)
10839          ast_str_append(&a_text, 0, "a=ptime:%d\r\n", min_text_packet_size);
10840  
10841       if (m_audio->len - m_audio->used < 2 || m_video->len - m_video->used < 2 ||
10842           m_text->len - m_text->used < 2 || a_text->len - a_text->used < 2 ||
10843           a_audio->len - a_audio->used < 2 || a_video->len - a_video->used < 2)
10844          ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
10845    }
10846 
10847    if (add_t38) {
10848       /* Our T.38 end is */
10849       ast_udptl_get_us(p->udptl, &udptlsin);
10850 
10851       /* Determine T.38 UDPTL destination */
10852       if (p->udptlredirip.sin_addr.s_addr) {
10853          udptldest.sin_port = p->udptlredirip.sin_port;
10854          udptldest.sin_addr = p->udptlredirip.sin_addr;
10855       } else {
10856          udptldest.sin_addr = p->ourip.sin_addr;
10857          udptldest.sin_port = udptlsin.sin_port;
10858       }
10859 
10860       if (debug)
10861          ast_debug(1, "T.38 UDPTL is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(udptlsin.sin_port));
10862 
10863       /* We break with the "recommendation" and send our IP, in order that our
10864          peer doesn't have to ast_gethostbyname() us */
10865 
10866       ast_str_append(&m_modem, 0, "m=image %d udptl t38\r\n", ntohs(udptldest.sin_port));
10867 
10868       ast_str_append(&a_modem, 0, "a=T38FaxVersion:%d\r\n", p->t38.our_parms.version);
10869       ast_str_append(&a_modem, 0, "a=T38MaxBitRate:%d\r\n", t38_get_rate(p->t38.our_parms.rate));
10870       if (p->t38.our_parms.fill_bit_removal) {
10871          ast_str_append(&a_modem, 0, "a=T38FaxFillBitRemoval\r\n");
10872       }
10873       if (p->t38.our_parms.transcoding_mmr) {
10874          ast_str_append(&a_modem, 0, "a=T38FaxTranscodingMMR\r\n");
10875       }
10876       if (p->t38.our_parms.transcoding_jbig) {
10877          ast_str_append(&a_modem, 0, "a=T38FaxTranscodingJBIG\r\n");
10878       }
10879       switch (p->t38.our_parms.rate_management) {
10880       case AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF:
10881          ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:transferredTCF\r\n");
10882          break;
10883       case AST_T38_RATE_MANAGEMENT_LOCAL_TCF:
10884          ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:localTCF\r\n");
10885          break;
10886       }
10887       ast_str_append(&a_modem, 0, "a=T38FaxMaxDatagram:%u\r\n", ast_udptl_get_local_max_datagram(p->udptl));
10888       switch (ast_udptl_get_error_correction_scheme(p->udptl)) {
10889       case UDPTL_ERROR_CORRECTION_NONE:
10890          break;
10891       case UDPTL_ERROR_CORRECTION_FEC:
10892          ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPFEC\r\n");
10893          break;
10894       case UDPTL_ERROR_CORRECTION_REDUNDANCY:
10895          ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPRedundancy\r\n");
10896          break;
10897       }
10898    }
10899 
10900    if (needaudio)
10901       ast_str_append(&m_audio, 0, "\r\n");
10902    if (needvideo)
10903       ast_str_append(&m_video, 0, "\r\n");
10904    if (needtext)
10905       ast_str_append(&m_text, 0, "\r\n");
10906 
10907    add_header(resp, "Content-Type", "application/sdp");
10908    add_content(resp, version);
10909    add_content(resp, owner);
10910    add_content(resp, subject);
10911    add_content(resp, connection);
10912    if (needvideo)    /* only if video response is appropriate */
10913       add_content(resp, bandwidth);
10914    add_content(resp, session_time);
10915    if (needaudio) {
10916       add_content(resp, m_audio->str);
10917       add_content(resp, a_audio->str);
10918       add_content(resp, hold);
10919    } else if (p->offered_media[SDP_AUDIO].offered) {
10920       snprintf(dummy_answer, sizeof(dummy_answer), "m=audio 0 RTP/AVP %s\r\n", p->offered_media[SDP_AUDIO].text);
10921       add_content(resp, dummy_answer);
10922    }
10923    if (needvideo) { /* only if video response is appropriate */
10924       add_content(resp, m_video->str);
10925       add_content(resp, a_video->str);
10926       add_content(resp, hold);   /* Repeat hold for the video stream */
10927    } else if (p->offered_media[SDP_VIDEO].offered) {
10928       snprintf(dummy_answer, sizeof(dummy_answer), "m=video 0 RTP/AVP %s\r\n", p->offered_media[SDP_VIDEO].text);
10929       add_content(resp, dummy_answer);
10930    }
10931    if (needtext) { /* only if text response is appropriate */
10932       add_content(resp, m_text->str);
10933       add_content(resp, a_text->str);
10934       add_content(resp, hold);   /* Repeat hold for the text stream */
10935    } else if (p->offered_media[SDP_TEXT].offered) {
10936       snprintf(dummy_answer, sizeof(dummy_answer), "m=text 0 RTP/AVP %s\r\n", p->offered_media[SDP_TEXT].text);
10937       add_content(resp, dummy_answer);
10938    }
10939    if (add_t38) {
10940       add_content(resp, m_modem->str);
10941       add_content(resp, a_modem->str);
10942    } else if (p->offered_media[SDP_IMAGE].offered) {
10943       add_content(resp, "m=image 0 udptl t38\r\n");
10944    }
10945 
10946    /* Update lastrtprx when we send our SDP */
10947    p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
10948 
10949    ast_debug(3, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, capability));
10950 
10951    return AST_SUCCESS;
10952 }
10953 
10954 /*! \brief Used for 200 OK and 183 early media */
10955 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
10956 {
10957    struct sip_request resp;
10958    int seqno;
10959    
10960    if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
10961       ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
10962       return -1;
10963    }
10964    respprep(&resp, p, msg, req);
10965    if (p->udptl) {
10966       add_sdp(&resp, p, 0, 0, 1);
10967    } else 
10968       ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
10969    if (retrans && !p->pendinginvite)
10970       p->pendinginvite = seqno;     /* Buggy clients sends ACK on RINGING too */
10971    return send_response(p, &resp, retrans, seqno);
10972 }
10973 
10974 /*! \brief copy SIP request (mostly used to save request for responses) */
10975 static void copy_request(struct sip_request *dst, const struct sip_request *src)
10976 {
10977    /* XXX this function can encounter memory allocation errors, perhaps it
10978     * should return a value */
10979 
10980    struct ast_str *duplicate = dst->data;
10981    struct ast_str *duplicate_content = dst->content;
10982 
10983    /* copy the entire request then restore the original data and content
10984     * members from the dst request */
10985    memcpy(dst, src, sizeof(*dst));
10986    dst->data = duplicate;
10987    dst->content = duplicate_content;
10988 
10989    /* copy the data into the dst request */
10990    if (!dst->data && !(dst->data = ast_str_create(ast_str_strlen(src->data) + 1)))
10991       return;
10992    ast_str_copy_string(&dst->data, src->data);
10993 
10994    /* copy the content into the dst request (if it exists) */
10995    if (src->content) {
10996       if (!dst->content && !(dst->content = ast_str_create(ast_str_strlen(src->content) + 1)))
10997          return;
10998       ast_str_copy_string(&dst->content, src->content);
10999    }
11000 }
11001 
11002 /*! \brief Used for 200 OK and 183 early media 
11003    \return Will return XMIT_ERROR for network errors.
11004 */
11005 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp)
11006 {
11007    struct sip_request resp;
11008    int seqno;
11009    if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
11010       ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
11011       return -1;
11012    }
11013    respprep(&resp, p, msg, req);
11014    if (p->rtp) {
11015       if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
11016          ast_debug(1, "Setting framing from config on incoming call\n");
11017          ast_rtp_codec_setpref(p->rtp, &p->prefs);
11018       }
11019       try_suggested_sip_codec(p);
11020       if (p->t38.state == T38_ENABLED) {
11021          add_sdp(&resp, p, oldsdp, TRUE, TRUE);
11022       } else {
11023          add_sdp(&resp, p, oldsdp, TRUE, FALSE);
11024       }
11025    } else 
11026       ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
11027    if (reliable && !p->pendinginvite)
11028       p->pendinginvite = seqno;     /* Buggy clients sends ACK on RINGING too */
11029    return send_response(p, &resp, reliable, seqno);
11030 }
11031 
11032 /*! \brief Parse first line of incoming SIP request */
11033 static int determine_firstline_parts(struct sip_request *req) 
11034 {
11035    char *e = ast_skip_blanks(req->data->str);   /* there shouldn't be any */
11036    char *local_rlPart1;
11037 
11038    if (!*e)
11039       return -1;
11040    req->rlPart1 = e - req->data->str;  /* method or protocol */
11041    local_rlPart1 = e;
11042    e = ast_skip_nonblanks(e);
11043    if (*e)
11044       *e++ = '\0';
11045    /* Get URI or status code */
11046    e = ast_skip_blanks(e);
11047    if ( !*e )
11048       return -1;
11049    ast_trim_blanks(e);
11050 
11051    if (!strcasecmp(local_rlPart1, "SIP/2.0") ) { /* We have a response */
11052       if (strlen(e) < 3)   /* status code is 3 digits */
11053          return -1;
11054       req->rlPart2 = e - req->data->str;
11055    } else { /* We have a request */
11056       if ( *e == '<' ) { /* XXX the spec says it must not be in <> ! */
11057          ast_debug(3, "Oops. Bogus uri in <> %s\n", e);
11058          e++;
11059          if (!*e)
11060             return -1; 
11061       }
11062       req->rlPart2 = e - req->data->str;  /* URI */
11063       e = ast_skip_nonblanks(e);
11064       if (*e)
11065          *e++ = '\0';
11066       e = ast_skip_blanks(e);
11067       if (strcasecmp(e, "SIP/2.0") ) {
11068          ast_debug(3, "Skipping packet - Bad request protocol %s\n", e);
11069          return -1;
11070       }
11071    }
11072    return 1;
11073 }
11074 
11075 /*! \brief Transmit reinvite with SDP
11076 \note    A re-invite is basically a new INVITE with the same CALL-ID and TAG as the
11077    INVITE that opened the SIP dialogue 
11078    We reinvite so that the audio stream (RTP) go directly between
11079    the SIP UAs. SIP Signalling stays with * in the path.
11080    
11081    If t38version is TRUE, we send T38 SDP for re-invite from audio/video to
11082    T38 UDPTL transmission on the channel
11083 
11084     If oldsdp is TRUE then the SDP version number is not incremented. This
11085     is needed for Session-Timers so we can send a re-invite to refresh the
11086     SIP session without modifying the media session. 
11087 */
11088 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp)
11089 {
11090    struct sip_request req;
11091    
11092    reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ?  SIP_UPDATE : SIP_INVITE, 0, 1);
11093 
11094    add_header(&req, "Allow", ALLOWED_METHODS);
11095    add_supported_header(p, &req);
11096    if (sipdebug) {
11097       if (oldsdp == TRUE)
11098          add_header(&req, "X-asterisk-Info", "SIP re-invite (Session-Timers)");
11099       else
11100          add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
11101    }
11102 
11103    if (p->do_history)
11104       append_history(p, "ReInv", "Re-invite sent");
11105    memset(p->offered_media, 0, sizeof(p->offered_media));
11106 
11107    if (t38version)
11108       add_sdp(&req, p, oldsdp, FALSE, TRUE);
11109    else
11110       add_sdp(&req, p, oldsdp, TRUE, FALSE);
11111 
11112    /* Use this as the basis */
11113    initialize_initreq(p, &req);
11114    p->lastinvite = p->ocseq;
11115    ast_set_flag(&p->flags[0], SIP_OUTGOING);       /* Change direction of this dialog */
11116 
11117    return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
11118 }
11119 
11120 /* \brief Remove URI parameters at end of URI, not in username part though */
11121 static char *remove_uri_parameters(char *uri)
11122 {
11123    char *atsign;
11124    atsign = strchr(uri, '@'); /* First, locate the at sign */
11125    if (!atsign)
11126       atsign = uri;  /* Ok hostname only, let's stick with the rest */
11127    atsign = strchr(atsign, ';'); /* Locate semi colon */
11128    if (atsign)
11129       *atsign = '\0';   /* Kill at the semi colon */
11130    return uri;
11131 }
11132 
11133 /*! \brief Check Contact: URI of SIP message */
11134 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
11135 {
11136    char stripped[SIPBUFSIZE];
11137    char *c;
11138 
11139    ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
11140    c = get_in_brackets(stripped);
11141    /* Cut the URI at the at sign after the @, not in the username part */
11142    c = remove_uri_parameters(c);
11143    if (!ast_strlen_zero(c))
11144       ast_string_field_set(p, uri, c);
11145 
11146 }
11147 
11148 /*! \brief Build contact header - the contact header we send out */
11149 static void build_contact(struct sip_pvt *p)
11150 {
11151    char tmp[SIPBUFSIZE];
11152    char *user = ast_uri_encode(p->exten, tmp, sizeof(tmp), 1);
11153    int ourport = ntohs(p->ourip.sin_port);
11154 
11155    /* only add port if it's non-standard for the transport type */
11156    if (!sip_standard_port(p->socket.type, ourport)) {
11157       if (p->socket.type == SIP_TRANSPORT_UDP)
11158          ast_string_field_build(p, our_contact, "<sip:%s%s%s:%d>", user, ast_strlen_zero(user) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr), ourport);
11159       else
11160          ast_string_field_build(p, our_contact, "<sip:%s%s%s:%d;transport=%s>", user, ast_strlen_zero(user) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr), ourport, get_transport(p->socket.type));
11161    } else {
11162       if (p->socket.type == SIP_TRANSPORT_UDP)
11163          ast_string_field_build(p, our_contact, "<sip:%s%s%s>", user, ast_strlen_zero(user) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr));
11164       else
11165          ast_string_field_build(p, our_contact, "<sip:%s%s%s;transport=%s>", user, ast_strlen_zero(user) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr), get_transport(p->socket.type));
11166    }
11167 }
11168 
11169 /*! \brief Build the Remote Party-ID & From using callingpres options */
11170 static void build_rpid(struct sip_pvt *p)
11171 {
11172    int send_pres_tags = TRUE;
11173    const char *privacy=NULL;
11174    const char *screen=NULL;
11175    char buf[256];
11176    const char *clid = default_callerid;
11177    const char *clin = NULL;
11178    const char *fromdomain;
11179 
11180    if (!ast_strlen_zero(p->rpid) || !ast_strlen_zero(p->rpid_from))  
11181       return;
11182 
11183    if (p->owner && !ast_strlen_zero(p->owner->cid.cid_num))
11184       clid = p->owner->cid.cid_num;
11185    if (p->owner && p->owner->cid.cid_name)
11186       clin = p->owner->cid.cid_name;
11187    if (ast_strlen_zero(clin))
11188       clin = clid;
11189 
11190    switch (p->callingpres) {
11191    case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
11192       privacy = "off";
11193       screen = "no";
11194       break;
11195    case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
11196       privacy = "off";
11197       screen = "yes";
11198       break;
11199    case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
11200       privacy = "off";
11201       screen = "no";
11202       break;
11203    case AST_PRES_ALLOWED_NETWORK_NUMBER:
11204       privacy = "off";
11205       screen = "yes";
11206       break;
11207    case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
11208       privacy = "full";
11209       screen = "no";
11210       break;
11211    case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
11212       privacy = "full";
11213       screen = "yes";
11214       break;
11215    case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
11216       privacy = "full";
11217       screen = "no";
11218       break;
11219    case AST_PRES_PROHIB_NETWORK_NUMBER:
11220       privacy = "full";
11221       screen = "yes";
11222       break;
11223    case AST_PRES_NUMBER_NOT_AVAILABLE:
11224       send_pres_tags = FALSE;
11225       break;
11226    default:
11227       ast_log(LOG_WARNING, "Unsupported callingpres (%d)\n", p->callingpres);
11228       if ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)
11229          privacy = "full";
11230       else
11231          privacy = "off";
11232       screen = "no";
11233       break;
11234    }
11235    
11236    fromdomain = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr));
11237 
11238    snprintf(buf, sizeof(buf), "\"%s\" <sip:%s@%s>", clin, clid, fromdomain);
11239    if (send_pres_tags)
11240       snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ";privacy=%s;screen=%s", privacy, screen);
11241    ast_string_field_set(p, rpid, buf);
11242 
11243    ast_string_field_build(p, rpid_from, "\"%s\" <sip:%s@%s>;tag=%s", clin,
11244                 S_OR(p->fromuser, clid),
11245                 fromdomain, p->tag);
11246 }
11247 
11248 /*! \brief Initiate new SIP request to peer/user */
11249 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod)
11250 {
11251    struct ast_str *invite = ast_str_alloca(256);
11252    char from[256];
11253    char to[256];
11254    char tmp_n[SIPBUFSIZE/2];  /* build a local copy of 'n' if needed */
11255    char tmp_l[SIPBUFSIZE/2];  /* build a local copy of 'l' if needed */
11256    const char *l = NULL;   /* XXX what is this, exactly ? */
11257    const char *n = NULL;   /* XXX what is this, exactly ? */
11258    const char *d = NULL;   /* domain in from header */
11259    const char *urioptions = "";
11260    int ourport;
11261 
11262    if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
11263       const char *s = p->username;  /* being a string field, cannot be NULL */
11264 
11265       /* Test p->username against allowed characters in AST_DIGIT_ANY
11266          If it matches the allowed characters list, then sipuser = ";user=phone"
11267          If not, then sipuser = ""
11268       */
11269       /* + is allowed in first position in a tel: uri */
11270       if (*s == '+')
11271          s++;
11272       for (; *s; s++) {
11273          if (!strchr(AST_DIGIT_ANYNUM, *s) )
11274             break;
11275       }
11276       /* If we have only digits, add ;user=phone to the uri */
11277       if (!*s)
11278          urioptions = ";user=phone";
11279    }
11280 
11281 
11282    snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
11283 
11284    d = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr));
11285    if (p->owner) {
11286       l = p->owner->cid.cid_num;
11287       n = p->owner->cid.cid_name;
11288    }
11289    /* if we are not sending RPID and user wants his callerid restricted */
11290    if (!ast_test_flag(&p->flags[0], SIP_SENDRPID) &&
11291        ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)) {
11292       l = CALLERID_UNKNOWN;
11293       n = l;
11294       d = FROMDOMAIN_INVALID;
11295    }
11296    if (ast_strlen_zero(l))
11297       l = default_callerid;
11298    if (ast_strlen_zero(n))
11299       n = l;
11300    /* Allow user to be overridden */
11301    if (!ast_strlen_zero(p->fromuser))
11302       l = p->fromuser;
11303    else /* Save for any further attempts */
11304       ast_string_field_set(p, fromuser, l);
11305 
11306    /* Allow user to be overridden */
11307    if (!ast_strlen_zero(p->fromname))
11308       n = p->fromname;
11309    else /* Save for any further attempts */
11310       ast_string_field_set(p, fromname, n);
11311 
11312    if (sip_cfg.pedanticsipchecking) {
11313       ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
11314       n = tmp_n;
11315       ast_uri_encode(l, tmp_l, sizeof(tmp_l), 0);
11316       l = tmp_l;
11317    }
11318 
11319    ourport = ntohs(p->ourip.sin_port);
11320    if (!sip_standard_port(p->socket.type, ourport) && ast_strlen_zero(p->fromdomain))
11321       snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=%s", n, l, d, ourport, p->tag);
11322    else
11323       snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, l, d, p->tag);
11324 
11325    /* If we're calling a registered SIP peer, use the fullcontact to dial to the peer */
11326    if (!ast_strlen_zero(p->fullcontact)) {
11327       /* If we have full contact, trust it */
11328       ast_str_append(&invite, 0, "%s", p->fullcontact);
11329    } else {
11330       /* Otherwise, use the username while waiting for registration */
11331       ast_str_append(&invite, 0, "sip:");
11332       if (!ast_strlen_zero(p->username)) {
11333          n = p->username;
11334          if (sip_cfg.pedanticsipchecking) {
11335             ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
11336             n = tmp_n;
11337          }
11338          ast_str_append(&invite, 0, "%s@", n);
11339       }
11340       ast_str_append(&invite, 0, "%s", p->tohost);
11341       if (p->portinuri)
11342          ast_str_append(&invite, 0, ":%d", ntohs(p->sa.sin_port));
11343       ast_str_append(&invite, 0, "%s", urioptions);
11344    }
11345 
11346    /* If custom URI options have been provided, append them */
11347    if (p->options && !ast_strlen_zero(p->options->uri_options))
11348       ast_str_append(&invite, 0, ";%s", p->options->uri_options);
11349    
11350    /* This is the request URI, which is the next hop of the call
11351       which may or may not be the destination of the call
11352    */
11353    ast_string_field_set(p, uri, invite->str);
11354   
11355    if (!ast_strlen_zero(p->todnid)) {
11356       /*! \todo Need to add back the VXML URL here at some point, possibly use build_string for all this junk */
11357       if (!strchr(p->todnid, '@')) {
11358          /* We have no domain in the dnid */
11359          snprintf(to, sizeof(to), "<sip:%s@%s>%s%s", p->todnid, p->tohost, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
11360       } else {
11361          snprintf(to, sizeof(to), "<sip:%s>%s%s", p->todnid, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
11362       }
11363    } else {
11364       if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) { 
11365          /* If this is a NOTIFY, use the From: tag in the subscribe (RFC 3265) */
11366          snprintf(to, sizeof(to), "<%s%s>;tag=%s", (strncasecmp(p->uri, "sip:", 4) ? "sip:" : ""), p->uri, p->theirtag);
11367       } else if (p->options && p->options->vxml_url) {
11368          /* If there is a VXML URL append it to the SIP URL */
11369          snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
11370       } else 
11371          snprintf(to, sizeof(to), "<%s>", p->uri);
11372    }
11373 
11374    init_req(req, sipmethod, p->uri);
11375    /* now tmp_n is available so reuse it to build the CSeq */
11376    snprintf(tmp_n, sizeof(tmp_n), "%d %s", ++p->ocseq, sip_methods[sipmethod].text);
11377 
11378    add_header(req, "Via", p->via);
11379    add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
11380    /* This will be a no-op most of the time. However, under certain circumstances,
11381     * NOTIFY messages will use this function for preparing the request and should
11382     * have Route headers present.
11383     */
11384    add_route(req, p->route);
11385 
11386    /* Build Remote Party-ID and From */
11387    if (ast_test_flag(&p->flags[0], SIP_SENDRPID) && (sipmethod == SIP_INVITE)) {
11388       build_rpid(p);
11389       add_header(req, "From", p->rpid_from);
11390    } else 
11391       add_header(req, "From", from);
11392    add_header(req, "To", to);
11393    ast_string_field_set(p, exten, l);
11394    build_contact(p);
11395    add_header(req, "Contact", p->our_contact);
11396    add_header(req, "Call-ID", p->callid);
11397    add_header(req, "CSeq", tmp_n);
11398    if (!ast_strlen_zero(global_useragent))
11399       add_header(req, "User-Agent", global_useragent);
11400    if (!ast_strlen_zero(p->rpid))
11401       add_header(req, "Remote-Party-ID", p->rpid);
11402 }
11403 
11404 /*! \brief Build REFER/INVITE/OPTIONS/SUBSCRIBE message and transmit it 
11405    \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
11406  \param p sip_pvt structure
11407  \param sdp unknown 
11408  \param sipmethod unknown 
11409  
11410 */
11411 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init)
11412 {
11413    struct sip_request req;
11414    struct ast_variable *var;
11415    
11416    req.method = sipmethod;
11417    if (init) {/* Bump branch even on initial requests */
11418       p->branch ^= ast_random();
11419       p->invite_branch = p->branch;
11420       build_via(p);
11421    }
11422    if (init > 1)
11423       initreqprep(&req, p, sipmethod);
11424    else
11425       /* If init=1, we should not generate a new branch. If it's 0, we need a new branch. */
11426       reqprep(&req, p, sipmethod, 0, init ? 0 : 1);
11427       
11428    if (p->options && p->options->auth)
11429       add_header(&req, p->options->authheader, p->options->auth);
11430    append_date(&req);
11431    if (sipmethod == SIP_REFER) { /* Call transfer */
11432       if (p->refer) {
11433          char buf[SIPBUFSIZE];
11434          if (!ast_strlen_zero(p->refer->refer_to))
11435             add_header(&req, "Refer-To", p->refer->refer_to);
11436          if (!ast_strlen_zero(p->refer->referred_by)) {
11437             snprintf(buf, sizeof(buf), "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
11438             add_header(&req, "Referred-By", buf);
11439          }
11440       }
11441    } else if (sipmethod == SIP_SUBSCRIBE) { /* We only support sending MWI subscriptions right now */
11442       char buf[SIPBUFSIZE];
11443 
11444       add_header(&req, "Event", "message-summary");
11445       add_header(&req, "Accept", "application/simple-message-summary");
11446       snprintf(buf, sizeof(buf), "%d", mwi_expiry);
11447       add_header(&req, "Expires", buf);
11448    }
11449 
11450    /* This new INVITE is part of an attended transfer. Make sure that the
11451    other end knows and replace the current call with this new call */
11452    if (p->options && !ast_strlen_zero(p->options->replaces)) {
11453       add_header(&req, "Replaces", p->options->replaces);
11454       add_header(&req, "Require", "replaces");
11455    }
11456 
11457    /* Add Session-Timers related headers */
11458    if (st_get_mode(p, 0) == SESSION_TIMER_MODE_ORIGINATE) {
11459       char i2astr[10];
11460 
11461       if (!p->stimer->st_interval)
11462          p->stimer->st_interval = st_get_se(p, TRUE);
11463 
11464       p->stimer->st_active = TRUE;
11465       
11466       snprintf(i2astr, sizeof(i2astr), "%d", p->stimer->st_interval);
11467       add_header(&req, "Session-Expires", i2astr);
11468       snprintf(i2astr, sizeof(i2astr), "%d", st_get_se(p, FALSE));
11469       add_header(&req, "Min-SE", i2astr);
11470    }
11471 
11472    add_header(&req, "Allow", ALLOWED_METHODS);
11473    add_supported_header(p, &req);
11474 
11475    if(p->notify_headers) {
11476       char buf[512];
11477       for (var = p->notify_headers; var; var = var->next) {
11478          ast_copy_string(buf, var->value, sizeof(buf));
11479          add_header(&req, var->name, ast_unescape_semicolon(buf));
11480       }
11481    }
11482    if (p->options && p->options->addsipheaders && p->owner) {
11483       struct ast_channel *chan = p->owner; /* The owner channel */
11484       struct varshead *headp;
11485    
11486       ast_channel_lock(chan);
11487 
11488       headp = &chan->varshead;
11489 
11490       if (!headp)
11491          ast_log(LOG_WARNING, "No Headp for the channel...ooops!\n");
11492       else {
11493          const struct ast_var_t *current;
11494          AST_LIST_TRAVERSE(headp, current, entries) {  
11495             /* SIPADDHEADER: Add SIP header to outgoing call */
11496             if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
11497                char *content, *end;
11498                const char *header = ast_var_value(current);
11499                char *headdup = ast_strdupa(header);
11500 
11501                /* Strip of the starting " (if it's there) */
11502                if (*headdup == '"')
11503                   headdup++;
11504                if ((content = strchr(headdup, ':'))) {
11505                   *content++ = '\0';
11506                   content = ast_skip_blanks(content); /* Skip white space */
11507                   /* Strip the ending " (if it's there) */
11508                   end = content + strlen(content) -1; 
11509                   if (*end == '"')
11510                      *end = '\0';
11511                
11512                   add_header(&req, headdup, content);
11513                   if (sipdebug)
11514                      ast_debug(1, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
11515                }
11516             }
11517          }
11518       }
11519 
11520       ast_channel_unlock(chan);
11521    }
11522    if (sdp) {
11523       memset(p->offered_media, 0, sizeof(p->offered_media));
11524       if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
11525          ast_debug(1, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
11526          add_sdp(&req, p, FALSE, FALSE, TRUE);
11527       } else if (p->rtp) 
11528          add_sdp(&req, p, FALSE, TRUE, FALSE);
11529    }
11530 
11531    if (!p->initreq.headers || init > 2)
11532       initialize_initreq(p, &req);
11533    p->lastinvite = p->ocseq;
11534    return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
11535 }
11536 
11537 /*! \brief Send a subscription or resubscription for MWI */
11538 static int sip_subscribe_mwi_do(const void *data)
11539 {
11540    struct sip_subscription_mwi *mwi = (struct sip_subscription_mwi*)data;
11541    
11542    if (!mwi) {
11543       return -1;
11544    }
11545    
11546    mwi->resub = -1;
11547    __sip_subscribe_mwi_do(mwi);
11548    ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
11549    
11550    return 0;
11551 }
11552 
11553 /*! \brief Actually setup an MWI subscription or resubscribe */
11554 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi)
11555 {
11556    /* If we have no DNS manager let's do a lookup */
11557    if (!mwi->dnsmgr) {
11558       char transport[MAXHOSTNAMELEN];
11559       snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(mwi->transport), get_srv_protocol(mwi->transport));
11560       ast_dnsmgr_lookup(mwi->hostname, &mwi->us, &mwi->dnsmgr, sip_cfg.srvlookup ? transport : NULL);
11561    }
11562 
11563    /* If we already have a subscription up simply send a resubscription */
11564    if (mwi->call) {
11565       transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 0);
11566       return 0;
11567    }
11568    
11569    /* Create a dialog that we will use for the subscription */
11570    if (!(mwi->call = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
11571       return -1;
11572    }
11573 
11574    ref_proxy(mwi->call, obproxy_get(mwi->call, NULL));
11575 
11576    if (!mwi->us.sin_port && mwi->portno) {
11577       mwi->us.sin_port = htons(mwi->portno);
11578    }
11579    
11580    /* Setup the destination of our subscription */
11581    if (create_addr(mwi->call, mwi->hostname, &mwi->us, 0)) {
11582       dialog_unlink_all(mwi->call, TRUE, TRUE);
11583       mwi->call = dialog_unref(mwi->call, "unref dialog after unlink_all");
11584       return 0;
11585    }
11586    
11587    if (!mwi->dnsmgr && mwi->portno) {
11588       mwi->call->sa.sin_port = htons(mwi->portno);
11589       mwi->call->recv.sin_port = htons(mwi->portno);
11590    } else {
11591       mwi->portno = ntohs(mwi->call->sa.sin_port);
11592    }
11593    
11594    /* Set various other information */
11595    if (!ast_strlen_zero(mwi->authuser)) {
11596       ast_string_field_set(mwi->call, peername, mwi->authuser);
11597       ast_string_field_set(mwi->call, authname, mwi->authuser);
11598       ast_string_field_set(mwi->call, fromuser, mwi->authuser);
11599    } else {
11600       ast_string_field_set(mwi->call, peername, mwi->username);
11601       ast_string_field_set(mwi->call, authname, mwi->username);
11602       ast_string_field_set(mwi->call, fromuser, mwi->username);
11603    }
11604    ast_string_field_set(mwi->call, username, mwi->username);
11605    if (!ast_strlen_zero(mwi->secret)) {
11606       ast_string_field_set(mwi->call, peersecret, mwi->secret);
11607    }
11608    set_socket_transport(&mwi->call->socket, mwi->transport);
11609    mwi->call->socket.port = htons(mwi->portno);
11610    ast_sip_ouraddrfor(&mwi->call->sa.sin_addr, &mwi->call->ourip, mwi->call);
11611    build_contact(mwi->call);
11612    build_via(mwi->call);
11613    build_callid_pvt(mwi->call);
11614    ast_set_flag(&mwi->call->flags[0], SIP_OUTGOING);
11615    
11616    /* Associate the call with us */
11617    mwi->call->mwi = ASTOBJ_REF(mwi);
11618    
11619    /* Actually send the packet */
11620    transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 2);
11621 
11622    return 0;
11623 }
11624 
11625 static int find_calling_channel(struct ast_channel *c, void *data) {
11626    struct sip_pvt *p = data;
11627 
11628    return (c->pbx &&
11629          (!strcasecmp(c->macroexten, p->exten) || !strcasecmp(c->exten, p->exten)) &&
11630          (sip_cfg.notifycid == IGNORE_CONTEXT || !strcasecmp(c->context, p->context)));
11631 }
11632 
11633 /*! \brief Used in the SUBSCRIBE notification subsystem (RFC3265) */
11634 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
11635 {
11636    struct ast_str *tmp = ast_str_alloca(4000);
11637    char from[256], to[256];
11638    char *c, *mfrom, *mto;
11639    struct sip_request req;
11640    char hint[AST_MAX_EXTENSION];
11641    char *statestring = "terminated";
11642    const struct cfsubscription_types *subscriptiontype;
11643    enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
11644    char *pidfstate = "--";
11645    char *pidfnote= "Ready";
11646    
11647    memset(from, 0, sizeof(from));
11648    memset(to, 0, sizeof(to));
11649 
11650    switch (state) {
11651    case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
11652       statestring = (sip_cfg.notifyringing) ? "early" : "confirmed";
11653       local_state = NOTIFY_INUSE;
11654       pidfstate = "busy";
11655       pidfnote = "Ringing";
11656       break;
11657    case AST_EXTENSION_RINGING:
11658       statestring = "early";
11659       local_state = NOTIFY_INUSE;
11660       pidfstate = "busy";
11661       pidfnote = "Ringing";
11662       break;
11663    case AST_EXTENSION_INUSE:
11664       statestring = "confirmed";
11665       local_state = NOTIFY_INUSE;
11666       pidfstate = "busy";
11667       pidfnote = "On the phone";
11668       break;
11669    case AST_EXTENSION_BUSY:
11670       statestring = "confirmed";
11671       local_state = NOTIFY_CLOSED;
11672       pidfstate = "busy";
11673       pidfnote = "On the phone";
11674       break;
11675    case AST_EXTENSION_UNAVAILABLE:
11676       statestring = "terminated";
11677       local_state = NOTIFY_CLOSED;
11678       pidfstate = "away";
11679       pidfnote = "Unavailable";
11680       break;
11681    case AST_EXTENSION_ONHOLD:
11682       statestring = "confirmed";
11683       local_state = NOTIFY_CLOSED;
11684       pidfstate = "busy";
11685       pidfnote = "On hold";
11686       break;
11687    case AST_EXTENSION_NOT_INUSE:
11688    default:
11689       /* Default setting */
11690       break;
11691    }
11692 
11693    subscriptiontype = find_subscription_type(p->subscribed);
11694    
11695    /* Check which device/devices we are watching  and if they are registered */
11696    if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten)) {
11697       char *hint2 = hint, *individual_hint = NULL;
11698       int hint_count = 0, unavailable_count = 0;
11699 
11700       while ((individual_hint = strsep(&hint2, "&"))) {
11701          hint_count++;
11702 
11703          if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
11704             unavailable_count++;
11705       }
11706 
11707       /* If none of the hinted devices are registered, we will
11708        * override notification and show no availability.
11709        */
11710       if (hint_count > 0 && hint_count == unavailable_count) {
11711          local_state = NOTIFY_CLOSED;
11712          pidfstate = "away";
11713          pidfnote = "Not online";
11714       }
11715    }
11716 
11717    ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
11718    c = get_in_brackets(from);
11719    if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
11720       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
11721       return -1;
11722    }
11723    
11724    mfrom = remove_uri_parameters(c);
11725 
11726    ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
11727    c = get_in_brackets(to);
11728    if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
11729       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
11730       return -1;
11731    }
11732    mto = remove_uri_parameters(c);
11733 
11734    reqprep(&req, p, SIP_NOTIFY, 0, 1);
11735 
11736    
11737    add_header(&req, "Event", subscriptiontype->event);
11738    add_header(&req, "Content-Type", subscriptiontype->mediatype);
11739    switch(state) {
11740    case AST_EXTENSION_DEACTIVATED:
11741       if (timeout)
11742          add_header(&req, "Subscription-State", "terminated;reason=timeout");
11743       else {
11744          add_header(&req, "Subscription-State", "terminated;reason=probation");
11745          add_header(&req, "Retry-After", "60");
11746       }
11747       break;
11748    case AST_EXTENSION_REMOVED:
11749       add_header(&req, "Subscription-State", "terminated;reason=noresource");
11750       break;
11751    default:
11752       if (p->expiry)
11753          add_header(&req, "Subscription-State", "active");
11754       else  /* Expired */
11755          add_header(&req, "Subscription-State", "terminated;reason=timeout");
11756    }
11757    switch (p->subscribed) {
11758    case XPIDF_XML:
11759    case CPIM_PIDF_XML:
11760       ast_str_append(&tmp, 0,
11761          "<?xml version=\"1.0\"?>\n"
11762          "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n"
11763          "<presence>\n");
11764       ast_str_append(&tmp, 0, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
11765       ast_str_append(&tmp, 0, "<atom id=\"%s\">\n", p->exten);
11766       ast_str_append(&tmp, 0, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
11767       ast_str_append(&tmp, 0, "<status status=\"%s\" />\n", (local_state ==  NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
11768       ast_str_append(&tmp, 0, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
11769       ast_str_append(&tmp, 0, "</address>\n</atom>\n</presence>\n");
11770       break;
11771    case PIDF_XML: /* Eyebeam supports this format */
11772       ast_str_append(&tmp, 0,
11773          "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
11774          "<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);
11775       ast_str_append(&tmp, 0, "<pp:person><status>\n");
11776       if (pidfstate[0] != '-')
11777          ast_str_append(&tmp, 0, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
11778       ast_str_append(&tmp, 0, "</status></pp:person>\n");
11779       ast_str_append(&tmp, 0, "<note>%s</note>\n", pidfnote); /* Note */
11780       ast_str_append(&tmp, 0, "<tuple id=\"%s\">\n", p->exten); /* Tuple start */
11781       ast_str_append(&tmp, 0, "<contact priority=\"1\">%s</contact>\n", mto);
11782       if (pidfstate[0] == 'b') /* Busy? Still open ... */
11783          ast_str_append(&tmp, 0, "<status><basic>open</basic></status>\n");
11784       else
11785          ast_str_append(&tmp, 0, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
11786       ast_str_append(&tmp, 0, "</tuple>\n</presence>\n");
11787       break;
11788    case DIALOG_INFO_XML: /* SNOM subscribes in this format */
11789       ast_str_append(&tmp, 0, "<?xml version=\"1.0\"?>\n");
11790       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);
11791       if ((state & AST_EXTENSION_RINGING) && sip_cfg.notifyringing) {
11792          const char *local_display = p->exten;
11793          char *local_target = mto;
11794 
11795          /* There are some limitations to how this works.  The primary one is that the
11796             callee must be dialing the same extension that is being monitored.  Simply dialing
11797             the hint'd device is not sufficient. */
11798          if (sip_cfg.notifycid) {
11799             struct ast_channel *caller = ast_channel_search_locked(find_calling_channel, p);
11800 
11801             if (caller) {
11802                int need = strlen(caller->cid.cid_num) + strlen(p->fromdomain) + sizeof("sip:@");
11803                local_target = alloca(need);
11804                snprintf(local_target, need, "sip:%s@%s", caller->cid.cid_num, p->fromdomain);
11805                if (!(ast_strlen_zero(caller->cid.cid_name))) {
11806                   local_display = ast_strdupa(caller->cid.cid_name);
11807                }
11808                ast_channel_unlock(caller);
11809                caller = NULL;
11810             }
11811             /* We create a fake call-id which the phone will send back in an INVITE
11812              * Replaces header which we can grab and do some magic with. */
11813             if (sip_cfg.pedanticsipchecking) {
11814                ast_str_append(&tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" local-tag=\"%s\" remote-tag=\"%s\" direction=\"recipient\">\n",
11815                   p->exten, p->callid, p->theirtag, p->tag);
11816             } else {
11817                ast_str_append(&tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" direction=\"recipient\">\n",
11818                   p->exten, p->callid);
11819             }
11820             ast_str_append(&tmp, 0, 
11821                   "<remote>\n"
11822                   /* See the limitations of this above.  Luckily the phone seems to still be
11823                      happy when these values are not correct. */
11824                   "<identity display=\"%s\">%s</identity>\n"
11825                   "<target uri=\"%s\"/>\n"
11826                   "</remote>\n"
11827                   "<local>\n"
11828                   "<identity>%s</identity>\n"
11829                   "<target uri=\"%s\"/>\n"
11830                   "</local>\n",
11831                   local_display, local_target, local_target, mto, mto);
11832          } else {
11833             ast_str_append(&tmp, 0, "<dialog id=\"%s\" direction=\"recipient\">\n", p->exten);
11834          }
11835       } else {
11836          ast_str_append(&tmp, 0, "<dialog id=\"%s\">\n", p->exten);
11837       }
11838       ast_str_append(&tmp, 0, "<state>%s</state>\n", statestring);
11839       if (state == AST_EXTENSION_ONHOLD) {
11840          ast_str_append(&tmp, 0, "<local>\n<target uri=\"%s\">\n"
11841                                          "<param pname=\"+sip.rendering\" pvalue=\"no\"/>\n"
11842                                          "</target>\n</local>\n", mto);
11843       }
11844       ast_str_append(&tmp, 0, "</dialog>\n</dialog-info>\n");
11845       break;
11846    case NONE:
11847    default:
11848       break;
11849    }
11850 
11851    add_content(&req, tmp->str);
11852 
11853    p->pendinginvite = p->ocseq;  /* Remember that we have a pending NOTIFY in order not to confuse the NOTIFY subsystem */
11854 
11855    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11856 }
11857 
11858 /*! \brief Notify user of messages waiting in voicemail (RFC3842)
11859 \note - Notification only works for registered peers with mailbox= definitions
11860    in sip.conf
11861    - We use the SIP Event package message-summary
11862     MIME type defaults to  "application/simple-message-summary";
11863  */
11864 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten)
11865 {
11866    struct sip_request req;
11867    struct ast_str *out = ast_str_alloca(500);
11868    int ourport = ntohs(p->ourip.sin_port);
11869    const char *exten = S_OR(vmexten, default_vmexten);
11870 
11871    initreqprep(&req, p, SIP_NOTIFY);
11872    add_header(&req, "Event", "message-summary");
11873    add_header(&req, "Content-Type", default_notifymime);
11874    ast_str_append(&out, 0, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
11875 
11876    if (!ast_strlen_zero(p->fromdomain)) {
11877       ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, p->fromdomain);
11878    } else if (!sip_standard_port(p->socket.type, ourport)) {
11879       if (p->socket.type == SIP_TRANSPORT_UDP) {
11880          ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr), ourport);
11881       } else {
11882          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));
11883       }
11884    } else {
11885       if (p->socket.type == SIP_TRANSPORT_UDP) {
11886          ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr));
11887       } else {
11888          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));
11889       }
11890    }
11891    /* Cisco has a bug in the SIP stack where it can't accept the
11892       (0/0) notification. This can temporarily be disabled in
11893       sip.conf with the "buggymwi" option */
11894    ast_str_append(&out, 0, "Voice-Message: %d/%d%s\r\n",
11895       newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));
11896 
11897    if (p->subscribed) {
11898       if (p->expiry)
11899          add_header(&req, "Subscription-State", "active");
11900       else  /* Expired */
11901          add_header(&req, "Subscription-State", "terminated;reason=timeout");
11902    }
11903 
11904    add_content(&req, out->str);
11905 
11906    if (!p->initreq.headers) 
11907       initialize_initreq(p, &req);
11908    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11909 }
11910 
11911 /*! \brief Notify a transferring party of the status of transfer (RFC3515) */
11912 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
11913 {
11914    struct sip_request req;
11915    char tmp[SIPBUFSIZE/2];
11916    
11917    reqprep(&req, p, SIP_NOTIFY, 0, 1);
11918    snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
11919    add_header(&req, "Event", tmp);
11920    add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
11921    add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
11922    add_header(&req, "Allow", ALLOWED_METHODS);
11923    add_supported_header(p, &req);
11924 
11925    snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
11926    add_content(&req, tmp);
11927 
11928    if (!p->initreq.headers)
11929       initialize_initreq(p, &req);
11930 
11931    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11932 }
11933 
11934 /*! \brief Notify device with custom headers from sip_notify.conf */
11935 static int transmit_notify_custom(struct sip_pvt *p, struct ast_variable *vars) {
11936    struct sip_request req;
11937    struct ast_variable *var, *newvar;
11938 
11939    initreqprep(&req, p, SIP_NOTIFY);
11940 
11941    /* Copy notify vars and add headers */
11942    p->notify_headers = newvar = ast_variable_new("Subscription-State", "terminated", "");
11943    add_header(&req, newvar->name, newvar->value);
11944    for (var = vars; var; var = var->next) {
11945       char buf[512];
11946 
11947       if (!strcasecmp(var->name, "Content-Length")) {
11948          ast_debug(2, "Ignoring pair %s=%s\n", var->name, var->value);
11949          continue; /* ignore content-length, it is calculated automatically */
11950       }
11951 
11952       ast_debug(2, "  Adding pair %s=%s\n", var->name, var->value);
11953       ast_copy_string(buf, var->value, sizeof(buf));
11954       add_header(&req, var->name, ast_unescape_semicolon(buf));
11955       newvar->next = ast_variable_new(var->name, var->value, "");
11956       newvar = newvar->next;
11957    }
11958 
11959    if (!p->initreq.headers) { /* Initialize first request before sending */
11960       initialize_initreq(p, &req);
11961    }
11962 
11963    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11964 }
11965 
11966 static int manager_sipnotify(struct mansession *s, const struct message *m)
11967 {
11968    const char *channame = astman_get_header(m, "Channel");
11969    struct ast_variable *vars = astman_get_variables(m);
11970    struct sip_pvt *p;
11971 
11972    if (ast_strlen_zero(channame)) {
11973       astman_send_error(s, m, "SIPNotify requires a channel name");
11974       return 0;
11975    }
11976 
11977    if (!strncasecmp(channame, "sip/", 4)) {
11978       channame += 4;
11979    }
11980 
11981    if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
11982       astman_send_error(s, m, "Unable to build sip pvt data for notify (memory/socket error)");
11983       return 0;
11984    }
11985 
11986    if (create_addr(p, channame, NULL, 0)) {
11987       /* Maybe they're not registered, etc. */
11988       dialog_unlink_all(p, TRUE, TRUE);
11989       dialog_unref(p, "unref dialog inside for loop" );
11990       /* sip_destroy(p); */
11991       astman_send_error(s, m, "Could not create address");
11992       return 0;
11993    }
11994 
11995    /* Notify is outgoing call */
11996    ast_set_flag(&p->flags[0], SIP_OUTGOING);
11997 
11998    /* Recalculate our side, and recalculate Call ID */
11999    ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
12000    build_via(p);
12001    ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
12002    build_callid_pvt(p);
12003    ao2_t_link(dialogs, p, "Linking in new name");
12004    dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
12005    sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
12006 
12007    if (!transmit_notify_custom(p, vars)) {
12008       astman_send_ack(s, m, "Notify Sent");
12009    } else {
12010       astman_send_error(s, m, "Unable to send notify");
12011    }
12012    ast_variables_destroy(vars);
12013    return 0;
12014 }
12015 
12016 static char mandescr_sipnotify[] =
12017 "Description: Sends a SIP Notify event\n"
12018 "All parameters for this event must be specified in the body of this request\n"
12019 "via multiple Variable: name=value sequences.\n"
12020 "Variables: \n"
12021 "  *Channel: <peername>       Peer to receive the notify. Required.\n"
12022 "  *Variable: <name>=<value>  At least one variable pair must be specified.\n"
12023 "  ActionID: <id>             Action ID for this transaction. Will be returned.\n";
12024 
12025 static const struct _map_x_s regstatestrings[] = {
12026    { REG_STATE_FAILED,     "Failed" },
12027    { REG_STATE_UNREGISTERED, "Unregistered"},
12028    { REG_STATE_REGSENT, "Request Sent"},
12029    { REG_STATE_AUTHSENT, "Auth. Sent"},
12030    { REG_STATE_REGISTERED, "Registered"},
12031    { REG_STATE_REJECTED, "Rejected"},
12032    { REG_STATE_TIMEOUT, "Timeout"},
12033    { REG_STATE_NOAUTH, "No Authentication"},
12034    { -1, NULL } /* terminator */
12035 };
12036 
12037 /*! \brief Convert registration state status to string */
12038 static const char *regstate2str(enum sipregistrystate regstate)
12039 {
12040    return map_x_s(regstatestrings, regstate, "Unknown");
12041 }
12042 
12043 /*! \brief Update registration with SIP Proxy.
12044  * Called from the scheduler when the previous registration expires,
12045  * so we don't have to cancel the pending event.
12046  * We assume the reference so the sip_registry is valid, since it
12047  * is stored in the scheduled event anyways.
12048  */
12049 static int sip_reregister(const void *data) 
12050 {
12051    /* if we are here, we know that we need to reregister. */
12052    struct sip_registry *r= (struct sip_registry *) data;
12053 
12054    /* if we couldn't get a reference to the registry object, punt */
12055    if (!r)
12056       return 0;
12057 
12058    if (r->call && r->call->do_history)
12059       append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
12060    /* Since registry's are only added/removed by the the monitor thread, this
12061       may be overkill to reference/dereference at all here */
12062    if (sipdebug)
12063       ast_log(LOG_NOTICE, "   -- Re-registration for  %s@%s\n", r->username, r->hostname);
12064 
12065    r->expire = -1;
12066    r->expiry = r->configured_expiry;
12067    __sip_do_register(r);
12068    registry_unref(r, "unref the re-register scheduled event");
12069    return 0;
12070 }
12071 
12072 /*! \brief Register with SIP proxy */
12073 static int __sip_do_register(struct sip_registry *r)
12074 {
12075    int res;
12076 
12077    res = transmit_register(r, SIP_REGISTER, NULL, NULL);
12078    return res;
12079 }
12080 
12081 /*! \brief Registration timeout, register again
12082  * Registered as a timeout handler during transmit_register(),
12083  * to retransmit the packet if a reply does not come back.
12084  * This is called by the scheduler so the event is not pending anymore when
12085  * we are called.
12086  */
12087 static int sip_reg_timeout(const void *data)
12088 {
12089 
12090    /* if we are here, our registration timed out, so we'll just do it over */
12091    struct sip_registry *r = (struct sip_registry *)data; /* the ref count should have been bumped when the sched item was added */
12092    struct sip_pvt *p;
12093    int res;
12094 
12095    /* if we couldn't get a reference to the registry object, punt */
12096    if (!r)
12097       return 0;
12098 
12099    if (r->dnsmgr) {
12100       /* If the registration has timed out, maybe the IP changed.  Force a refresh. */
12101       ast_dnsmgr_refresh(r->dnsmgr);
12102    }
12103 
12104    ast_log(LOG_NOTICE, "   -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts); 
12105    /* If the initial tranmission failed, we may not have an existing dialog,
12106     * so it is possible that r->call == NULL.
12107     * Otherwise destroy it, as we have a timeout so we don't want it.
12108     */
12109    if (r->call) {
12110       /* Unlink us, destroy old call.  Locking is not relevant here because all this happens
12111          in the single SIP manager thread. */
12112       p = r->call;
12113       sip_pvt_lock(p);
12114       pvt_set_needdestroy(p, "registration timeout");
12115       /* Pretend to ACK anything just in case */
12116       __sip_pretend_ack(p);
12117       sip_pvt_unlock(p);
12118 
12119       /* decouple the two objects */
12120       /* p->registry == r, so r has 2 refs, and the unref won't take the object away */
12121       if (p->registry)
12122          p->registry = registry_unref(p->registry, "p->registry unreffed");
12123       r->call = dialog_unref(r->call, "unrefing r->call");
12124    }
12125    /* If we have a limit, stop registration and give up */
12126    r->timeout = -1;
12127    if (global_regattempts_max && r->regattempts > global_regattempts_max) {
12128       /* Ok, enough is enough. Don't try any more */
12129       /* We could add an external notification here... 
12130          steal it from app_voicemail :-) */
12131       ast_log(LOG_NOTICE, "   -- Giving up forever trying to register '%s@%s'\n", r->username, r->hostname);
12132       r->regstate = REG_STATE_FAILED;
12133    } else {
12134       r->regstate = REG_STATE_UNREGISTERED;
12135       res=transmit_register(r, SIP_REGISTER, NULL, NULL);
12136    }
12137    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));
12138    registry_unref(r, "unreffing registry_unref r");
12139    return 0;
12140 }
12141 
12142 /*! \brief Transmit register to SIP proxy or UA
12143  * auth = NULL on the initial registration (from sip_reregister())
12144  */
12145 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
12146 {
12147    struct sip_request req;
12148    char from[256];
12149    char to[256];
12150    char tmp[80];
12151    char addr[80];
12152    struct sip_pvt *p;
12153    struct sip_peer *peer = NULL;
12154    int res;
12155    char *fromdomain;
12156    char *domainport = NULL;
12157 
12158    /* exit if we are already in process with this registrar ?*/
12159    if (r == NULL || ((auth == NULL) && (r->regstate == REG_STATE_REGSENT || r->regstate == REG_STATE_AUTHSENT))) {
12160       if (r) {
12161          ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
12162       }
12163       return 0;
12164    }
12165 
12166    if (r->dnsmgr == NULL) {
12167       char transport[MAXHOSTNAMELEN];
12168       peer = find_peer(r->hostname, NULL, TRUE, FINDPEERS, FALSE, 0);
12169       snprintf(transport, sizeof(transport), "_%s._%s",get_srv_service(r->transport), get_srv_protocol(r->transport)); /* have to use static get_transport function */
12170       ast_dnsmgr_lookup(peer ? peer->tohost : r->hostname, &r->us, &r->dnsmgr, sip_cfg.srvlookup ? transport : NULL);
12171       if (peer) {
12172          peer = unref_peer(peer, "removing peer ref for dnsmgr_lookup");
12173       }
12174    }
12175 
12176    if (r->call) { /* We have a registration */
12177       if (!auth) {
12178          ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
12179          return 0;
12180       } else {
12181          p = dialog_ref(r->call, "getting a copy of the r->call dialog in transmit_register");
12182          make_our_tag(p->tag, sizeof(p->tag));  /* create a new local tag for every register attempt */
12183          ast_string_field_set(p, theirtag, NULL);  /* forget their old tag, so we don't match tags when getting response */
12184       }
12185    } else {
12186       /* Build callid for registration if we haven't registered before */
12187       if (!r->callid_valid) {
12188          build_callid_registry(r, internip.sin_addr, default_fromdomain);
12189          r->callid_valid = TRUE;
12190       }
12191       /* Allocate SIP dialog for registration */
12192       if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER, NULL))) {
12193          ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
12194          return 0;
12195       }
12196       
12197       if (p->do_history)
12198          append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
12199 
12200       /* Use port number specified if no SRV record was found */
12201       if (!r->us.sin_port && r->portno)
12202          r->us.sin_port = htons(r->portno);
12203 
12204       /* Find address to hostname */
12205       if (create_addr(p, S_OR(r->peername, r->hostname), &r->us, 0)) {
12206          /* we have what we hope is a temporary network error,
12207           * probably DNS.  We need to reschedule a registration try */
12208          dialog_unlink_all(p, TRUE, TRUE);
12209          p = dialog_unref(p, "unref dialog after unlink_all");
12210          if (r->timeout > -1) {
12211             AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
12212                               registry_unref(_data, "del for REPLACE of registry ptr"), 
12213                               registry_unref(r, "object ptr dec when SCHED_REPLACE add failed"),
12214                               registry_addref(r,"add for REPLACE registry ptr"));
12215             ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
12216          } else {
12217             r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, registry_addref(r, "add for REPLACE registry ptr"));
12218             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);
12219          }
12220          r->regattempts++;
12221          return 0;
12222       }
12223 
12224       /* Copy back Call-ID in case create_addr changed it */
12225       ast_string_field_set(r, callid, p->callid);
12226       if (!r->dnsmgr && r->portno) {
12227          p->sa.sin_port = htons(r->portno);
12228          p->recv.sin_port = htons(r->portno);
12229       } else { /* Set registry port to the port set from the peer definition/srv or default */
12230          r->portno = ntohs(p->sa.sin_port);
12231       }
12232       ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Registration is outgoing call */
12233       r->call = dialog_ref(p, "copying dialog into registry r->call");     /* Save pointer to SIP dialog */
12234       p->registry = registry_addref(r, "transmit_register: addref to p->registry in transmit_register"); /* Add pointer to registry in packet */
12235       if (!ast_strlen_zero(r->secret)) {  /* Secret (password) */
12236          ast_string_field_set(p, peersecret, r->secret);
12237       }
12238       if (!ast_strlen_zero(r->md5secret))
12239          ast_string_field_set(p, peermd5secret, r->md5secret);
12240       /* User name in this realm  
12241       - if authuser is set, use that, otherwise use username */
12242       if (!ast_strlen_zero(r->authuser)) {   
12243          ast_string_field_set(p, peername, r->authuser);
12244          ast_string_field_set(p, authname, r->authuser);
12245       } else if (!ast_strlen_zero(r->username)) {
12246          ast_string_field_set(p, peername, r->username);
12247          ast_string_field_set(p, authname, r->username);
12248          ast_string_field_set(p, fromuser, r->username);
12249       }
12250       if (!ast_strlen_zero(r->username))
12251          ast_string_field_set(p, username, r->username);
12252       /* Save extension in packet */
12253       if (!ast_strlen_zero(r->callback))
12254          ast_string_field_set(p, exten, r->callback);
12255 
12256       /* Set transport and port so the correct contact is built */
12257       set_socket_transport(&p->socket, r->transport);
12258       if (r->transport == SIP_TRANSPORT_TLS || r->transport == SIP_TRANSPORT_TCP) {
12259          p->socket.port = sip_tcp_desc.local_address.sin_port;
12260       }
12261 
12262       /*
12263         check which address we should use in our contact header 
12264         based on whether the remote host is on the external or
12265         internal network so we can register through nat
12266        */
12267       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
12268       build_contact(p);
12269    }
12270 
12271    /* set up a timeout */
12272    if (auth == NULL)  {
12273       if (r->timeout > -1)
12274          ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
12275       AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
12276                         registry_unref(_data,"reg ptr unrefed from del in SCHED_REPLACE"),
12277                         registry_unref(r,"reg ptr unrefed from add failure in SCHED_REPLACE"),
12278                         registry_addref(r,"reg ptr reffed from add in SCHED_REPLACE"));
12279       ast_debug(1, "Scheduled a registration timeout for %s id  #%d \n", r->hostname, r->timeout);
12280    }
12281 
12282    if ((fromdomain = strchr(r->username, '@'))) {
12283       /* the domain name is just behind '@' */
12284       fromdomain++ ;
12285       /* We have a domain in the username for registration */
12286       snprintf(from, sizeof(from), "<sip:%s>;tag=%s", r->username, p->tag);
12287       if (!ast_strlen_zero(p->theirtag))
12288          snprintf(to, sizeof(to), "<sip:%s>;tag=%s", r->username, p->theirtag);
12289       else
12290          snprintf(to, sizeof(to), "<sip:%s>", r->username);
12291 
12292       /* If the registration username contains '@', then the domain should be used as
12293          the equivalent of "fromdomain" for the registration */
12294       if (ast_strlen_zero(p->fromdomain)) {
12295          ast_string_field_set(p, fromdomain, fromdomain);
12296       }
12297    } else {
12298       snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->tag);
12299       if (!ast_strlen_zero(p->theirtag))
12300          snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->theirtag);
12301       else
12302          snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, p->tohost);
12303    }
12304    
12305    /* Fromdomain is what we are registering to, regardless of actual
12306       host name from SRV */
12307    if (!ast_strlen_zero(p->fromdomain)) {
12308       domainport = strrchr(p->fromdomain, ':');
12309       if (domainport) {
12310          *domainport++ = '\0'; /* trim off domainport from p->fromdomain */
12311          if (ast_strlen_zero(domainport))
12312             domainport = NULL;
12313       }     
12314       if (domainport) {       
12315          if (atoi(domainport) != STANDARD_SIP_PORT)
12316             snprintf(addr, sizeof(addr), "sip:%s:%s", p->fromdomain, domainport);
12317          else
12318             snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
12319       } else {
12320          if (r->portno && r->portno != STANDARD_SIP_PORT)
12321             snprintf(addr, sizeof(addr), "sip:%s:%d", p->fromdomain, r->portno);
12322          else
12323             snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
12324       }
12325    } else {
12326       if (r->portno && r->portno != STANDARD_SIP_PORT)
12327          snprintf(addr, sizeof(addr), "sip:%s:%d", r->hostname, r->portno);
12328       else
12329          snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
12330    }
12331    ast_string_field_set(p, uri, addr);
12332 
12333    p->branch ^= ast_random();
12334 
12335    init_req(&req, sipmethod, addr);
12336 
12337    /* Add to CSEQ */
12338    snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
12339    p->ocseq = r->ocseq;
12340 
12341    build_via(p);
12342    add_header(&req, "Via", p->via);
12343    add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
12344    add_header(&req, "From", from);
12345    add_header(&req, "To", to);
12346    add_header(&req, "Call-ID", p->callid);
12347    add_header(&req, "CSeq", tmp);
12348    if (!ast_strlen_zero(global_useragent))
12349       add_header(&req, "User-Agent", global_useragent);
12350 
12351    
12352    if (auth)   /* Add auth header */
12353       add_header(&req, authheader, auth);
12354    else if (!ast_strlen_zero(r->nonce)) {
12355       char digest[1024];
12356 
12357       /* We have auth data to reuse, build a digest header.
12358        * Note, this is not always useful because some parties do not
12359        * like nonces to be reused (for good reasons!) so they will
12360        * challenge us anyways.
12361        */
12362       if (sipdebug)
12363          ast_debug(1, "   >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
12364       ast_string_field_set(p, realm, r->realm);
12365       ast_string_field_set(p, nonce, r->nonce);
12366       ast_string_field_set(p, domain, r->domain);
12367       ast_string_field_set(p, opaque, r->opaque);
12368       ast_string_field_set(p, qop, r->qop);
12369       p->noncecount = ++r->noncecount;
12370 
12371       memset(digest, 0, sizeof(digest));
12372       if(!build_reply_digest(p, sipmethod, digest, sizeof(digest)))
12373          add_header(&req, "Authorization", digest);
12374       else
12375          ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
12376    
12377    }
12378 
12379    snprintf(tmp, sizeof(tmp), "%d", r->expiry);
12380    add_header(&req, "Expires", tmp);
12381    add_header(&req, "Contact", p->our_contact);
12382 
12383    initialize_initreq(p, &req);
12384    if (sip_debug_test_pvt(p)) {
12385       ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
12386    }
12387    r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
12388    r->regattempts++; /* Another attempt */
12389    ast_debug(4, "REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
12390    res = send_request(p, &req, XMIT_CRITICAL, p->ocseq);
12391    dialog_unref(p, "p is finished here at the end of transmit_register");
12392    return res;
12393 }
12394 
12395 /*! \brief Transmit text with SIP MESSAGE method */
12396 static int transmit_message_with_text(struct sip_pvt *p, const char *text)
12397 {
12398    struct sip_request req;
12399    
12400    reqprep(&req, p, SIP_MESSAGE, 0, 1);
12401    add_text(&req, text);
12402    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12403 }
12404 
12405 /*! \brief Allocate SIP refer structure */
12406 static int sip_refer_allocate(struct sip_pvt *p)
12407 {
12408    p->refer = ast_calloc(1, sizeof(struct sip_refer)); 
12409    return p->refer ? 1 : 0;
12410 }
12411 
12412 /*! \brief Transmit SIP REFER message (initiated by the transfer() dialplan application
12413    \note this is currently broken as we have no way of telling the dialplan
12414    engine whether a transfer succeeds or fails.
12415    \todo Fix the transfer() dialplan function so that a transfer may fail
12416 */
12417 static int transmit_refer(struct sip_pvt *p, const char *dest)
12418 {
12419    struct sip_request req = { 
12420       .headers = 0,  
12421    };
12422    char from[256];
12423    const char *of;
12424    char *c;
12425    char referto[256];
12426    char *ttag, *ftag;
12427    char *theirtag = ast_strdupa(p->theirtag);
12428    int   use_tls=FALSE;
12429 
12430    if (sipdebug)
12431       ast_debug(1, "SIP transfer of %s to %s\n", p->callid, dest);
12432 
12433    /* Are we transfering an inbound or outbound call ? */
12434    if (ast_test_flag(&p->flags[0], SIP_OUTGOING))  {
12435       of = get_header(&p->initreq, "To");
12436       ttag = theirtag;
12437       ftag = p->tag;
12438    } else {
12439       of = get_header(&p->initreq, "From");
12440       ftag = theirtag;
12441       ttag = p->tag;
12442    }
12443 
12444    ast_copy_string(from, of, sizeof(from));
12445    of = get_in_brackets(from);
12446    ast_string_field_set(p, from, of);
12447    if (!strncasecmp(of, "sip:", 4)) {
12448       of += 4;
12449    }else if (!strncasecmp(of, "sips:", 5)) {
12450       of += 5;
12451       use_tls = TRUE;
12452    } else {
12453       ast_log(LOG_NOTICE, "From address missing 'sip(s):', assuming sip:\n");
12454    }
12455    /* Get just the username part */
12456    if ((c = strchr(dest, '@')))
12457       c = NULL;
12458    else if ((c = strchr(of, '@')))
12459       *c++ = '\0';
12460    if (c) 
12461       snprintf(referto, sizeof(referto), "<sip%s:%s@%s>", use_tls ? "s" : "", dest, c);
12462    else
12463       snprintf(referto, sizeof(referto), "<sip%s:%s>", use_tls ? "s" : "", dest);
12464 
12465    /* save in case we get 407 challenge */
12466    sip_refer_allocate(p);
12467    ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
12468    ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
12469    p->refer->status = REFER_SENT;   /* Set refer status */
12470 
12471    reqprep(&req, p, SIP_REFER, 0, 1);
12472 
12473    add_header(&req, "Refer-To", referto);
12474    add_header(&req, "Allow", ALLOWED_METHODS);
12475    add_supported_header(p, &req);
12476    if (!ast_strlen_zero(p->our_contact))
12477       add_header(&req, "Referred-By", p->our_contact);
12478 
12479    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12480 
12481    /* We should propably wait for a NOTIFY here until we ack the transfer */
12482    /* Maybe fork a new thread and wait for a STATUS of REFER_200OK on the refer status before returning to app_transfer */
12483 
12484    /*! \todo In theory, we should hang around and wait for a reply, before
12485    returning to the dial plan here. Don't know really how that would
12486    affect the transfer() app or the pbx, but, well, to make this
12487    useful we should have a STATUS code on transfer().
12488    */
12489 }
12490 
12491 
12492 /*! \brief Send SIP INFO dtmf message, see Cisco documentation on cisco.com */
12493 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
12494 {
12495    struct sip_request req;
12496    
12497    reqprep(&req, p, SIP_INFO, 0, 1);
12498    add_digit(&req, digit, duration, (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO));
12499    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12500 }
12501 
12502 /*! \brief Send SIP INFO with video update request */
12503 static int transmit_info_with_vidupdate(struct sip_pvt *p)
12504 {
12505    struct sip_request req;
12506    
12507    reqprep(&req, p, SIP_INFO, 0, 1);
12508    add_vidupdate(&req);
12509    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12510 }
12511 
12512 /*! \brief Transmit generic SIP request 
12513    returns XMIT_ERROR if transmit failed with a critical error (don't retry)
12514 */
12515 static int transmit_request(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
12516 {
12517    struct sip_request resp;
12518    
12519    if (sipmethod == SIP_ACK)
12520       p->invitestate = INV_CONFIRMED;
12521 
12522    reqprep(&resp, p, sipmethod, seqno, newbranch);
12523    if (sipmethod == SIP_CANCEL && p->answered_elsewhere) 
12524       add_header(&resp, "Reason", "SIP;cause=200;text=\"Call completed elsewhere\"");
12525 
12526    return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
12527 }
12528 
12529 /*! \brief return the request and response heade for a 401 or 407 code */
12530 static void auth_headers(enum sip_auth_type code, char **header, char **respheader)
12531 {
12532    if (code == WWW_AUTH) {       /* 401 */
12533       *header = "WWW-Authenticate";
12534       *respheader = "Authorization";
12535    } else if (code == PROXY_AUTH) { /* 407 */
12536       *header = "Proxy-Authenticate";
12537       *respheader = "Proxy-Authorization";
12538    } else {
12539       ast_verbose("-- wrong response code %d\n", code);
12540       *header = *respheader = "Invalid";
12541    }
12542 }
12543 
12544 /*! \brief Transmit SIP request, auth added */
12545 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
12546 {
12547    struct sip_request resp;
12548    
12549    reqprep(&resp, p, sipmethod, seqno, newbranch);
12550    if (!ast_strlen_zero(p->realm)) {
12551       char digest[1024];
12552 
12553       memset(digest, 0, sizeof(digest));
12554       if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
12555          char *dummy, *response;
12556          enum sip_auth_type code = p->options ? p->options->auth_type : PROXY_AUTH; /* XXX force 407 if unknown */
12557          auth_headers(code, &dummy, &response);
12558          add_header(&resp, response, digest);
12559       } else
12560          ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
12561    }
12562    /* If we are hanging up and know a cause for that, send it in clear text to make
12563       debugging easier. */
12564    if (sipmethod == SIP_BYE)  {
12565       char buf[10];
12566 
12567       add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->hangupcause));
12568       snprintf(buf, sizeof(buf), "%d", p->hangupcause);
12569       add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
12570    }
12571 
12572    return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);   
12573 }
12574 
12575 /*! \brief Remove registration data from realtime database or AST/DB when registration expires */
12576 static void destroy_association(struct sip_peer *peer)
12577 {
12578    int realtimeregs = ast_check_realtime("sipregs");
12579    char *tablename = (realtimeregs) ? "sipregs" : "sippeers";
12580 
12581    if (!sip_cfg.ignore_regexpire) {
12582       if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
12583          ast_update_realtime(tablename, "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", "regserver", "", "useragent", "", "lastms", "", SENTINEL);
12584       } else {
12585          ast_db_del("SIP/Registry", peer->name);
12586       }
12587    }
12588 }
12589 
12590 static void set_socket_transport(struct sip_socket *socket, int transport)
12591 {
12592    /* if the transport type changes, clear all socket data */
12593    if (socket->type != transport) {
12594       socket->fd = -1;
12595       socket->type = transport;
12596       if (socket->tcptls_session) {
12597          ao2_ref(socket->tcptls_session, -1);
12598          socket->tcptls_session = NULL;
12599       }
12600    }
12601 }
12602 
12603 /*! \brief Expire registration of SIP peer */
12604 static int expire_register(const void *data)
12605 {
12606    struct sip_peer *peer = (struct sip_peer *)data;
12607 
12608    if (!peer)     /* Hmmm. We have no peer. Weird. */
12609       return 0;
12610 
12611    peer->expire = -1;
12612    peer->portinuri = 0;
12613 
12614    destroy_association(peer); /* remove registration data from storage */
12615    set_socket_transport(&peer->socket, peer->default_outbound_transport);
12616 
12617    if (peer->socket.tcptls_session) {
12618       ao2_ref(peer->socket.tcptls_session, -1);
12619       peer->socket.tcptls_session = NULL;
12620    }
12621 
12622    manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
12623    register_peer_exten(peer, FALSE);   /* Remove regexten */
12624    ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
12625 
12626    /* Do we need to release this peer from memory? 
12627       Only for realtime peers and autocreated peers
12628    */
12629    if (peer->is_realtime)
12630       ast_debug(3, "-REALTIME- peer expired registration. Name: %s. Realtime peer objects now %d\n", peer->name, rpeerobjs);
12631 
12632    if (peer->selfdestruct ||
12633        ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
12634       unlink_peer_from_tables(peer);
12635    } else if (peer->addr.sin_addr.s_addr) {
12636       /* If we aren't self-destructing a temp_peer, we still need to unlink the peer
12637        * from the peers_by_ip table, otherwise we end up with multiple copies hanging
12638        * around each time a registration expires and the peer re-registers. */
12639       ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
12640    }
12641 
12642    /* Only clear the addr after we check for destruction.  The addr must remain
12643     * in order to unlink from the peers_by_ip container correctly */
12644    memset(&peer->addr, 0, sizeof(peer->addr));
12645 
12646    unref_peer(peer, "removing peer ref for expire_register");
12647 
12648    return 0;
12649 }
12650 
12651 /*! \brief Poke peer (send qualify to check if peer is alive and well) */
12652 static int sip_poke_peer_s(const void *data)
12653 {
12654    struct sip_peer *peer = (struct sip_peer *)data;
12655    struct sip_peer *foundpeer;
12656 
12657    peer->pokeexpire = -1;
12658 
12659    foundpeer = ao2_find(peers, peer, OBJ_POINTER);
12660    if (!foundpeer) {
12661       unref_peer(peer, "removing poke peer ref");
12662       return 0;
12663    } else if (foundpeer->name != peer->name) {
12664       unref_peer(foundpeer, "removing above peer ref");
12665       unref_peer(peer, "removing poke peer ref");
12666       return 0;
12667    }
12668 
12669    unref_peer(foundpeer, "removing above peer ref");
12670    sip_poke_peer(peer, 0);
12671    unref_peer(peer, "removing poke peer ref");
12672 
12673    return 0;
12674 }
12675 
12676 /*! \brief Get registration details from Asterisk DB */
12677 static void reg_source_db(struct sip_peer *peer)
12678 {
12679    char data[256];
12680    struct in_addr in;
12681    int expire;
12682    int port;
12683    char *scan, *addr, *port_str, *expiry_str, *username, *contact;
12684 
12685    if (peer->rt_fromcontact) 
12686       return;
12687    if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data)))
12688       return;
12689 
12690    scan = data;
12691    addr = strsep(&scan, ":");
12692    port_str = strsep(&scan, ":");
12693    expiry_str = strsep(&scan, ":");
12694    username = strsep(&scan, ":");
12695    contact = scan;   /* Contact include sip: and has to be the last part of the database entry as long as we use : as a separator */
12696 
12697    if (!inet_aton(addr, &in))
12698       return;
12699 
12700    if (port_str)
12701       port = atoi(port_str);
12702    else
12703       return;
12704 
12705    if (expiry_str)
12706       expire = atoi(expiry_str);
12707    else
12708       return;
12709 
12710    if (username)
12711       ast_string_field_set(peer, username, username);
12712    if (contact)
12713       ast_string_field_set(peer, fullcontact, contact);
12714 
12715    ast_debug(2, "SIP Seeding peer from astdb: '%s' at %s@%s:%d for %d\n",
12716        peer->name, peer->username, ast_inet_ntoa(in), port, expire);
12717 
12718    memset(&peer->addr, 0, sizeof(peer->addr));
12719    peer->addr.sin_family = AF_INET;
12720    peer->addr.sin_addr = in;
12721    peer->addr.sin_port = htons(port);
12722    if (sipsock < 0) {
12723       /* SIP isn't up yet, so schedule a poke only, pretty soon */
12724       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ast_random() % 5000 + 1, sip_poke_peer_s, peer,
12725             unref_peer(_data, "removing poke peer ref"),
12726             unref_peer(peer, "removing poke peer ref"),
12727             ref_peer(peer, "adding poke peer ref"));
12728    } else {
12729       sip_poke_peer(peer, 0);
12730    }
12731    AST_SCHED_REPLACE_UNREF(peer->expire, sched, (expire + 10) * 1000, expire_register, peer,
12732          unref_peer(_data, "remove registration ref"),
12733          unref_peer(peer, "remove registration ref"),
12734          ref_peer(peer, "add registration ref"));
12735    register_peer_exten(peer, TRUE);
12736 }
12737 
12738 /*! \brief Save contact header for 200 OK on INVITE */
12739 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
12740 {
12741    char contact[SIPBUFSIZE]; 
12742    char *c;
12743 
12744    /* Look for brackets */
12745    ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
12746    c = get_in_brackets(contact);
12747 
12748    /* Save full contact to call pvt for later bye or re-invite */
12749    ast_string_field_set(pvt, fullcontact, c);
12750 
12751    /* Save URI for later ACKs, BYE or RE-invites */
12752    ast_string_field_set(pvt, okcontacturi, c);
12753 
12754    /* We should return false for URI:s we can't handle,
12755       like tel:, mailto:,ldap: etc */
12756    return TRUE;      
12757 }
12758 
12759 static int __set_address_from_contact(const char *fullcontact, struct sockaddr_in *sin, int tcp)
12760 {
12761    struct hostent *hp;
12762    struct ast_hostent ahp;
12763    int port = STANDARD_SIP_PORT;
12764    char *host, *pt, *transport;
12765    char contact_buf[256];
12766    char *contact;
12767 
12768    /* Work on a copy */
12769    ast_copy_string(contact_buf, fullcontact, sizeof(contact_buf));
12770    contact = contact_buf;
12771 
12772    /* 
12773     * We have only the part in <brackets> here so we just need to parse a SIP URI.
12774     *
12775     * Note: The outbound proxy could be using UDP between the proxy and Asterisk.
12776     * We still need to be able to send to the remote agent through the proxy.
12777     */
12778 
12779    if (parse_uri(contact, "sip:,sips:", &contact, NULL, &host, &pt, NULL, &transport)) {
12780       ast_log(LOG_WARNING, "Invalid contact uri %s (missing sip: or sips:), attempting to use anyway\n", fullcontact);
12781    }
12782 
12783    /* set port */
12784    if (((get_transport_str2enum(transport) == SIP_TRANSPORT_TLS)) || !(strncasecmp(fullcontact, "sips", 4))) {
12785       port = port_str2int(pt, STANDARD_TLS_PORT);
12786    } else {
12787       port = port_str2int(pt, STANDARD_SIP_PORT);
12788    }
12789 
12790 
12791    /* XXX This could block for a long time XXX */
12792    /* We should only do this if it's a name, not an IP */
12793    /* \todo - if there's no PORT number in contact - we are required to check NAPTR/SRV records
12794       to find transport, port address and hostname. If there's a port number, we have to
12795       assume that the domain part is a host name and only look for an A/AAAA record in DNS.
12796    */
12797    hp = ast_gethostbyname(host, &ahp);
12798    if (!hp)  {
12799       ast_log(LOG_WARNING, "Invalid host name in Contact: (can't resolve in DNS) : '%s'\n", host);
12800       return -1;
12801    }
12802    sin->sin_family = AF_INET;
12803    memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
12804    sin->sin_port = htons(port);
12805 
12806    return 0;
12807 }
12808 
12809 /*! \brief Change the other partys IP address based on given contact */
12810 static int set_address_from_contact(struct sip_pvt *pvt)
12811 {
12812    if (ast_test_flag(&pvt->flags[0], SIP_NAT_ROUTE)) {
12813       /* NAT: Don't trust the contact field.  Just use what they came to us
12814          with. */
12815       /*! \todo We need to save the TRANSPORT here too */
12816       pvt->sa = pvt->recv;
12817       return 0;
12818    }
12819 
12820    return __set_address_from_contact(pvt->fullcontact, &pvt->sa, pvt->socket.type == SIP_TRANSPORT_TLS ? 1 : 0);
12821 }
12822 
12823 /*! \brief Parse contact header and save registration (peer registration) */
12824 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
12825 {
12826    char contact[SIPBUFSIZE];
12827    char data[SIPBUFSIZE];
12828    const char *expires = get_header(req, "Expires");
12829    int expire = atoi(expires);
12830    char *curi, *host, *pt, *transport;
12831    int port;
12832    int transport_type;
12833    const char *useragent;
12834    struct hostent *hp;
12835    struct ast_hostent ahp;
12836    struct sockaddr_in oldsin, testsin;
12837    char *firstcuri = NULL;
12838    int start = 0;
12839    int wildcard_found = 0;
12840    int single_binding_found = 0;
12841 
12842    ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
12843 
12844    if (ast_strlen_zero(expires)) {  /* No expires header, try look in Contact: */
12845       char *s = strcasestr(contact, ";expires=");
12846       if (s) {
12847          expires = strsep(&s, ";"); /* trim ; and beyond */
12848          if (sscanf(expires + 9, "%30d", &expire) != 1)
12849             expire = default_expiry;
12850       } else {
12851          /* Nothing has been specified */
12852          expire = default_expiry;
12853       }
12854    }
12855 
12856    copy_socket_data(&pvt->socket, &req->socket);
12857 
12858    do {
12859       /* Look for brackets */
12860       curi = contact;
12861       if (strchr(contact, '<') == NULL)   /* No <, check for ; and strip it */
12862          strsep(&curi, ";");  /* This is Header options, not URI options */
12863       curi = get_in_brackets(contact);
12864       if (!firstcuri) {
12865          firstcuri = ast_strdupa(curi);
12866       }
12867 
12868       if (!strcasecmp(curi, "*")) {
12869          wildcard_found = 1;
12870       } else {
12871          single_binding_found = 1;
12872       }
12873 
12874       if (wildcard_found && (ast_strlen_zero(expires) || expire != 0 || single_binding_found)) {
12875          /* Contact header parameter "*" detected, so punt if: Expires header is missing,
12876           * Expires value is not zero, or another Contact header is present. */
12877          return PARSE_REGISTER_FAILED;
12878       }
12879 
12880       ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
12881    } while (!ast_strlen_zero(contact));
12882    curi = firstcuri;
12883 
12884    /* if they did not specify Contact: or Expires:, they are querying
12885       what we currently have stored as their contact address, so return
12886       it
12887    */
12888    if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
12889       /* If we have an active registration, tell them when the registration is going to expire */
12890       if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact))
12891          pvt->expiry = ast_sched_when(sched, peer->expire);
12892       return PARSE_REGISTER_QUERY;
12893    } else if (!strcasecmp(curi, "*") || !expire) { /* Unregister this peer */
12894       /* This means remove all registrations and return OK */
12895       AST_SCHED_DEL_UNREF(sched, peer->expire,
12896             unref_peer(peer, "remove register expire ref"));
12897       ast_verb(3, "Unregistered SIP '%s'\n", peer->name);
12898       expire_register(ref_peer(peer,"add ref for explicit expire_register"));
12899       return PARSE_REGISTER_UPDATE;
12900    }
12901 
12902    /* Store whatever we got as a contact from the client */
12903    ast_string_field_set(peer, fullcontact, curi);
12904 
12905    /* For the 200 OK, we should use the received contact */
12906    ast_string_field_build(pvt, our_contact, "<%s>", curi);
12907 
12908    /* Make sure it's a SIP URL */
12909    if (parse_uri(curi, "sip:,sips:", &curi, NULL, &host, &pt, NULL, &transport)) {
12910       ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:) trying to use anyway\n");
12911    }
12912 
12913    /* If we have a port number in the given URI, make sure we do remember to not check for NAPTR/SRV records. 
12914       The domain part is actually a host. */
12915    peer->portinuri = !ast_strlen_zero(pt) ? TRUE : FALSE;
12916 
12917    /* handle the transport type specified in Contact header. */
12918    if ((transport_type = get_transport_str2enum(transport))) {
12919       /* if the port is not specified but the transport is, make sure to set the
12920        * default port to match the specified transport.  This may or may not be the
12921        * same transport used by the pvt struct for the Register dialog. */
12922       
12923       port = port_str2int(pt, (transport_type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
12924    } else {
12925       port = port_str2int(pt, STANDARD_SIP_PORT);
12926       transport_type = pvt->socket.type;
12927    }
12928 
12929    /* if the peer's socket type is different than the Registration
12930     * transport type, change it.  If it got this far, it is a
12931     * supported type, but check just in case */
12932    if ((peer->socket.type != transport_type) && (peer->transports & transport_type)) {
12933       set_socket_transport(&peer->socket, transport_type);
12934    }
12935 
12936    oldsin = peer->addr;
12937 
12938    /* If we were already linked into the peers_by_ip container unlink ourselves so nobody can find us */
12939    if (peer->addr.sin_addr.s_addr && (!peer->is_realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS))) {
12940       ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
12941    }
12942 
12943    if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE)) {
12944       /* use the data provided in the Contact header for call routing */
12945       ast_debug(1, "Store REGISTER's Contact header for call routing.\n");
12946       /* XXX This could block for a long time XXX */
12947       /*! \todo Check NAPTR/SRV if we have not got a port in the URI */
12948       hp = ast_gethostbyname(host, &ahp);
12949       if (!hp)  {
12950          ast_log(LOG_WARNING, "Invalid host '%s'\n", host);
12951          ast_string_field_set(peer, fullcontact, "");
12952          ast_string_field_set(pvt, our_contact, "");
12953          return PARSE_REGISTER_FAILED;
12954       }
12955       peer->addr.sin_family = AF_INET;
12956       memcpy(&peer->addr.sin_addr, hp->h_addr, sizeof(peer->addr.sin_addr));
12957       peer->addr.sin_port = htons(port);
12958    } else {
12959       /* Don't trust the contact field.  Just use what they came to us
12960          with */
12961       ast_debug(1, "Store REGISTER's src-IP:port for call routing.\n");
12962       peer->addr = pvt->recv;
12963    }
12964 
12965    /* Check that they're allowed to register at this IP */
12966    memcpy(&testsin.sin_addr, &peer->addr.sin_addr, sizeof(testsin.sin_addr));
12967    if (ast_apply_ha(global_contact_ha, &testsin) != AST_SENSE_ALLOW ||
12968          ast_apply_ha(peer->contactha, &testsin) != AST_SENSE_ALLOW) {
12969       ast_log(LOG_WARNING, "Host '%s' disallowed by contact ACL (violating IP %s)\n", host, ast_inet_ntoa(testsin.sin_addr));
12970       ast_string_field_set(peer, fullcontact, "");
12971       ast_string_field_set(pvt, our_contact, "");
12972       return PARSE_REGISTER_DENIED;
12973    }
12974 
12975    /* if the Contact header information copied into peer->addr matches the
12976     * received address, and the transport types are the same, then copy socket
12977     * data into the peer struct */
12978    if ((peer->socket.type == pvt->socket.type) &&
12979       (peer->addr.sin_addr.s_addr == pvt->recv.sin_addr.s_addr) &&
12980       (peer->addr.sin_port == pvt->recv.sin_port)){
12981 
12982       copy_socket_data(&peer->socket, &pvt->socket);
12983    }
12984 
12985    /* Now that our address has been updated put ourselves back into the container for lookups */
12986    if (!peer->is_realtime || ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
12987       ao2_t_link(peers_by_ip, peer, "ao2_link into peers_by_ip table");
12988    }
12989 
12990    /* Save SIP options profile */
12991    peer->sipoptions = pvt->sipoptions;
12992 
12993    if (!ast_strlen_zero(curi) && ast_strlen_zero(peer->username))
12994       ast_string_field_set(peer, username, curi);
12995 
12996    AST_SCHED_DEL_UNREF(sched, peer->expire,
12997          unref_peer(peer, "remove register expire ref"));
12998 
12999    if (expire > max_expiry)
13000       expire = max_expiry;
13001    if (expire < min_expiry)
13002       expire = min_expiry;
13003    if (peer->is_realtime && !ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
13004       peer->expire = -1;
13005    } else {
13006       peer->expire = ast_sched_add(sched, (expire + 10) * 1000, expire_register,
13007             ref_peer(peer, "add registration ref"));
13008       if (peer->expire == -1) {
13009          unref_peer(peer, "remote registration ref");
13010       }
13011    }
13012    pvt->expiry = expire;
13013    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);
13014    /* Saving TCP connections is useless, we won't be able to reconnect 
13015       XXX WHY???? XXX
13016       \todo Fix this immediately.
13017    */
13018    if (!peer->rt_fromcontact && (peer->socket.type & SIP_TRANSPORT_UDP))
13019       ast_db_put("SIP/Registry", peer->name, data);
13020    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));
13021 
13022    /* Is this a new IP address for us? */
13023    if (VERBOSITY_ATLEAST(2) && inaddrcmp(&peer->addr, &oldsin)) {
13024       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));
13025    }
13026    sip_poke_peer(peer, 0);
13027    register_peer_exten(peer, 1);
13028    
13029    /* Save User agent */
13030    useragent = get_header(req, "User-Agent");
13031    if (strcasecmp(useragent, peer->useragent)) {
13032       ast_string_field_set(peer, useragent, useragent);
13033       ast_verb(4, "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
13034    }
13035    return PARSE_REGISTER_UPDATE;
13036 }
13037 
13038 /*! \brief Remove route from route list */
13039 static void free_old_route(struct sip_route *route)
13040 {
13041    struct sip_route *next;
13042 
13043    while (route) {
13044       next = route->next;
13045       ast_free(route);
13046       route = next;
13047    }
13048 }
13049 
13050 /*! \brief List all routes - mostly for debugging */
13051 static void list_route(struct sip_route *route)
13052 {
13053    if (!route)
13054       ast_verbose("list_route: no route\n");
13055    else {
13056       for (;route; route = route->next)
13057          ast_verbose("list_route: hop: <%s>\n", route->hop);
13058    }
13059 }
13060 
13061 /*! \brief Build route list from Record-Route header */
13062 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
13063 {
13064    struct sip_route *thishop, *head, *tail;
13065    int start = 0;
13066    int len;
13067    const char *rr, *contact, *c;
13068 
13069    /* Once a persistant route is set, don't fool with it */
13070    if (p->route && p->route_persistant) {
13071       ast_debug(1, "build_route: Retaining previous route: <%s>\n", p->route->hop);
13072       return;
13073    }
13074 
13075    if (p->route) {
13076       free_old_route(p->route);
13077       p->route = NULL;
13078    }
13079 
13080    /* We only want to create the route set the first time this is called */
13081    p->route_persistant = 1;
13082    
13083    /* Build a tailq, then assign it to p->route when done.
13084     * If backwards, we add entries from the head so they end up
13085     * in reverse order. However, we do need to maintain a correct
13086     * tail pointer because the contact is always at the end.
13087     */
13088    head = NULL;
13089    tail = head;
13090    /* 1st we pass through all the hops in any Record-Route headers */
13091    for (;;) {
13092       /* Each Record-Route header */
13093       rr = __get_header(req, "Record-Route", &start);
13094       if (*rr == '\0')
13095          break;
13096       for (; (rr = strchr(rr, '<')) ; rr += len) { /* Each route entry */
13097          ++rr;
13098          len = strcspn(rr, ">") + 1;
13099          /* Make a struct route */
13100          if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
13101             /* ast_calloc is not needed because all fields are initialized in this block */
13102             ast_copy_string(thishop->hop, rr, len);
13103             ast_debug(2, "build_route: Record-Route hop: <%s>\n", thishop->hop);
13104             /* Link in */
13105             if (backwards) {
13106                /* Link in at head so they end up in reverse order */
13107                thishop->next = head;
13108                head = thishop;
13109                /* If this was the first then it'll be the tail */
13110                if (!tail)
13111                   tail = thishop;
13112             } else {
13113                thishop->next = NULL;
13114                /* Link in at the end */
13115                if (tail)
13116                   tail->next = thishop;
13117                else
13118                   head = thishop;
13119                tail = thishop;
13120             }
13121          }
13122       }
13123    }
13124 
13125    /* Only append the contact if we are dealing with a strict router */
13126    if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop, ";lr") == NULL) ) {
13127       /* 2nd append the Contact: if there is one */
13128       /* Can be multiple Contact headers, comma separated values - we just take the first */
13129       contact = get_header(req, "Contact");
13130       if (!ast_strlen_zero(contact)) {
13131          ast_debug(2, "build_route: Contact hop: %s\n", contact);
13132          /* Look for <: delimited address */
13133          c = strchr(contact, '<');
13134          if (c) {
13135             /* Take to > */
13136             ++c;
13137             len = strcspn(c, ">") + 1;
13138          } else {
13139             /* No <> - just take the lot */
13140             c = contact;
13141             len = strlen(contact) + 1;
13142          }
13143          if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
13144             /* ast_calloc is not needed because all fields are initialized in this block */
13145             ast_copy_string(thishop->hop, c, len);
13146             thishop->next = NULL;
13147             /* Goes at the end */
13148             if (tail)
13149                tail->next = thishop;
13150             else
13151                head = thishop;
13152          }
13153       }
13154    }
13155 
13156    /* Store as new route */
13157    p->route = head;
13158 
13159    /* For debugging dump what we ended up with */
13160    if (sip_debug_test_pvt(p))
13161       list_route(p->route);
13162 }
13163 
13164 /*! \brief builds the sip_pvt's randdata field which is used for the nonce
13165  *  challenge.  When forceupdate is not set, the nonce is only updated if
13166  *  the current one is stale.  In this case, a stalenonce is one which
13167  *  has already received a response, if a nonce has not received a response
13168  *  it is not always necessary or beneficial to create a new one. */
13169 
13170 static void set_nonce_randdata(struct sip_pvt *p, int forceupdate)
13171 {
13172    if (p->stalenonce || forceupdate || ast_strlen_zero(p->randdata)) {
13173       ast_string_field_build(p, randdata, "%08lx", ast_random()); /* Create nonce for challenge */
13174       p->stalenonce = 0;
13175    }
13176 }
13177 
13178 AST_THREADSTORAGE(check_auth_buf);
13179 #define CHECK_AUTH_BUF_INITLEN   256
13180 
13181 /*! \brief  Check user authorization from peer definition 
13182    Some actions, like REGISTER and INVITEs from peers require
13183    authentication (if peer have secret set) 
13184     \return 0 on success, non-zero on error
13185 */
13186 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
13187                 const char *secret, const char *md5secret, int sipmethod,
13188                 char *uri, enum xmittype reliable, int ignore)
13189 {
13190    const char *response;
13191    char *reqheader, *respheader;
13192    const char *authtoken;
13193    char a1_hash[256];
13194    char resp_hash[256]="";
13195    char *c;
13196    int  wrongnonce = FALSE;
13197    int  good_response;
13198    const char *usednonce = p->randdata;
13199    struct ast_str *buf;
13200    int res;
13201 
13202    /* table of recognised keywords, and their value in the digest */
13203    enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
13204    struct x {
13205       const char *key;
13206       const char *s;
13207    } *i, keys[] = {
13208       [K_RESP] = { "response=", "" },
13209       [K_URI] = { "uri=", "" },
13210       [K_USER] = { "username=", "" },
13211       [K_NONCE] = { "nonce=", "" },
13212       [K_LAST] = { NULL, NULL}
13213    };
13214 
13215    /* Always OK if no secret */
13216    if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
13217       return AUTH_SUCCESSFUL;
13218 
13219    /* Always auth with WWW-auth since we're NOT a proxy */
13220    /* Using proxy-auth in a B2BUA may block proxy authorization in the same transaction */
13221    response = "401 Unauthorized";
13222 
13223    /*
13224     * Note the apparent swap of arguments below, compared to other
13225     * usages of auth_headers().
13226     */
13227    auth_headers(WWW_AUTH, &respheader, &reqheader);
13228 
13229    authtoken =  get_header(req, reqheader);  
13230    if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
13231       /* This is a retransmitted invite/register/etc, don't reconstruct authentication
13232          information */
13233       if (!reliable) {
13234          /* Resend message if this was NOT a reliable delivery.   Otherwise the
13235             retransmission should get it */
13236          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
13237          /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
13238          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13239       }
13240       return AUTH_CHALLENGE_SENT;
13241    } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
13242       /* We have no auth, so issue challenge and request authentication */
13243       set_nonce_randdata(p, 1); /* Create nonce for challenge */
13244       transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
13245       /* Schedule auto destroy in 32 seconds */
13246       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13247       return AUTH_CHALLENGE_SENT;
13248    } 
13249 
13250    /* --- We have auth, so check it */
13251 
13252    /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
13253       an example in the spec of just what it is you're doing a hash on. */
13254 
13255    if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN)))
13256       return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
13257 
13258    /* Make a copy of the response and parse it */
13259    res = ast_str_set(&buf, 0, "%s", authtoken);
13260 
13261    if (res == AST_DYNSTR_BUILD_FAILED)
13262       return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
13263 
13264    c = buf->str;
13265 
13266    while(c && *(c = ast_skip_blanks(c)) ) { /* lookup for keys */
13267       for (i = keys; i->key != NULL; i++) {
13268          const char *separator = ",";  /* default */
13269 
13270          if (strncasecmp(c, i->key, strlen(i->key)) != 0)
13271             continue;
13272          /* Found. Skip keyword, take text in quotes or up to the separator. */
13273          c += strlen(i->key);
13274          if (*c == '"') { /* in quotes. Skip first and look for last */
13275             c++;
13276             separator = "\"";
13277          }
13278          i->s = c;
13279          strsep(&c, separator);
13280          break;
13281       }
13282       if (i->key == NULL) /* not found, jump after space or comma */
13283          strsep(&c, " ,");
13284    }
13285 
13286    /* Verify that digest username matches  the username we auth as */
13287    if (strcmp(username, keys[K_USER].s)) {
13288       ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
13289          username, keys[K_USER].s);
13290       /* Oops, we're trying something here */
13291       return AUTH_USERNAME_MISMATCH;
13292    }
13293 
13294    /* Verify nonce from request matches our nonce, and the nonce has not already been responded to.
13295     * If this check fails, send 401 with new nonce */
13296    if (strcasecmp(p->randdata, keys[K_NONCE].s) || p->stalenonce) { /* XXX it was 'n'casecmp ? */
13297       wrongnonce = TRUE;
13298       usednonce = keys[K_NONCE].s;
13299    } else {
13300       p->stalenonce = 1; /* now, since the nonce has a response, mark it as stale so it can't be sent or responded to again */
13301    }
13302 
13303    if (!ast_strlen_zero(md5secret))
13304       ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
13305    else {
13306       char a1[256];
13307       snprintf(a1, sizeof(a1), "%s:%s:%s", username, sip_cfg.realm, secret);
13308       ast_md5_hash(a1_hash, a1);
13309    }
13310 
13311    /* compute the expected response to compare with what we received */
13312    {
13313       char a2[256];
13314       char a2_hash[256];
13315       char resp[256];
13316 
13317       snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
13318             S_OR(keys[K_URI].s, uri));
13319       ast_md5_hash(a2_hash, a2);
13320       snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
13321       ast_md5_hash(resp_hash, resp);
13322    }
13323 
13324    good_response = keys[K_RESP].s &&
13325          !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
13326    if (wrongnonce) {
13327       if (good_response) {
13328          if (sipdebug)
13329             ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "From"));
13330          /* We got working auth token, based on stale nonce . */
13331          set_nonce_randdata(p, 0);
13332          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
13333       } else {
13334          /* Everything was wrong, so give the device one more try with a new challenge */
13335          if (!req->ignore) {
13336             if (sipdebug)
13337                ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
13338             set_nonce_randdata(p, 1);
13339          } else {
13340             if (sipdebug)
13341                ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", get_header(req, "To"));
13342          }
13343          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
13344       }
13345 
13346       /* Schedule auto destroy in 32 seconds */
13347       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13348       return AUTH_CHALLENGE_SENT;
13349    } 
13350    if (good_response) {
13351       append_history(p, "AuthOK", "Auth challenge successful for %s", username);
13352       return AUTH_SUCCESSFUL;
13353    }
13354 
13355    /* Ok, we have a bad username/secret pair */
13356    /* Tell the UAS not to re-send this authentication data, because
13357       it will continue to fail
13358    */
13359 
13360    return AUTH_SECRET_FAILED;
13361 }
13362 
13363 /*! \brief Change onhold state of a peer using a pvt structure */
13364 static void sip_peer_hold(struct sip_pvt *p, int hold)
13365 {
13366    struct sip_peer *peer = find_peer(p->peername, NULL, 1, FINDALLDEVICES, FALSE, 0);
13367 
13368    if (!peer)
13369       return;
13370 
13371    /* If they put someone on hold, increment the value... otherwise decrement it */
13372    ast_atomic_fetchadd_int(&peer->onHold, (hold ? +1 : -1));
13373 
13374    /* Request device state update */
13375    ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
13376    unref_peer(peer, "sip_peer_hold: from find_peer operation");
13377    
13378    return;
13379 }
13380 
13381 /*! \brief Receive MWI events that we have subscribed to */
13382 static void mwi_event_cb(const struct ast_event *event, void *userdata)
13383 {
13384    struct sip_peer *peer = userdata;
13385 
13386    ao2_lock(peer);
13387    sip_send_mwi_to_peer(peer, event, 0);
13388    ao2_unlock(peer);
13389 }
13390 
13391 /*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem
13392 \note If you add an "hint" priority to the extension in the dial plan,
13393    you will get notifications on device state changes */
13394 static int cb_extensionstate(char *context, char* exten, int state, void *data)
13395 {
13396    struct sip_pvt *p = data;
13397 
13398    sip_pvt_lock(p);
13399 
13400    switch(state) {
13401    case AST_EXTENSION_DEACTIVATED:  /* Retry after a while */
13402    case AST_EXTENSION_REMOVED:   /* Extension is gone */
13403       if (p->autokillid > -1 && sip_cancel_destroy(p))   /* Remove subscription expiry for renewals */
13404          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
13405       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);  /* Delete subscription in 32 secs */
13406       ast_verb(2, "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
13407       p->stateid = -1;
13408       p->subscribed = NONE;
13409       append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
13410       break;
13411    default: /* Tell user */
13412       p->laststate = state;
13413       break;
13414    }
13415    if (p->subscribed != NONE) {  /* Only send state NOTIFY if we know the format */
13416       if (!p->pendinginvite) {
13417          transmit_state_notify(p, state, 1, FALSE);
13418       } else {
13419          /* We already have a NOTIFY sent that is not answered. Queue the state up.
13420             if many state changes happen meanwhile, we will only send a notification of the last one */
13421          ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
13422       }
13423    }
13424    ast_verb(2, "Extension Changed %s[%s] new state %s for Notify User %s %s\n", exten, context, ast_extension_state2str(state), p->username,
13425          ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
13426 
13427    sip_pvt_unlock(p);
13428 
13429    return 0;
13430 }
13431 
13432 /*! \brief Send a fake 401 Unauthorized response when the administrator
13433   wants to hide the names of local devices  from fishers
13434  */
13435 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable)
13436 {
13437    /* We have to emulate EXACTLY what we'd get with a good peer
13438     * and a bad password, or else we leak information. */
13439    const char *response = "401 Unauthorized";
13440    const char *reqheader = "Authorization";
13441    const char *respheader = "WWW-Authenticate";
13442    const char *authtoken;
13443    struct ast_str *buf;
13444    char *c;
13445 
13446    /* table of recognised keywords, and their value in the digest */
13447    enum keys { K_NONCE, K_LAST };
13448    struct x {
13449       const char *key;
13450       const char *s;
13451    } *i, keys[] = {
13452       [K_NONCE] = { "nonce=", "" },
13453       [K_LAST] = { NULL, NULL}
13454    };
13455 
13456    authtoken = get_header(req, reqheader);
13457    if (req->ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
13458       /* This is a retransmitted invite/register/etc, don't reconstruct authentication
13459        * information */
13460       transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
13461       /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
13462       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13463       return;
13464    } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
13465       /* We have no auth, so issue challenge and request authentication */
13466       set_nonce_randdata(p, 1);
13467       transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
13468       /* Schedule auto destroy in 32 seconds */
13469       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13470       return;
13471    }
13472 
13473    if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
13474       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
13475       return;
13476    }
13477 
13478    /* Make a copy of the response and parse it */
13479    if (ast_str_set(&buf, 0, "%s", authtoken) == AST_DYNSTR_BUILD_FAILED) {
13480       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
13481       return;
13482    }
13483 
13484    c = buf->str;
13485 
13486    while (c && *(c = ast_skip_blanks(c))) { /* lookup for keys */
13487       for (i = keys; i->key != NULL; i++) {
13488          const char *separator = ",";  /* default */
13489 
13490          if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
13491             continue;
13492          }
13493          /* Found. Skip keyword, take text in quotes or up to the separator. */
13494          c += strlen(i->key);
13495          if (*c == '"') { /* in quotes. Skip first and look for last */
13496             c++;
13497             separator = "\"";
13498          }
13499          i->s = c;
13500          strsep(&c, separator);
13501          break;
13502       }
13503       if (i->key == NULL) { /* not found, jump after space or comma */
13504          strsep(&c, " ,");
13505       }
13506    }
13507 
13508    /* Verify nonce from request matches our nonce.  If not, send 401 with new nonce */
13509    if (strcasecmp(p->randdata, keys[K_NONCE].s)) {
13510       if (!req->ignore) {
13511          set_nonce_randdata(p, 1);
13512       }
13513       transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
13514 
13515       /* Schedule auto destroy in 32 seconds */
13516       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13517    } else {
13518       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
13519    }
13520 }
13521 
13522 /*!
13523  * Terminate the uri at the first ';' or space.
13524  * Technically we should ignore escaped space per RFC3261 (19.1.1 etc)
13525  * but don't do it for the time being. Remember the uri format is:
13526  * (User-parameters was added after RFC 3261)
13527  *\verbatim
13528  *
13529  * sip:user:password;user-parameters@host:port;uri-parameters?headers
13530  * sips:user:password;user-parameters@host:port;uri-parameters?headers
13531  *
13532  *\endverbatim
13533  * \todo As this function does not support user-parameters, it's considered broken
13534  * and needs fixing.
13535  */
13536 static char *terminate_uri(char *uri)
13537 {
13538    char *t = uri;
13539    while (*t && *t > ' ' && *t != ';')
13540       t++;
13541    *t = '\0';
13542    return uri;
13543 }
13544 
13545 /*! \brief Verify registration of user 
13546    - Registration is done in several steps, first a REGISTER without auth
13547      to get a challenge (nonce) then a second one with auth
13548    - Registration requests are only matched with peers that are marked as "dynamic"
13549  */
13550 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
13551                      struct sip_request *req, char *uri)
13552 {
13553    enum check_auth_result res = AUTH_NOT_FOUND;
13554    struct sip_peer *peer;
13555    char tmp[256];
13556    char *name, *c;
13557    char *domain;
13558 
13559    terminate_uri(uri);  /* warning, overwrite the string */
13560 
13561    ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
13562    if (sip_cfg.pedanticsipchecking)
13563       ast_uri_decode(tmp);
13564 
13565    c = get_in_brackets(tmp);
13566    c = remove_uri_parameters(c);
13567 
13568    if (!strncasecmp(c, "sip:", 4)) {
13569       name = c + 4;
13570    } else if (!strncasecmp(c, "sips:", 5)) {
13571       name = c + 5;
13572    } else {
13573       name = c;
13574       ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_inet_ntoa(sin->sin_addr));
13575    }
13576 
13577    /*! \todo XXX here too we interpret a missing @domain as a name-only
13578     * URI, whereas the RFC says this is a domain-only uri.
13579     */
13580    /* Strip off the domain name */
13581    if ((c = strchr(name, '@'))) {
13582       *c++ = '\0';
13583       domain = c;
13584       if ((c = strchr(domain, ':')))   /* Remove :port */
13585          *c = '\0';
13586       if (!AST_LIST_EMPTY(&domain_list)) {
13587          if (!check_sip_domain(domain, NULL, 0)) {
13588             transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
13589             return AUTH_UNKNOWN_DOMAIN;
13590          }
13591       }
13592    }
13593    c = strchr(name, ';');  /* Remove any Username parameters */
13594    if (c)
13595       *c = '\0';
13596 
13597    ast_string_field_set(p, exten, name);
13598    build_contact(p);
13599    if (req->ignore) {
13600       /* Expires is a special case, where we only want to load the peer if this isn't a deregistration attempt */
13601       const char *expires = get_header(req, "Expires");
13602       int expire = atoi(expires);
13603 
13604       if (ast_strlen_zero(expires)) { /* No expires header; look in Contact */
13605          if ((expires = strcasestr(get_header(req, "Contact"), ";expires="))) {
13606             expire = atoi(expires + 9);
13607          }
13608       }
13609       if (!ast_strlen_zero(expires) && expire == 0) {
13610          transmit_response_with_date(p, "200 OK", req);
13611          return 0;
13612       }
13613    }
13614    peer = find_peer(name, NULL, TRUE, FINDPEERS, FALSE, 0);
13615    if (!(peer && ast_apply_ha(peer->ha, sin))) {
13616       /* Peer fails ACL check */
13617       if (peer) {
13618          unref_peer(peer, "register_verify: unref_peer: from find_peer operation");
13619          peer = NULL;
13620          res = AUTH_ACL_FAILED;
13621       } else
13622          res = AUTH_NOT_FOUND;
13623    }
13624 
13625    if (peer) {
13626       /*! \todo OEJ Remove this - there's never RTP in a REGISTER dialog... */
13627       /* Set Frame packetization */
13628       if (p->rtp) {
13629          ast_rtp_codec_setpref(p->rtp, &peer->prefs);
13630          p->autoframing = peer->autoframing;
13631       }
13632       if (!peer->host_dynamic) {
13633          ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
13634          res = AUTH_PEER_NOT_DYNAMIC;
13635       } else {
13636          ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT);
13637          if (ast_test_flag(&p->flags[1], SIP_PAGE2_REGISTERTRYING))
13638             transmit_response(p, "100 Trying", req);
13639          if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri, XMIT_UNRELIABLE, req->ignore))) {
13640             if (sip_cancel_destroy(p))
13641                ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
13642 
13643             if (check_request_transport(peer, req)) {
13644                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
13645                transmit_response_with_date(p, "403 Forbidden", req);
13646                res = AUTH_BAD_TRANSPORT;
13647             } else {
13648 
13649                /* We have a successful registration attempt with proper authentication,
13650                   now, update the peer */
13651                switch (parse_register_contact(p, peer, req)) {
13652                case PARSE_REGISTER_DENIED:
13653                   ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
13654                   transmit_response_with_date(p, "603 Denied", req);
13655                   peer->lastmsgssent = -1;
13656                   res = 0;
13657                   break;
13658                case PARSE_REGISTER_FAILED:
13659                   ast_log(LOG_WARNING, "Failed to parse contact info\n");
13660                   transmit_response_with_date(p, "400 Bad Request", req);
13661                   peer->lastmsgssent = -1;
13662                   res = 0;
13663                   break;
13664                case PARSE_REGISTER_QUERY:
13665                   ast_string_field_set(p, fullcontact, peer->fullcontact);
13666                   transmit_response_with_date(p, "200 OK", req);
13667                   peer->lastmsgssent = -1;
13668                   res = 0;
13669                   break;
13670                case PARSE_REGISTER_UPDATE:
13671                   ast_string_field_set(p, fullcontact, peer->fullcontact);
13672                   update_peer(peer, p->expiry);
13673                   /* Say OK and ask subsystem to retransmit msg counter */
13674                   transmit_response_with_date(p, "200 OK", req);
13675                   if (!ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY))
13676                      peer->lastmsgssent = -1;
13677                   res = 0;
13678                   break;
13679                }
13680             }
13681 
13682          } 
13683       }
13684    }
13685    if (!peer && sip_cfg.autocreatepeer) {
13686       /* Create peer if we have autocreate mode enabled */
13687       peer = temp_peer(name);
13688       if (peer) {
13689          ao2_t_link(peers, peer, "link peer into peer table");
13690          if (peer->addr.sin_addr.s_addr) {
13691             ao2_t_link(peers_by_ip, peer, "link peer into peers-by-ip table");
13692          }
13693          
13694          if (sip_cancel_destroy(p))
13695             ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
13696          switch (parse_register_contact(p, peer, req)) {
13697          case PARSE_REGISTER_DENIED:
13698             ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
13699             transmit_response_with_date(p, "403 Forbidden (ACL)", req);
13700             peer->lastmsgssent = -1;
13701             res = 0;
13702             break;
13703          case PARSE_REGISTER_FAILED:
13704             ast_log(LOG_WARNING, "Failed to parse contact info\n");
13705             transmit_response_with_date(p, "400 Bad Request", req);
13706             peer->lastmsgssent = -1;
13707             res = 0;
13708             break;
13709          case PARSE_REGISTER_QUERY:
13710             ast_string_field_set(p, fullcontact, peer->fullcontact);
13711             transmit_response_with_date(p, "200 OK", req);
13712             peer->lastmsgssent = -1;
13713             res = 0;
13714             break;
13715          case PARSE_REGISTER_UPDATE:
13716             ast_string_field_set(p, fullcontact, peer->fullcontact);
13717             /* Say OK and ask subsystem to retransmit msg counter */
13718             transmit_response_with_date(p, "200 OK", req);
13719             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));
13720             peer->lastmsgssent = -1;
13721             res = 0;
13722             break;
13723          }
13724       }
13725    }
13726    if (!peer && sip_cfg.alwaysauthreject && ast_test_flag(&p->flags[1], SIP_PAGE2_REGISTERTRYING)) {
13727       /* If we found a peer, we transmit a 100 Trying.  Therefore, if we're
13728        * trying to avoid leaking information, we MUST also transmit the same
13729        * response when we DON'T find a peer. */
13730       transmit_response(p, "100 Trying", req);
13731       /* Insert a fake delay between the 100 and the subsequent failure. */
13732       sched_yield();
13733    }
13734    if (!res) {
13735       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
13736    }
13737    if (res < 0) {
13738       switch (res) {
13739       case AUTH_SECRET_FAILED:
13740          /* Wrong password in authentication. Go away, don't try again until you fixed it */
13741          transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
13742          if (global_authfailureevents)
13743             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", 
13744                name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13745          break;
13746       case AUTH_USERNAME_MISMATCH:
13747          /* Username and digest username does not match.
13748             Asterisk uses the From: username for authentication. We need the
13749             devices to use the same authentication user name until we support
13750             proper authentication by digest auth name */
13751       case AUTH_NOT_FOUND:
13752       case AUTH_PEER_NOT_DYNAMIC:
13753       case AUTH_ACL_FAILED:
13754          if (sip_cfg.alwaysauthreject) {
13755             transmit_fake_auth_response(p, SIP_REGISTER, &p->initreq, XMIT_UNRELIABLE);
13756             if (global_authfailureevents) {
13757                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",
13758                   name, res == AUTH_PEER_NOT_DYNAMIC ? "AUTH_PEER_NOT_DYNAMIC" : "URI_NOT_FOUND",
13759                   ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13760             }
13761          } else {
13762             /* URI not found */
13763             if (res == AUTH_PEER_NOT_DYNAMIC) {
13764                transmit_response(p, "403 Forbidden", &p->initreq);
13765                if (global_authfailureevents) {
13766                   manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
13767                      "ChannelType: SIP\r\n"
13768                      "Peer: SIP/%s\r\n"
13769                      "PeerStatus: Rejected\r\n"
13770                      "Cause: AUTH_PEER_NOT_DYNAMIC\r\n"
13771                      "Address: %s\r\n"
13772                      "Port: %d\r\n",
13773                      name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13774                }
13775             } else {
13776                transmit_response(p, "404 Not found", &p->initreq);
13777                if (global_authfailureevents) {
13778                   manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
13779                      "ChannelType: SIP\r\n"
13780                      "Peer: SIP/%s\r\n"
13781                      "PeerStatus: Rejected\r\n"
13782                      "Cause: %s\r\n"
13783                      "Address: %s\r\n"
13784                      "Port: %d\r\n",
13785                      name,
13786                      (res == AUTH_USERNAME_MISMATCH) ? "AUTH_USERNAME_MISMATCH" : "URI_NOT_FOUND",
13787                      ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13788                }
13789             }
13790          }
13791          break;
13792       case AUTH_BAD_TRANSPORT:
13793       default:
13794          break;
13795       }
13796    }
13797    if (peer)
13798       unref_peer(peer, "register_verify: unref_peer: tossing stack peer pointer at end of func");
13799 
13800    return res;
13801 }
13802 
13803 /*! \brief Translate referring cause */
13804 static void sip_set_redirstr(struct sip_pvt *p, char *reason) {
13805 
13806    if (!strcmp(reason, "unknown")) {
13807       ast_string_field_set(p, redircause, "UNKNOWN");
13808    } else if (!strcmp(reason, "user-busy")) {
13809       ast_string_field_set(p, redircause, "BUSY");
13810    } else if (!strcmp(reason, "no-answer")) {
13811       ast_string_field_set(p, redircause, "NOANSWER");
13812    } else if (!strcmp(reason, "unavailable")) {
13813       ast_string_field_set(p, redircause, "UNREACHABLE");
13814    } else if (!strcmp(reason, "unconditional")) {
13815       ast_string_field_set(p, redircause, "UNCONDITIONAL");
13816    } else if (!strcmp(reason, "time-of-day")) {
13817       ast_string_field_set(p, redircause, "UNKNOWN");
13818    } else if (!strcmp(reason, "do-not-disturb")) {
13819       ast_string_field_set(p, redircause, "UNKNOWN");
13820    } else if (!strcmp(reason, "deflection")) {
13821       ast_string_field_set(p, redircause, "UNKNOWN");
13822    } else if (!strcmp(reason, "follow-me")) {
13823       ast_string_field_set(p, redircause, "UNKNOWN");
13824    } else if (!strcmp(reason, "out-of-service")) {
13825       ast_string_field_set(p, redircause, "UNREACHABLE");
13826    } else if (!strcmp(reason, "away")) {
13827       ast_string_field_set(p, redircause, "UNREACHABLE");
13828    } else {
13829       ast_string_field_set(p, redircause, "UNKNOWN");
13830    }
13831 }
13832 
13833 /*! \brief Get referring dnis */
13834 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq)
13835 {
13836    char tmp[256], *exten, *rexten, *rdomain;
13837    char *params, *reason = NULL;
13838    struct sip_request *req;
13839    
13840    req = oreq ? oreq : &p->initreq;
13841 
13842    ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
13843    if (ast_strlen_zero(tmp))
13844       return 0;
13845 
13846    /*! \todo This function does not take user-parameters into consideration.
13847       First look for @, then start looking for ; to find uri-parameters.
13848    */
13849    params = strchr(tmp, ';');
13850 
13851    exten = get_in_brackets(tmp);
13852    if (!strncasecmp(exten, "sip:", 4)) {
13853       exten += 4;
13854    } else if (!strncasecmp(exten, "sips:", 5)) {
13855       exten += 5;
13856    } else {
13857       ast_log(LOG_WARNING, "Huh?  Not an RDNIS SIP header (%s)?\n", exten);
13858       return -1;
13859    }
13860 
13861    /* Get diversion-reason param if present */
13862    if (params) {
13863       *params = '\0';   /* Cut off parameters  */
13864       params++;
13865       while (*params == ';' || *params == ' ')
13866          params++;
13867       /* Check if we have a reason parameter */
13868       if ((reason = strcasestr(params, "reason="))) {
13869          reason+=7;
13870          /* Remove enclosing double-quotes */
13871          if (*reason == '"') 
13872             ast_strip_quoted(reason, "\"", "\"");
13873          if (!ast_strlen_zero(reason)) {
13874             sip_set_redirstr(p, reason);
13875             if (p->owner) {
13876                pbx_builtin_setvar_helper(p->owner, "__PRIREDIRECTREASON", p->redircause);
13877                pbx_builtin_setvar_helper(p->owner, "__SIPREDIRECTREASON", reason);
13878             }
13879          }
13880       }
13881    }
13882 
13883    rdomain = exten;
13884    rexten = strsep(&rdomain, "@");  /* trim anything after @ */
13885    if (p->owner) 
13886       pbx_builtin_setvar_helper(p->owner, "__SIPRDNISDOMAIN", rdomain);
13887 
13888    if (sip_debug_test_pvt(p))
13889       ast_verbose("RDNIS for this call is is %s (reason %s)\n", exten, reason ? reason : "");
13890 
13891    ast_string_field_set(p, rdnis, rexten);
13892 
13893    return 0;
13894 }
13895 
13896 /*! \brief Find out who the call is for.
13897    We use the request uri as a destination. 
13898    This code assumes authentication has been done, so that the
13899    device (peer/user) context is already set.
13900    \return 0 on success (found a matching extension),
13901    1 for pickup extension or overlap dialling support (if we support it),
13902    -1 on error.
13903 
13904   \note If the incoming uri is a SIPS: uri, we are required to carry this across
13905    the dialplan, so that the outbound call also is a sips: call or encrypted
13906    IAX2 call. If that's not available, the call should FAIL.
13907 */
13908 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
13909 {
13910    char tmp[256] = "", *uri, *a;
13911    char tmpf[256] = "", *from = NULL;
13912    struct sip_request *req;
13913    char *colon;
13914    char *decoded_uri;
13915    
13916    req = oreq;
13917    if (!req)
13918       req = &p->initreq;
13919 
13920    /* Find the request URI */
13921    if (req->rlPart2)
13922       ast_copy_string(tmp, REQ_OFFSET_TO_STR(req, rlPart2), sizeof(tmp));
13923    
13924    if (sip_cfg.pedanticsipchecking)
13925       ast_uri_decode(tmp);
13926 
13927    uri = get_in_brackets(tmp);
13928    
13929    if (!strncasecmp(uri, "sip:", 4)) {
13930       uri += 4;
13931    } else if (!strncasecmp(uri, "sips:", 5)) {
13932       uri += 5;
13933    } else {
13934       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", uri);
13935       return -1;
13936    }
13937 
13938    /* Now find the From: caller ID and name */
13939    /* XXX Why is this done in get_destination? Isn't it already done?
13940       Needs to be checked 
13941         */
13942    ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
13943    if (!ast_strlen_zero(tmpf)) {
13944       if (sip_cfg.pedanticsipchecking)
13945          ast_uri_decode(tmpf);
13946       from = get_in_brackets(tmpf);
13947    } 
13948    
13949    if (!ast_strlen_zero(from)) {
13950       if (!strncasecmp(from, "sip:", 4)) {
13951          from += 4;
13952       } else if (!strncasecmp(from, "sips:", 5)) {
13953          from += 5;
13954       } else {
13955          ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", from);
13956          return -1;
13957       }
13958       if ((a = strchr(from, '@')))
13959          *a++ = '\0';
13960       else
13961          a = from;   /* just a domain */
13962       from = strsep(&from, ";"); /* Remove userinfo options */
13963       a = strsep(&a, ";");    /* Remove URI options */
13964       ast_string_field_set(p, fromdomain, a);
13965    }
13966 
13967    /* Skip any options and find the domain */
13968 
13969    /* Get the target domain */
13970    if ((a = strchr(uri, '@'))) {
13971       *a++ = '\0';
13972    } else { /* No username part */
13973       a = uri;
13974       uri = "s";  /* Set extension to "s" */
13975    }
13976    colon = strchr(a, ':'); /* Remove :port */
13977    if (colon)
13978       *colon = '\0';
13979 
13980    uri = strsep(&uri, ";");   /* Remove userinfo options */
13981    a = strsep(&a, ";");    /* Remove URI options */
13982 
13983    ast_string_field_set(p, domain, a);
13984 
13985    if (!AST_LIST_EMPTY(&domain_list)) {
13986       char domain_context[AST_MAX_EXTENSION];
13987 
13988       domain_context[0] = '\0';
13989       if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
13990          if (!sip_cfg.allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
13991             ast_debug(1, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
13992             return -2;
13993          }
13994       }
13995       /* If we don't have a peer (i.e. we're a guest call),
13996        * overwrite the original context */
13997       if (!ast_test_flag(&p->flags[1], SIP_PAGE2_HAVEPEERCONTEXT) && !ast_strlen_zero(domain_context))
13998          ast_string_field_set(p, context, domain_context);
13999    }
14000 
14001    /* If the request coming in is a subscription and subscribecontext has been specified use it */
14002    if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext))
14003       ast_string_field_set(p, context, p->subscribecontext);
14004 
14005    if (sip_debug_test_pvt(p))
14006       ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
14007 
14008    /* Since extensions.conf can have unescaped characters, try matching a
14009     * decoded uri in addition to the non-decoded uri. */
14010    decoded_uri = ast_strdupa(uri);
14011    ast_uri_decode(decoded_uri);
14012 
14013    /* If this is a subscription we actually just need to see if a hint exists for the extension */
14014    if (req->method == SIP_SUBSCRIBE) {
14015       char hint[AST_MAX_EXTENSION];
14016       int which = 0;
14017       if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, uri) ||
14018           (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, decoded_uri) && (which = 1))) {
14019          if (!oreq) {
14020             ast_string_field_set(p, exten, which ? decoded_uri : uri);
14021          }
14022          return 0;
14023       } else {
14024          return -1;
14025       }
14026    } else {
14027       int which = 0;
14028       /* Check the dialplan for the username part of the request URI,
14029          the domain will be stored in the SIPDOMAIN variable
14030          Return 0 if we have a matching extension */
14031       if (ast_exists_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from)) ||
14032           (ast_exists_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from)) && (which = 1)) ||
14033           !strcmp(decoded_uri, ast_pickup_ext())) {
14034          if (!oreq) {
14035             ast_string_field_set(p, exten, which ? decoded_uri : uri);
14036          }
14037          return 0;
14038       }
14039    }
14040 
14041    /* Return 1 for pickup extension or overlap dialling support (if we support it) */
14042    if((ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) && 
14043        ast_canmatch_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))) ||
14044        !strncmp(decoded_uri, ast_pickup_ext(), strlen(decoded_uri))) {
14045       return 1;
14046    }
14047    
14048    return -1;
14049 }
14050 
14051 /*! \brief Lock dialog lock and find matching pvt lock  
14052    \return a reference, remember to release it when done 
14053 */
14054 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag) 
14055 {
14056    struct sip_pvt *sip_pvt_ptr;
14057    struct sip_pvt tmp_dialog = {
14058       .callid = callid,
14059    };
14060 
14061    if (totag)
14062       ast_debug(4, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
14063 
14064    /* Search dialogs and find the match */
14065    
14066    sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find of dialog in dialogs table");
14067    if (sip_pvt_ptr) {
14068       /* Go ahead and lock it (and its owner) before returning */
14069       sip_pvt_lock(sip_pvt_ptr);
14070       if (sip_cfg.pedanticsipchecking) {
14071          unsigned char frommismatch = 0, tomismatch = 0;
14072 
14073          if (ast_strlen_zero(fromtag)) {
14074             sip_pvt_unlock(sip_pvt_ptr);
14075             ast_debug(4, "Matched %s call for callid=%s - no from tag specified, pedantic check fails\n",
14076                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
14077             return NULL;
14078          }
14079 
14080          if (ast_strlen_zero(totag)) {
14081             sip_pvt_unlock(sip_pvt_ptr);
14082             ast_debug(4, "Matched %s call for callid=%s - no to tag specified, pedantic check fails\n",
14083                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
14084             return NULL;
14085          }
14086          /* RFC 3891
14087           * > 3.  User Agent Server Behavior: Receiving a Replaces Header
14088           * > The Replaces header contains information used to match an existing
14089           * > SIP dialog (call-id, to-tag, and from-tag).  Upon receiving an INVITE
14090           * > with a Replaces header, the User Agent (UA) attempts to match this
14091           * > information with a confirmed or early dialog.  The User Agent Server
14092           * > (UAS) matches the to-tag and from-tag parameters as if they were tags
14093           * > present in an incoming request.  In other words, the to-tag parameter
14094           * > is compared to the local tag, and the from-tag parameter is compared
14095           * > to the remote tag.
14096           *
14097           * Thus, the totag is always compared to the local tag, regardless if
14098           * this our call is an incoming or outgoing call.
14099           */
14100          frommismatch = !!strcmp(fromtag, sip_pvt_ptr->theirtag);
14101          tomismatch = !!strcmp(totag, sip_pvt_ptr->tag);
14102 
14103          if (frommismatch || tomismatch) {
14104             sip_pvt_unlock(sip_pvt_ptr);
14105             if (frommismatch) {
14106                ast_debug(4, "Matched %s call for callid=%s - pedantic from tag check fails; their tag is %s our tag is %s\n",
14107                     sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid, 
14108                     fromtag, sip_pvt_ptr->theirtag);
14109             }
14110             if (tomismatch) {
14111                ast_debug(4, "Matched %s call for callid=%s - pedantic to tag check fails; their tag is %s our tag is %s\n",
14112                     sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid, 
14113                     totag, sip_pvt_ptr->tag);
14114             }
14115             return NULL;
14116          }
14117       }
14118       
14119       if (totag)
14120          ast_debug(4, "Matched %s call - their tag is %s Our tag is %s\n",
14121                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING",
14122                  sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
14123 
14124       /* deadlock avoidance... */
14125       while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
14126          sip_pvt_unlock(sip_pvt_ptr);
14127          usleep(1);
14128          sip_pvt_lock(sip_pvt_ptr);
14129       }
14130    }
14131    
14132    return sip_pvt_ptr;
14133 }
14134 
14135 /*! \brief Call transfer support (the REFER method) 
14136  *    Extracts Refer headers into pvt dialog structure 
14137  *
14138  * \note If we get a SIPS uri in the refer-to header, we're required to set up a secure signalling path
14139  * to that extension. As a minimum, this needs to be added to a channel variable, if not a channel
14140  * flag.
14141  */
14142 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
14143 {
14144 
14145    const char *p_referred_by = NULL;
14146    char *h_refer_to = NULL; 
14147    char *h_referred_by = NULL;
14148    char *refer_to;
14149    const char *p_refer_to;
14150    char *referred_by_uri = NULL;
14151    char *ptr;
14152    struct sip_request *req = NULL;
14153    const char *transfer_context = NULL;
14154    struct sip_refer *referdata;
14155 
14156 
14157    req = outgoing_req;
14158    referdata = transferer->refer;
14159 
14160    if (!req)
14161       req = &transferer->initreq;
14162 
14163    p_refer_to = get_header(req, "Refer-To");
14164    if (ast_strlen_zero(p_refer_to)) {
14165       ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
14166       return -2;  /* Syntax error */
14167    }
14168    h_refer_to = ast_strdupa(p_refer_to);
14169    refer_to = get_in_brackets(h_refer_to);
14170    if (sip_cfg.pedanticsipchecking)
14171       ast_uri_decode(refer_to);
14172 
14173    if (!strncasecmp(refer_to, "sip:", 4)) {
14174       refer_to += 4;       /* Skip sip: */
14175    } else if (!strncasecmp(refer_to, "sips:", 5)) {
14176       refer_to += 5;
14177    } else {
14178       ast_log(LOG_WARNING, "Can't transfer to non-sip: URI.  (Refer-to: %s)?\n", refer_to);
14179       return -3;
14180    }
14181 
14182    /* Get referred by header if it exists */
14183    p_referred_by = get_header(req, "Referred-By");
14184 
14185    /* Give useful transfer information to the dialplan */
14186    if (transferer->owner) {
14187       struct ast_channel *peer = ast_bridged_channel(transferer->owner);
14188       if (peer) {
14189          pbx_builtin_setvar_helper(peer, "SIPREFERRINGCONTEXT", transferer->context);
14190          pbx_builtin_setvar_helper(peer, "SIPREFERREDBYHDR", p_referred_by);
14191       }
14192    }
14193 
14194    if (!ast_strlen_zero(p_referred_by)) {
14195       char *lessthan;
14196       h_referred_by = ast_strdupa(p_referred_by);
14197       if (sip_cfg.pedanticsipchecking)
14198          ast_uri_decode(h_referred_by);
14199 
14200       /* Store referrer's caller ID name */
14201       ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
14202       if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
14203          *(lessthan - 1) = '\0'; /* Space */
14204       }
14205 
14206       referred_by_uri = get_in_brackets(h_referred_by);
14207       if (!strncasecmp(referred_by_uri, "sip:", 4)) {
14208          referred_by_uri += 4;      /* Skip sip: */
14209       } else if (!strncasecmp(referred_by_uri, "sips:", 5)) {
14210          referred_by_uri += 5;      /* Skip sips: */
14211       } else {
14212          ast_log(LOG_WARNING, "Huh?  Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
14213          referred_by_uri = NULL;
14214       }
14215    }
14216 
14217    /* Check for arguments in the refer_to header */
14218    if ((ptr = strcasestr(refer_to, "replaces="))) {
14219       char *to = NULL, *from = NULL;
14220       
14221       /* This is an attended transfer */
14222       referdata->attendedtransfer = 1;
14223       ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
14224       ast_uri_decode(referdata->replaces_callid);
14225       if ((ptr = strchr(referdata->replaces_callid, ';')))  /* Find options */ {
14226          *ptr++ = '\0';
14227       }
14228       
14229       if (ptr) {
14230          /* Find the different tags before we destroy the string */
14231          to = strcasestr(ptr, "to-tag=");
14232          from = strcasestr(ptr, "from-tag=");
14233       }
14234       
14235       /* Grab the to header */
14236       if (to) {
14237          ptr = to + 7;
14238          if ((to = strchr(ptr, '&')))
14239             *to = '\0';
14240          if ((to = strchr(ptr, ';')))
14241             *to = '\0';
14242          ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
14243       }
14244       
14245       if (from) {
14246          ptr = from + 9;
14247          if ((to = strchr(ptr, '&')))
14248             *to = '\0';
14249          if ((to = strchr(ptr, ';')))
14250             *to = '\0';
14251          ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
14252       }
14253 
14254       if (!strcmp(referdata->replaces_callid, transferer->callid) &&
14255          (!sip_cfg.pedanticsipchecking ||
14256          (!strcmp(referdata->replaces_callid_fromtag, transferer->theirtag) &&
14257          !strcmp(referdata->replaces_callid_totag, transferer->tag)))) {
14258             ast_log(LOG_WARNING, "Got an attempt to replace own Call-ID on %s\n", transferer->callid);
14259             return -4;
14260       }
14261 
14262       if (!sip_cfg.pedanticsipchecking)
14263          ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
14264       else
14265          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>" );
14266    }
14267    
14268    if ((ptr = strchr(refer_to, '@'))) {   /* Separate domain */
14269       char *urioption = NULL, *domain;
14270       *ptr++ = '\0';
14271 
14272       if ((urioption = strchr(ptr, ';'))) /* Separate urioptions */
14273          *urioption++ = '\0';
14274       
14275       domain = ptr;
14276       if ((ptr = strchr(domain, ':'))) /* Remove :port */
14277          *ptr = '\0';
14278       
14279       /* Save the domain for the dial plan */
14280       ast_copy_string(referdata->refer_to_domain, domain, sizeof(referdata->refer_to_domain));
14281       if (urioption)
14282          ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
14283    }
14284 
14285    if ((ptr = strchr(refer_to, ';')))  /* Remove options */
14286       *ptr = '\0';
14287    ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
14288    
14289    if (referred_by_uri) {
14290       if ((ptr = strchr(referred_by_uri, ';')))    /* Remove options */
14291          *ptr = '\0';
14292       ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
14293    } else {
14294       referdata->referred_by[0] = '\0';
14295    }
14296 
14297    /* Determine transfer context */
14298    if (transferer->owner)  /* Mimic behaviour in res_features.c */
14299       transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
14300 
14301    /* By default, use the context in the channel sending the REFER */
14302    if (ast_strlen_zero(transfer_context)) {
14303       transfer_context = S_OR(transferer->owner->macrocontext,
14304                S_OR(transferer->context, sip_cfg.default_context));
14305    }
14306 
14307    ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
14308    
14309    /* Either an existing extension or the parking extension */
14310    if (referdata->attendedtransfer || ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
14311       if (sip_debug_test_pvt(transferer)) {
14312          ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
14313       }
14314       /* We are ready to transfer to the extension */
14315       return 0;
14316    } 
14317    if (sip_debug_test_pvt(transferer))
14318       ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
14319 
14320    /* Failure, we can't find this extension */
14321    return -1;
14322 }
14323 
14324 
14325 /*! \brief Call transfer support (old way, deprecated by the IETF)
14326  * \note does not account for SIPS: uri requirements, nor check transport
14327  */
14328 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
14329 {
14330    char tmp[256] = "", *c, *a;
14331    struct sip_request *req = oreq ? oreq : &p->initreq;
14332    struct sip_refer *referdata = NULL;
14333    const char *transfer_context = NULL;
14334    
14335    if (!p->refer && !sip_refer_allocate(p))
14336       return -1;
14337 
14338    referdata = p->refer;
14339 
14340    ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
14341    c = get_in_brackets(tmp);
14342 
14343    if (sip_cfg.pedanticsipchecking)
14344       ast_uri_decode(c);
14345 
14346    if (!strncasecmp(c, "sip:", 4)) {
14347       c += 4;
14348    } else if (!strncasecmp(c, "sips:", 5)) {
14349       c += 5;
14350    } else {
14351       ast_log(LOG_WARNING, "Huh?  Not a SIP header in Also: transfer (%s)?\n", c);
14352       return -1;
14353    }
14354 
14355    if ((a = strchr(c, ';')))  /* Remove arguments */
14356       *a = '\0';
14357    
14358    if ((a = strchr(c, '@'))) {   /* Separate Domain */
14359       *a++ = '\0';
14360       ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
14361    }
14362    
14363    if (sip_debug_test_pvt(p))
14364       ast_verbose("Looking for %s in %s\n", c, p->context);
14365 
14366    if (p->owner)  /* Mimic behaviour in res_features.c */
14367       transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
14368 
14369    /* By default, use the context in the channel sending the REFER */
14370    if (ast_strlen_zero(transfer_context)) {
14371       transfer_context = S_OR(p->owner->macrocontext,
14372                S_OR(p->context, sip_cfg.default_context));
14373    }
14374    if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
14375       /* This is a blind transfer */
14376       ast_debug(1, "SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
14377       ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
14378       ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
14379       ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
14380       referdata->refer_call = dialog_unref(referdata->refer_call, "unreffing referdata->refer_call");
14381       /* Set new context */
14382       ast_string_field_set(p, context, transfer_context);
14383       return 0;
14384    } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
14385       return 1;
14386    }
14387 
14388    return -1;
14389 }
14390 
14391 /*! \brief check received= and rport= in a SIP response.
14392  * If we get a response with received= and/or rport= in the Via:
14393  * line, use them as 'p->ourip' (see RFC 3581 for rport,
14394  * and RFC 3261 for received).
14395  * Using these two fields SIP can produce the correct
14396  * address and port in the SIP headers without the need for STUN.
14397  * The address part is also reused for the media sessions.
14398  * Note that ast_sip_ouraddrfor() still rewrites p->ourip
14399  * if you specify externip/seternaddr/stunaddr.
14400  */
14401 static attribute_unused void check_via_response(struct sip_pvt *p, struct sip_request *req)
14402 {
14403    char via[256];
14404    char *cur, *opts;
14405 
14406    ast_copy_string(via, get_header(req, "Via"), sizeof(via));
14407 
14408    /* Work on the leftmost value of the topmost Via header */
14409    opts = strchr(via, ',');
14410    if (opts)
14411       *opts = '\0';
14412 
14413    /* parse all relevant options */
14414    opts = strchr(via, ';');
14415    if (!opts)
14416       return;  /* no options to parse */
14417    *opts++ = '\0';
14418    while ( (cur = strsep(&opts, ";")) ) {
14419       if (!strncmp(cur, "rport=", 6)) {
14420          int port = strtol(cur+6, NULL, 10);
14421          /* XXX add error checking */
14422          p->ourip.sin_port = ntohs(port);
14423       } else if (!strncmp(cur, "received=", 9)) {
14424          if (ast_parse_arg(cur+9, PARSE_INADDR, &p->ourip))
14425             ;  /* XXX add error checking */
14426       }
14427    }
14428 }
14429 
14430 /*! \brief check Via: header for hostname, port and rport request/answer */
14431 static void check_via(struct sip_pvt *p, struct sip_request *req)
14432 {
14433    char via[512];
14434    char *c, *pt, *maddr;
14435    struct hostent *hp;
14436    struct ast_hostent ahp;
14437 
14438    ast_copy_string(via, get_header(req, "Via"), sizeof(via));
14439 
14440    /* Work on the leftmost value of the topmost Via header */
14441    c = strchr(via, ',');
14442    if (c)
14443       *c = '\0';
14444 
14445    /* Check for rport */
14446    c = strstr(via, ";rport");
14447    if (c && (c[6] != '=')) /* rport query, not answer */
14448       ast_set_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT);
14449 
14450    /* Check for maddr */
14451    maddr = strstr(via, "maddr=");
14452    if (maddr) {
14453       maddr += 6;
14454       c = maddr + strspn(maddr, "0123456789.");
14455       *c = '\0';
14456    }
14457 
14458    c = strchr(via, ';');
14459    if (c)
14460       *c = '\0';
14461 
14462    c = strchr(via, ' ');
14463    if (c) {
14464       *c = '\0';
14465       c = ast_skip_blanks(c+1);
14466       if (strcasecmp(via, "SIP/2.0/UDP") && strcasecmp(via, "SIP/2.0/TCP") && strcasecmp(via, "SIP/2.0/TLS")) {
14467          ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
14468          return;
14469       }
14470       pt = strchr(c, ':');
14471       if (pt)
14472          *pt++ = '\0';  /* remember port pointer */
14473       /* Use maddr if found */
14474       if (maddr)
14475          c = maddr;
14476       hp = ast_gethostbyname(c, &ahp);
14477       if (!hp) {
14478          ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
14479          return;
14480       }
14481       memset(&p->sa, 0, sizeof(p->sa));
14482       p->sa.sin_family = AF_INET;
14483       memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
14484       p->sa.sin_port = htons(port_str2int(pt, STANDARD_SIP_PORT));
14485 
14486       if (sip_debug_test_pvt(p)) {
14487          const struct sockaddr_in *dst = sip_real_dst(p);
14488          ast_verbose("Sending to %s : %d (%s)\n", ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), sip_nat_mode(p));
14489       }
14490    }
14491 }
14492 
14493 /*! \brief  Get caller id name from SIP headers */
14494 static char *get_calleridname(const char *input, char *output, size_t outputsize)
14495 {
14496    const char *end = strchr(input, '<');  /* first_bracket */
14497    const char *tmp = strchr(input, '"');  /* first quote */
14498    int bytes = 0;
14499    int maxbytes = outputsize - 1;
14500 
14501    if (!end || end == input)  /* we require a part in brackets */
14502       return NULL;
14503 
14504    end--; /* move just before "<" */
14505 
14506    if (tmp && tmp <= end) {
14507       /* The quote (tmp) precedes the bracket (end+1).
14508        * Find the matching quote and return the content.
14509        */
14510       end = strchr(tmp+1, '"');
14511       if (!end)
14512          return NULL;
14513       bytes = (int) (end - tmp);
14514       /* protect the output buffer */
14515       if (bytes > maxbytes)
14516          bytes = maxbytes;
14517       ast_copy_string(output, tmp + 1, bytes);
14518    } else {
14519       /* No quoted string, or it is inside brackets. */
14520       /* clear the empty characters in the begining*/
14521       input = ast_skip_blanks(input);
14522       /* clear the empty characters in the end */
14523       while(*end && *end < 33 && end > input)
14524          end--;
14525       if (end >= input) {
14526          bytes = (int) (end - input) + 2;
14527          /* protect the output buffer */
14528          if (bytes > maxbytes)
14529             bytes = maxbytes;
14530          ast_copy_string(output, input, bytes);
14531       } else
14532          return NULL;
14533    }
14534    return output;
14535 }
14536 
14537 /*! \brief  Get caller id number from Remote-Party-ID header field 
14538  * Returns true if number should be restricted (privacy setting found)
14539  * output is set to NULL if no number found
14540  */
14541 static int get_rpid_num(const char *input, char *output, int maxlen)
14542 {
14543    char *start;
14544    char *end;
14545 
14546    start = strchr(input, ':');
14547    if (!start) {
14548       output[0] = '\0';
14549       return 0;
14550    }
14551    start++;
14552 
14553    /* we found "number" */
14554    ast_copy_string(output, start, maxlen);
14555    output[maxlen-1] = '\0';
14556 
14557    end = strchr(output, '@');
14558    if (end)
14559       *end = '\0';
14560    else
14561       output[0] = '\0';
14562    if (strstr(input, "privacy=full") || strstr(input, "privacy=uri"))
14563       return AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
14564 
14565    return 0;
14566 }
14567 
14568 
14569 /*! \brief helper function for check_{user|peer}_ok() */
14570 static void replace_cid(struct sip_pvt *p, const char *rpid_num, const char *calleridname)
14571 {
14572    /* replace callerid if rpid found, and not restricted */
14573    if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
14574       char *tmp = ast_strdupa(rpid_num); /* XXX the copy can be done later */
14575       if (!ast_strlen_zero(calleridname))
14576          ast_string_field_set(p, cid_name, calleridname);
14577       if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
14578          ast_shrink_phone_number(tmp);
14579       ast_string_field_set(p, cid_num, tmp);
14580    }
14581 }
14582 
14583 /*! \brief Validate device authentication */
14584 static enum check_auth_result check_peer_ok(struct sip_pvt *p, char *of,
14585    struct sip_request *req, int sipmethod, struct sockaddr_in *sin,
14586    struct sip_peer **authpeer,
14587    enum xmittype reliable,
14588    char *rpid_num, char *calleridname, char *uri2)
14589 {
14590    enum check_auth_result res;
14591    int debug=sip_debug_test_addr(sin);
14592    struct sip_peer *peer;
14593 
14594    if (sipmethod == SIP_SUBSCRIBE) {
14595       /* For subscribes, match on device name only; for other methods,
14596       * match on IP address-port of the incoming request.
14597       */
14598       peer = find_peer(of, NULL, TRUE, FINDALLDEVICES, FALSE, 0);
14599    } else {
14600       /* First find devices based on username (avoid all type=peer's) */
14601       peer = find_peer(of, NULL, TRUE, FINDUSERS, FALSE, 0);
14602 
14603       /* Then find devices based on IP */
14604       if (!peer) {
14605          peer = find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
14606       }
14607    }
14608 
14609    if (!peer) {
14610       if (debug)
14611          ast_verbose("No matching peer for '%s' from '%s:%d'\n",
14612             of, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
14613       return AUTH_DONT_KNOW;
14614    }
14615    if (!ast_apply_ha(peer->ha, sin)) {
14616       ast_debug(2, "Found peer '%s' for '%s', but fails host access\n", peer->name, of);
14617       unref_peer(peer, "unref_peer: check_peer_ok: from find_peer call, early return of AUTH_ACL_FAILED");
14618       return AUTH_ACL_FAILED;
14619    }
14620    if (debug)
14621       ast_verbose("Found peer '%s' for '%s' from %s:%d\n",
14622          peer->name, of, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
14623 
14624    /* XXX what about p->prefs = peer->prefs; ? */
14625    /* Set Frame packetization */
14626    if (p->rtp) {
14627       ast_rtp_codec_setpref(p->rtp, &peer->prefs);
14628       p->autoframing = peer->autoframing;
14629    }
14630 
14631    /* Take the peer */
14632    ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
14633    ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
14634 
14635    if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && p->udptl) {
14636       p->t38_maxdatagram = peer->t38_maxdatagram;
14637       set_t38_capabilities(p);
14638    }
14639 
14640    /* Copy SIP extensions profile to peer */
14641    /* XXX is this correct before a successful auth ? */
14642    if (p->sipoptions)
14643       peer->sipoptions = p->sipoptions;
14644 
14645    replace_cid(p, rpid_num, calleridname);
14646    do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE));
14647 
14648    ast_string_field_set(p, peersecret, peer->secret);
14649    ast_string_field_set(p, peermd5secret, peer->md5secret);
14650    ast_string_field_set(p, subscribecontext, peer->subscribecontext);
14651    ast_string_field_set(p, mohinterpret, peer->mohinterpret);
14652    ast_string_field_set(p, mohsuggest, peer->mohsuggest);
14653    ast_string_field_set(p, parkinglot, peer->parkinglot);
14654    if (peer->callingpres)  /* Peer calling pres setting will override RPID */
14655       p->callingpres = peer->callingpres;
14656    if (peer->maxms && peer->lastms)
14657       p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
14658    else
14659       p->timer_t1 = peer->timer_t1;
14660  
14661    /* Set timer B to control transaction timeouts */
14662    if (peer->timer_b)
14663       p->timer_b = peer->timer_b;
14664    else
14665       p->timer_b = 64 * p->timer_t1;
14666  
14667    if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
14668       /* Pretend there is no required authentication */
14669       ast_string_field_set(p, peersecret, NULL);
14670       ast_string_field_set(p, peermd5secret, NULL);
14671    }
14672    if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, req->ignore))) {
14673       ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
14674       ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
14675       /* If we have a call limit, set flag */
14676       if (peer->call_limit)
14677          ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
14678       ast_string_field_set(p, peername, peer->name);
14679       ast_string_field_set(p, authname, peer->name);
14680 
14681       if (sipmethod == SIP_INVITE) {
14682          /* copy channel vars */
14683          p->chanvars = copy_vars(peer->chanvars);
14684       }
14685 
14686       if (authpeer) {
14687          ao2_t_ref(peer, 1, "copy pointer into (*authpeer)");
14688          (*authpeer) = peer;  /* Add a ref to the object here, to keep it in memory a bit longer if it is realtime */
14689       }
14690 
14691       if (!ast_strlen_zero(peer->username)) {
14692          ast_string_field_set(p, username, peer->username);
14693          /* Use the default username for authentication on outbound calls */
14694          /* XXX this takes the name from the caller... can we override ? */
14695          ast_string_field_set(p, authname, peer->username);
14696       }
14697       if (!ast_strlen_zero(peer->cid_num)) {
14698          char *tmp = ast_strdupa(peer->cid_num);
14699          if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
14700             ast_shrink_phone_number(tmp);
14701          ast_string_field_set(p, cid_num, tmp);
14702       }
14703       if (!ast_strlen_zero(peer->cid_name)) 
14704          ast_string_field_set(p, cid_name, peer->cid_name);
14705       ast_string_field_set(p, fullcontact, peer->fullcontact);
14706       if (!ast_strlen_zero(peer->context))
14707          ast_string_field_set(p, context, peer->context);
14708       ast_string_field_set(p, peersecret, peer->secret);
14709       ast_string_field_set(p, peermd5secret, peer->md5secret);
14710       ast_string_field_set(p, language, peer->language);
14711       ast_string_field_set(p, accountcode, peer->accountcode);
14712       p->amaflags = peer->amaflags;
14713       p->callgroup = peer->callgroup;
14714       p->pickupgroup = peer->pickupgroup;
14715       p->capability = peer->capability;
14716       p->prefs = peer->prefs;
14717       p->jointcapability = peer->capability;
14718       if (p->peercapability)
14719          p->jointcapability &= p->peercapability;
14720       p->maxcallbitrate = peer->maxcallbitrate;
14721       if (!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) &&
14722             (!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
14723                !(p->capability & AST_FORMAT_VIDEO_MASK)) &&
14724             p->vrtp) {
14725          ast_rtp_destroy(p->vrtp);
14726          p->vrtp = NULL;
14727       }
14728       if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) || !(p->capability & AST_FORMAT_TEXT_MASK)) && p->trtp) {
14729          ast_rtp_destroy(p->trtp);
14730          p->trtp = NULL;
14731       }
14732       if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
14733           (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
14734          p->noncodeccapability |= AST_RTP_DTMF;
14735       else
14736          p->noncodeccapability &= ~AST_RTP_DTMF;
14737       p->jointnoncodeccapability = p->noncodeccapability;
14738    }
14739    unref_peer(peer, "check_peer_ok: unref_peer: tossing temp ptr to peer from find_peer");
14740    return res;
14741 }
14742 
14743 
14744 /*! \brief  Check if matching user or peer is defined 
14745    Match user on From: user name and peer on IP/port
14746    This is used on first invite (not re-invites) and subscribe requests 
14747     \return 0 on success, non-zero on failure
14748 */
14749 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
14750                      int sipmethod, char *uri, enum xmittype reliable,
14751                      struct sockaddr_in *sin, struct sip_peer **authpeer)
14752 {
14753    char from[256];
14754    char *dummy;   /* dummy return value for parse_uri */
14755    char *domain;  /* dummy return value for parse_uri */
14756    char *of;
14757    char rpid_num[50];
14758    const char *rpid;
14759    enum check_auth_result res;
14760    char calleridname[50];
14761    char *uri2 = ast_strdupa(uri);
14762 
14763    terminate_uri(uri2); /* trim extra stuff */
14764 
14765    ast_copy_string(from, get_header(req, "From"), sizeof(from));
14766    if (sip_cfg.pedanticsipchecking)
14767       ast_uri_decode(from);
14768    /* XXX here tries to map the username for invite things */
14769    memset(calleridname, 0, sizeof(calleridname));
14770    get_calleridname(from, calleridname, sizeof(calleridname));
14771    if (calleridname[0])
14772       ast_string_field_set(p, cid_name, calleridname);
14773 
14774    rpid = get_header(req, "Remote-Party-ID");
14775    memset(rpid_num, 0, sizeof(rpid_num));
14776    if (!ast_strlen_zero(rpid)) 
14777       p->callingpres = get_rpid_num(rpid, rpid_num, sizeof(rpid_num));
14778 
14779    of = get_in_brackets(from);
14780    if (ast_strlen_zero(p->exten)) {
14781       char *t = uri2;
14782       if (!strncasecmp(t, "sip:", 4))
14783          t+= 4;
14784       else if (!strncasecmp(t, "sips:", 5))
14785          t += 5;
14786       ast_string_field_set(p, exten, t);
14787       t = strchr(p->exten, '@');
14788       if (t)
14789          *t = '\0';
14790       if (ast_strlen_zero(p->our_contact))
14791          build_contact(p);
14792    }
14793    /* save the URI part of the From header */
14794    ast_string_field_set(p, from, of);
14795 
14796    /* ignore all fields but name */
14797    if (parse_uri(of, "sip:,sips:", &of, &dummy, &domain, &dummy, &dummy, NULL)) {
14798       ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
14799    }
14800 
14801    if (ast_strlen_zero(of)) {
14802       /* XXX note: the original code considered a missing @host
14803        * as a username-only URI. The SIP RFC (19.1.1) says that
14804        * this is wrong, and it should be considered as a domain-only URI.
14805        * For backward compatibility, we keep this block, but it is
14806        * really a mistake and should go away.
14807        */
14808       of = domain;
14809    } else {
14810       char *tmp = ast_strdupa(of);
14811       /* We need to be able to handle auth-headers looking like
14812          <sip:8164444422;phone-context=+1@1.2.3.4:5060;user=phone;tag=SDadkoa01-gK0c3bdb43>
14813       */
14814       tmp = strsep(&tmp, ";");
14815       if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
14816          ast_shrink_phone_number(tmp);
14817       ast_string_field_set(p, cid_num, tmp);
14818    }
14819 
14820    if (global_match_auth_username) {
14821       /*
14822        * XXX This is experimental code to grab the search key from the
14823        * Auth header's username instead of the 'From' name, if available.
14824        * Do not enable this block unless you understand the side effects (if any!)
14825        * Note, the search for "username" should be done in a more robust way.
14826        * Note2, at the moment we check both fields, though maybe we should
14827        * pick one or another depending on the request ? XXX
14828        */
14829       const char *hdr = get_header(req, "Authorization");
14830       if (ast_strlen_zero(hdr))
14831          hdr = get_header(req, "Proxy-Authorization");
14832 
14833       if ( !ast_strlen_zero(hdr) && (hdr = strstr(hdr, "username=\"")) ) {
14834          ast_copy_string(from, hdr + strlen("username=\""), sizeof(from));
14835          of = from;
14836          of = strsep(&of, "\"");
14837       }
14838    }
14839 
14840    res = check_peer_ok(p, of, req, sipmethod, sin,
14841          authpeer, reliable, rpid_num, calleridname, uri2);
14842    if (res != AUTH_DONT_KNOW)
14843       return res;
14844 
14845    /* Finally, apply the guest policy */
14846    if (sip_cfg.allowguest) {
14847       replace_cid(p, rpid_num, calleridname);
14848       res = AUTH_SUCCESSFUL;
14849    } else if (sip_cfg.alwaysauthreject)
14850       res = AUTH_FAKE_AUTH; /* reject with fake authorization request */
14851    else
14852       res = AUTH_SECRET_FAILED; /* we don't want any guests, authentication will fail */
14853 
14854 
14855    if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT)) {
14856       ast_set_flag(&p->flags[0], SIP_NAT_ROUTE);
14857    }
14858 
14859    return res;
14860 }
14861 
14862 /*! \brief  Find user 
14863    If we get a match, this will add a reference pointer to the user object in ASTOBJ, that needs to be unreferenced
14864 */
14865 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin)
14866 {
14867    return check_user_full(p, req, sipmethod, uri, reliable, sin, NULL);
14868 }
14869 
14870 /*! \brief  Get text out of a SIP MESSAGE packet */
14871 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline)
14872 {
14873    int x;
14874    int y;
14875 
14876    buf[0] = '\0';
14877    /*XXX isn't strlen(buf) going to always be 0? */
14878    y = len - strlen(buf) - 5;
14879    if (y < 0)
14880       y = 0;
14881    for (x = 0; x < req->lines; x++) {
14882       char *line = REQ_OFFSET_TO_STR(req, line[x]);
14883       strncat(buf, line, y); /* safe */
14884       y -= strlen(line) + 1;
14885       if (y < 0)
14886          y = 0;
14887       if (y != 0 && addnewline)
14888          strcat(buf, "\n"); /* safe */
14889    }
14890    return 0;
14891 }
14892 
14893 
14894 /*! \brief  Receive SIP MESSAGE method messages
14895 \note We only handle messages within current calls currently 
14896    Reference: RFC 3428 */
14897 static void receive_message(struct sip_pvt *p, struct sip_request *req)
14898 {
14899    char buf[1400];   
14900    struct ast_frame f;
14901    const char *content_type = get_header(req, "Content-Type");
14902 
14903    if (strncmp(content_type, "text/plain", strlen("text/plain"))) { /* No text/plain attachment */
14904       transmit_response(p, "415 Unsupported Media Type", req); /* Good enough, or? */
14905       if (!p->owner)
14906          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14907       return;
14908    }
14909 
14910    if (get_msg_text(buf, sizeof(buf), req, FALSE)) {
14911       ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
14912       transmit_response(p, "202 Accepted", req);
14913       if (!p->owner)
14914          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14915       return;
14916    }
14917 
14918    if (p->owner) {
14919       if (sip_debug_test_pvt(p))
14920          ast_verbose("SIP Text message received: '%s'\n", buf);
14921       memset(&f, 0, sizeof(f));
14922       f.frametype = AST_FRAME_TEXT;
14923       f.subclass = 0;
14924       f.offset = 0;
14925       f.data.ptr = buf;
14926       f.datalen = strlen(buf) + 1;
14927       ast_queue_frame(p->owner, &f);
14928       transmit_response(p, "202 Accepted", req); /* We respond 202 accepted, since we relay the message */
14929       return;
14930    }
14931 
14932    /* Message outside of a call, we do not support that */
14933    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);
14934    transmit_response(p, "405 Method Not Allowed", req);
14935    sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14936    return;
14937 }
14938 
14939 /*! \brief  CLI Command to show calls within limits set by call_limit */
14940 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14941 {
14942 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
14943 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
14944    char ilimits[40];
14945    char iused[40];
14946    int showall = FALSE;
14947    struct ao2_iterator i;
14948    struct sip_peer *peer;
14949    
14950    switch (cmd) {
14951    case CLI_INIT:
14952       e->command = "sip show inuse";
14953       e->usage =
14954          "Usage: sip show inuse [all]\n"
14955          "       List all SIP devices usage counters and limits.\n"
14956          "       Add option \"all\" to show all devices, not only those with a limit.\n";
14957       return NULL;
14958    case CLI_GENERATE:
14959       return NULL;
14960    }
14961 
14962    if (a->argc < 3) 
14963       return CLI_SHOWUSAGE;
14964 
14965    if (a->argc == 4 && !strcmp(a->argv[3], "all")) 
14966       showall = TRUE;
14967    
14968    ast_cli(a->fd, FORMAT, "* Peer name", "In use", "Limit");
14969 
14970    i = ao2_iterator_init(peers, 0);
14971    while ((peer = ao2_t_iterator_next(&i, "iterate thru peer table"))) {
14972       ao2_lock(peer);
14973       if (peer->call_limit)
14974          snprintf(ilimits, sizeof(ilimits), "%d", peer->call_limit);
14975       else 
14976          ast_copy_string(ilimits, "N/A", sizeof(ilimits));
14977       snprintf(iused, sizeof(iused), "%d/%d/%d", peer->inUse, peer->inRinging, peer->onHold);
14978       if (showall || peer->call_limit)
14979          ast_cli(a->fd, FORMAT2, peer->name, iused, ilimits);
14980       ao2_unlock(peer);
14981       unref_peer(peer, "toss iterator pointer");
14982    }
14983    ao2_iterator_destroy(&i);
14984 
14985    return CLI_SUCCESS;
14986 #undef FORMAT
14987 #undef FORMAT2
14988 }
14989 
14990 
14991 /*! \brief Convert transfer mode to text string */
14992 static char *transfermode2str(enum transfermodes mode)
14993 {
14994    if (mode == TRANSFER_OPENFORALL)
14995       return "open";
14996    else if (mode == TRANSFER_CLOSED)
14997       return "closed";
14998    return "strict";
14999 }
15000 
15001 static struct _map_x_s natmodes[] = {
15002    { SIP_NAT_NEVER,        "No"},
15003    { SIP_NAT_ROUTE,        "Route"},
15004    { SIP_NAT_ALWAYS,       "Always"},
15005    { SIP_NAT_RFC3581,      "RFC3581"},
15006    { -1,                   NULL}, /* terminator */
15007 };
15008 
15009 /*! \brief  Convert NAT setting to text string */
15010 static const char *nat2str(int nat)
15011 {
15012    return map_x_s(natmodes, nat, "Unknown");
15013 }
15014 
15015 #ifdef NOTUSED
15016 /* OEJ: This is not used, but may be useful in the future, so I don't want to 
15017    delete it. Keeping it enabled generates compiler warnings.
15018  */
15019 
15020 static struct _map_x_s natcfgmodes[] = {
15021    { SIP_NAT_NEVER,        "never"},
15022    { SIP_NAT_ROUTE,        "route"},
15023    { SIP_NAT_ALWAYS,       "yes"},
15024    { SIP_NAT_RFC3581,      "no"},
15025    { -1,                   NULL}, /* terminator */
15026 };
15027 
15028 /*! \brief  Convert NAT setting to text string appropriate for config files */
15029 static const char *nat2strconfig(int nat)
15030 {
15031    return map_x_s(natcfgmodes, nat, "Unknown");
15032 }
15033 #endif
15034 
15035 /*! \brief  Report Peer status in character string
15036  *  \return 0 if peer is unreachable, 1 if peer is online, -1 if unmonitored
15037  */
15038 
15039 
15040 /* Session-Timer Modes */
15041 static struct _map_x_s stmodes[] = {
15042         { SESSION_TIMER_MODE_ACCEPT,    "Accept"},
15043         { SESSION_TIMER_MODE_ORIGINATE, "Originate"},
15044         { SESSION_TIMER_MODE_REFUSE,    "Refuse"},
15045         { -1,                           NULL},
15046 };
15047 
15048 static const char *stmode2str(enum st_mode m)
15049 {
15050    return map_x_s(stmodes, m, "Unknown");
15051 }
15052 
15053 static enum st_mode str2stmode(const char *s)
15054 {
15055    return map_s_x(stmodes, s, -1);
15056 }
15057 
15058 /* Session-Timer Refreshers */
15059 static struct _map_x_s strefreshers[] = {
15060         { SESSION_TIMER_REFRESHER_AUTO,     "auto"},
15061         { SESSION_TIMER_REFRESHER_UAC,      "uac"},
15062         { SESSION_TIMER_REFRESHER_UAS,      "uas"},
15063         { -1,                               NULL},
15064 };
15065 
15066 static const char *strefresher2str(enum st_refresher r)
15067 {
15068    return map_x_s(strefreshers, r, "Unknown");
15069 }
15070 
15071 static enum st_refresher str2strefresher(const char *s)
15072 {
15073    return map_s_x(strefreshers, s, -1);
15074 }
15075 
15076 
15077 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
15078 {
15079    int res = 0;
15080    if (peer->maxms) {
15081       if (peer->lastms < 0) {
15082          ast_copy_string(status, "UNREACHABLE", statuslen);
15083       } else if (peer->lastms > peer->maxms) {
15084          snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
15085          res = 1;
15086       } else if (peer->lastms) {
15087          snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
15088          res = 1;
15089       } else {
15090          ast_copy_string(status, "UNKNOWN", statuslen);
15091       }
15092    } else { 
15093       ast_copy_string(status, "Unmonitored", statuslen);
15094       /* Checking if port is 0 */
15095       res = -1;
15096    }
15097    return res;
15098 }
15099 
15100 /*! \brief return Yes or No depending on the argument.
15101  * This is used in many places in CLI command, having a function to generate
15102  * this helps maintaining a consistent output (and possibly emitting the
15103  * output in other languages, at some point).
15104  */
15105 static const char *cli_yesno(int x)
15106 {
15107    return x ? "Yes" : "No";
15108 }
15109 
15110 /*! \brief  Show active TCP connections */
15111 static char *sip_show_tcp(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15112 {
15113    struct sip_threadinfo *th;
15114    struct ao2_iterator i;
15115 
15116 #define FORMAT2 "%-30.30s %3.6s %9.9s %6.6s\n"
15117 #define FORMAT  "%-30.30s %-6d %-9.9s %-6.6s\n"
15118 
15119    switch (cmd) {
15120    case CLI_INIT:
15121       e->command = "sip show tcp";
15122       e->usage =
15123          "Usage: sip show tcp\n"
15124          "       Lists all active TCP/TLS sessions.\n";
15125       return NULL;
15126    case CLI_GENERATE:
15127       return NULL;
15128    }
15129 
15130    if (a->argc != 3)
15131       return CLI_SHOWUSAGE;
15132 
15133    ast_cli(a->fd, FORMAT2, "Host", "Port", "Transport", "Type");
15134    i = ao2_iterator_init(threadt, 0);
15135    while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
15136       ast_cli(a->fd, FORMAT, ast_inet_ntoa(th->tcptls_session->remote_address.sin_addr), 
15137          ntohs(th->tcptls_session->remote_address.sin_port), 
15138          get_transport(th->type), 
15139          (th->tcptls_session->client ? "Client" : "Server"));
15140       ao2_t_ref(th, -1, "decrement ref from iterator");
15141    }
15142    ao2_iterator_destroy(&i);
15143    return CLI_SUCCESS;
15144 #undef FORMAT
15145 #undef FORMAT2
15146 }
15147 
15148 /*! \brief  CLI Command 'SIP Show Users' */
15149 static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15150 {
15151    regex_t regexbuf;
15152    int havepattern = FALSE;
15153    struct ao2_iterator user_iter;
15154    struct sip_peer *user;
15155 
15156 #define FORMAT  "%-25.25s  %-15.15s  %-15.15s  %-15.15s  %-5.5s%-10.10s\n"
15157 
15158    switch (cmd) {
15159    case CLI_INIT:
15160       e->command = "sip show users";
15161       e->usage =
15162          "Usage: sip show users [like <pattern>]\n"
15163          "       Lists all known SIP users.\n"
15164          "       Optional regular expression pattern is used to filter the user list.\n";
15165       return NULL;
15166    case CLI_GENERATE:
15167       return NULL;
15168    }
15169 
15170    switch (a->argc) {
15171    case 5:
15172       if (!strcasecmp(a->argv[3], "like")) {
15173          if (regcomp(&regexbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
15174             return CLI_SHOWUSAGE;
15175          havepattern = TRUE;
15176       } else
15177          return CLI_SHOWUSAGE;
15178    case 3:
15179       break;
15180    default:
15181       return CLI_SHOWUSAGE;
15182    }
15183 
15184    ast_cli(a->fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "NAT");
15185 
15186    user_iter = ao2_iterator_init(peers, 0);
15187    while ((user = ao2_t_iterator_next(&user_iter, "iterate thru peers table"))) {
15188       ao2_lock(user);
15189       if (!(user->type & SIP_TYPE_USER)) {
15190          ao2_unlock(user);
15191          unref_peer(user, "sip show users");
15192          continue;
15193       }
15194 
15195       if (havepattern && regexec(&regexbuf, user->name, 0, NULL, 0)) {
15196          ao2_unlock(user);
15197          unref_peer(user, "sip show users");
15198          continue;
15199       }
15200 
15201       ast_cli(a->fd, FORMAT, user->name, 
15202          user->secret, 
15203          user->accountcode,
15204          user->context,
15205          cli_yesno(user->ha != NULL),
15206          nat2str(ast_test_flag(&user->flags[0], SIP_NAT)));
15207       ao2_unlock(user);
15208       unref_peer(user, "sip show users");
15209    }
15210    ao2_iterator_destroy(&user_iter);
15211 
15212    if (havepattern)
15213       regfree(&regexbuf);
15214 
15215    return CLI_SUCCESS;
15216 #undef FORMAT
15217 }
15218 
15219 /*! \brief Manager Action SIPShowRegistry description */
15220 static char mandescr_show_registry[] =
15221 "Description: Lists all registration requests and status\n"
15222 "Registrations will follow as separate events. followed by a final event called\n"
15223 "RegistrationsComplete.\n"
15224 "Variables: \n"
15225 "  ActionID: <id>       Action ID for this transaction. Will be returned.\n";
15226 
15227 /*! \brief Show SIP registrations in the manager API */
15228 static int manager_show_registry(struct mansession *s, const struct message *m)
15229 {
15230    const char *id = astman_get_header(m, "ActionID");
15231    char idtext[256] = "";
15232    int total = 0;
15233 
15234    if (!ast_strlen_zero(id))
15235       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
15236 
15237    astman_send_listack(s, m, "Registrations will follow", "start");
15238 
15239    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
15240       ASTOBJ_RDLOCK(iterator);
15241       astman_append(s,
15242          "Event: RegistryEntry\r\n"
15243          "%s"
15244          "Host: %s\r\n"
15245          "Port: %d\r\n"
15246          "Username: %s\r\n"
15247          "Refresh: %d\r\n"
15248          "State: %s\r\n"
15249          "RegistrationTime: %ld\r\n"
15250          "\r\n", idtext, iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT,
15251                  iterator->username, iterator->refresh, regstate2str(iterator->regstate), (long) iterator->regtime.tv_sec);
15252       ASTOBJ_UNLOCK(iterator);
15253       total++;
15254    } while(0));
15255 
15256    astman_append(s,
15257       "Event: RegistrationsComplete\r\n"
15258       "EventList: Complete\r\n"
15259       "ListItems: %d\r\n"
15260       "%s"
15261       "\r\n", total, idtext);
15262    
15263    return 0;
15264 }
15265 
15266 static char mandescr_show_peers[] = 
15267 "Description: Lists SIP peers in text format with details on current status.\n"
15268 "Peerlist will follow as separate events, followed by a final event called\n"
15269 "PeerlistComplete.\n"
15270 "Variables: \n"
15271 "  ActionID: <id> Action ID for this transaction. Will be returned.\n";
15272 
15273 /*! \brief  Show SIP peers in the manager API */
15274 /*    Inspired from chan_iax2 */
15275 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
15276 {
15277    const char *id = astman_get_header(m, "ActionID");
15278    const char *a[] = {"sip", "show", "peers"};
15279    char idtext[256] = "";
15280    int total = 0;
15281 
15282    if (!ast_strlen_zero(id))
15283       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
15284 
15285    astman_send_listack(s, m, "Peer status list will follow", "start");
15286    /* List the peers in separate manager events */
15287    _sip_show_peers(-1, &total, s, m, 3, a);
15288    /* Send final confirmation */
15289    astman_append(s,
15290    "Event: PeerlistComplete\r\n"
15291    "EventList: Complete\r\n"
15292    "ListItems: %d\r\n"
15293    "%s"
15294    "\r\n", total, idtext);
15295    return 0;
15296 }
15297 
15298 /*! \brief  CLI Show Peers command */
15299 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15300 {
15301    switch (cmd) {
15302    case CLI_INIT:
15303       e->command = "sip show peers";
15304       e->usage =
15305          "Usage: sip show peers [like <pattern>]\n"
15306          "       Lists all known SIP peers.\n"
15307          "       Optional regular expression pattern is used to filter the peer list.\n";
15308       return NULL;
15309    case CLI_GENERATE:
15310       return NULL;
15311    }
15312 
15313    return _sip_show_peers(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
15314 }
15315 
15316 int peercomparefunc(const void *a, const void *b);
15317 
15318 int peercomparefunc(const void *a, const void *b)
15319 {
15320    struct sip_peer **ap = (struct sip_peer **)a;
15321    struct sip_peer **bp = (struct sip_peer **)b;
15322    return strcmp((*ap)->name, (*bp)->name);
15323 }
15324 
15325 
15326 /*! \brief Execute sip show peers command */
15327 static char *_sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
15328 {
15329    regex_t regexbuf;
15330    int havepattern = FALSE;
15331    struct sip_peer *peer;
15332    struct ao2_iterator i;
15333    
15334 /* the last argument is left-aligned, so we don't need a size anyways */
15335 #define FORMAT2 "%-25.25s  %-15.15s %-3.3s %-3.3s %-3.3s %-8s %-10s %s\n"
15336 #define FORMAT  "%-25.25s  %-15.15s %-3.3s %-3.3s %-3.3s %-8d %-10s %s\n"
15337 
15338    char name[256];
15339    int total_peers = 0;
15340    int peers_mon_online = 0;
15341    int peers_mon_offline = 0;
15342    int peers_unmon_offline = 0;
15343    int peers_unmon_online = 0;
15344    const char *id;
15345    char idtext[256] = "";
15346    int realtimepeers;
15347    int objcount = ao2_container_count(peers);
15348    struct sip_peer **peerarray;
15349    int k;
15350    
15351    
15352    realtimepeers = ast_check_realtime("sippeers");
15353    peerarray = ast_calloc(sizeof(struct sip_peer *), objcount);
15354 
15355    if (s) { /* Manager - get ActionID */
15356       id = astman_get_header(m, "ActionID");
15357       if (!ast_strlen_zero(id))
15358          snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
15359    }
15360 
15361    switch (argc) {
15362    case 5:
15363       if (!strcasecmp(argv[3], "like")) {
15364          if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
15365             return CLI_SHOWUSAGE;
15366          havepattern = TRUE;
15367       } else
15368          return CLI_SHOWUSAGE;
15369    case 3:
15370       break;
15371    default:
15372       return CLI_SHOWUSAGE;
15373    }
15374 
15375    if (!s) /* Normal list */
15376       ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Nat", "ACL", "Port", "Status", (realtimepeers ? "Realtime" : ""));
15377    
15378 
15379    i = ao2_iterator_init(peers, 0);
15380    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {  
15381       ao2_lock(peer);
15382 
15383       if (!(peer->type & SIP_TYPE_PEER)) {
15384          ao2_unlock(peer);
15385          unref_peer(peer, "unref peer because it's actually a user");
15386          continue;
15387       }
15388 
15389       if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0)) {
15390          objcount--;
15391          ao2_unlock(peer);
15392          unref_peer(peer, "toss iterator peer ptr before continue");
15393          continue;
15394       }
15395 
15396       peerarray[total_peers++] = peer;
15397       ao2_unlock(peer);
15398    }
15399    ao2_iterator_destroy(&i);
15400    
15401    qsort(peerarray, total_peers, sizeof(struct sip_peer *), peercomparefunc);
15402 
15403    for(k=0; k < total_peers; k++) {
15404       char status[20] = "";
15405       char srch[2000];
15406       char pstatus;
15407       peer = peerarray[k];
15408       
15409       ao2_lock(peer);
15410       if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0)) {
15411          ao2_unlock(peer);
15412          peer = peerarray[k] = unref_peer(peer, "toss iterator peer ptr before continue");
15413          continue;
15414       }
15415 
15416       if (!ast_strlen_zero(peer->username) && !s)
15417          snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
15418       else
15419          ast_copy_string(name, peer->name, sizeof(name));
15420       
15421       pstatus = peer_status(peer, status, sizeof(status));
15422       if (pstatus == 1)
15423          peers_mon_online++;
15424       else if (pstatus == 0)
15425          peers_mon_offline++;
15426       else {
15427          if (peer->addr.sin_port == 0)
15428             peers_unmon_offline++;
15429          else
15430             peers_unmon_online++;
15431       }
15432 
15433       snprintf(srch, sizeof(srch), FORMAT, name,
15434          peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
15435          peer->host_dynamic ? " D " : "   ",    /* Dynamic or not? */
15436          ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? " N " : "   ", /* NAT=yes? */
15437          peer->ha ? " A " : "   ",  /* permit/deny */
15438          ntohs(peer->addr.sin_port), status,
15439          realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
15440 
15441       if (!s)  {/* Normal CLI list */
15442          ast_cli(fd, FORMAT, name, 
15443          peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
15444          peer->host_dynamic ? " D " : "   ",    /* Dynamic or not? */
15445          ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? " N " : "   ", /* NAT=yes? */
15446          peer->ha ? " A " : "   ",       /* permit/deny */
15447          
15448          ntohs(peer->addr.sin_port), status,
15449          realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
15450       } else { /* Manager format */
15451          /* The names here need to be the same as other channels */
15452          astman_append(s, 
15453          "Event: PeerEntry\r\n%s"
15454          "Channeltype: SIP\r\n"
15455          "ObjectName: %s\r\n"
15456          "ChanObjectType: peer\r\n" /* "peer" or "user" */
15457          "IPaddress: %s\r\n"
15458          "IPport: %d\r\n"
15459          "Dynamic: %s\r\n"
15460          "Natsupport: %s\r\n"
15461          "VideoSupport: %s\r\n"
15462          "TextSupport: %s\r\n"
15463          "ACL: %s\r\n"
15464          "Status: %s\r\n"
15465          "RealtimeDevice: %s\r\n\r\n", 
15466          idtext,
15467          peer->name, 
15468          peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "-none-",
15469          ntohs(peer->addr.sin_port), 
15470          peer->host_dynamic ? "yes" : "no",  /* Dynamic or not? */
15471          ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? "yes" : "no",  /* NAT=yes? */
15472          ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no",  /* VIDEOSUPPORT=yes? */
15473          ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "yes" : "no",   /* TEXTSUPPORT=yes? */
15474          peer->ha ? "yes" : "no",       /* permit/deny */
15475          status,
15476          realtimepeers ? (peer->is_realtime ? "yes":"no") : "no");
15477       }
15478       ao2_unlock(peer);
15479       peer = peerarray[k] = unref_peer(peer, "toss iterator peer ptr");
15480    }
15481    
15482    if (!s)
15483       ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
15484               total_peers, peers_mon_online, peers_mon_offline, peers_unmon_online, peers_unmon_offline);
15485 
15486    if (havepattern)
15487       regfree(&regexbuf);
15488 
15489    if (total)
15490       *total = total_peers;
15491    
15492    ast_free(peerarray);
15493    
15494    return CLI_SUCCESS;
15495 #undef FORMAT
15496 #undef FORMAT2
15497 }
15498 
15499 static int peer_dump_func(void *userobj, void *arg, int flags)
15500 {
15501    struct sip_peer *peer = userobj;
15502    int refc = ao2_t_ref(userobj, 0, "");
15503    int *fd = arg;
15504    
15505    ast_cli(*fd, "name: %s\ntype: peer\nobjflags: %d\nrefcount: %d\n\n", 
15506           peer->name, 0, refc);
15507    return 0;
15508 }
15509 
15510 static int dialog_dump_func(void *userobj, void *arg, int flags)
15511 {
15512    struct sip_pvt *pvt = userobj;
15513    int refc = ao2_t_ref(userobj, 0, "");
15514    int *fd = arg;
15515    
15516    ast_cli(*fd, "name: %s\ntype: dialog\nobjflags: %d\nrefcount: %d\n\n", 
15517           pvt->callid, 0, refc);
15518    return 0;
15519 }
15520 
15521 
15522 /*! \brief List all allocated SIP Objects (realtime or static) */
15523 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15524 {
15525    char tmp[256];
15526    
15527    switch (cmd) {
15528    case CLI_INIT:
15529       e->command = "sip show objects";
15530       e->usage =
15531          "Usage: sip show objects\n"
15532          "       Lists status of known SIP objects\n";
15533       return NULL;
15534    case CLI_GENERATE:
15535       return NULL;
15536    }  
15537 
15538    if (a->argc != 3)
15539       return CLI_SHOWUSAGE;
15540    ast_cli(a->fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
15541    ao2_t_callback(peers, OBJ_NODATA, peer_dump_func, &a->fd, "initiate ao2_callback to dump peers");
15542    ast_cli(a->fd, "-= Peer objects by IP =-\n\n"); 
15543    ao2_t_callback(peers_by_ip, OBJ_NODATA, peer_dump_func, &a->fd, "initiate ao2_callback to dump peers_by_ip");
15544    ast_cli(a->fd, "-= Registry objects: %d =-\n\n", regobjs);
15545    ASTOBJ_CONTAINER_DUMP(a->fd, tmp, sizeof(tmp), &regl);
15546    ast_cli(a->fd, "-= Dialog objects:\n\n");
15547    ao2_t_callback(dialogs, OBJ_NODATA, dialog_dump_func, &a->fd, "initiate ao2_callback to dump dialogs");
15548    return CLI_SUCCESS;
15549 }
15550 /*! \brief Print call group and pickup group */
15551 static void  print_group(int fd, ast_group_t group, int crlf)
15552 {
15553    char buf[256];
15554    ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
15555 }
15556 
15557 /*! \brief mapping between dtmf flags and strings */
15558 static struct _map_x_s dtmfstr[] = {
15559    { SIP_DTMF_RFC2833,     "rfc2833" },
15560    { SIP_DTMF_INFO,        "info" },
15561    { SIP_DTMF_SHORTINFO,   "shortinfo" },
15562    { SIP_DTMF_INBAND,      "inband" },
15563    { SIP_DTMF_AUTO,        "auto" },
15564    { -1,                   NULL }, /* terminator */
15565 };
15566 
15567 /*! \brief Convert DTMF mode to printable string */
15568 static const char *dtmfmode2str(int mode)
15569 {
15570    return map_x_s(dtmfstr, mode, "<error>");
15571 }
15572 
15573 /*! \brief maps a string to dtmfmode, returns -1 on error */
15574 static int str2dtmfmode(const char *str)
15575 {
15576    return map_s_x(dtmfstr, str, -1);
15577 }
15578 
15579 static struct _map_x_s insecurestr[] = {
15580    { SIP_INSECURE_PORT,    "port" },
15581    { SIP_INSECURE_INVITE,  "invite" },
15582    { SIP_INSECURE_PORT | SIP_INSECURE_INVITE, "port,invite" },
15583    { 0,                    "no" },
15584    { -1,                   NULL }, /* terminator */
15585 };
15586 
15587 /*! \brief Convert Insecure setting to printable string */
15588 static const char *insecure2str(int mode)
15589 {
15590    return map_x_s(insecurestr, mode, "<error>");
15591 }
15592 
15593 /*! \brief Destroy disused contexts between reloads
15594    Only used in reload_config so the code for regcontext doesn't get ugly
15595 */
15596 static void cleanup_stale_contexts(char *new, char *old)
15597 {
15598    char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
15599 
15600    while ((oldcontext = strsep(&old, "&"))) {
15601       stalecontext = '\0';
15602       ast_copy_string(newlist, new, sizeof(newlist));
15603       stringp = newlist;
15604       while ((newcontext = strsep(&stringp, "&"))) {
15605          if (!strcmp(newcontext, oldcontext)) {
15606             /* This is not the context you're looking for */
15607             stalecontext = '\0';
15608             break;
15609          } else if (strcmp(newcontext, oldcontext)) {
15610             stalecontext = oldcontext;
15611          }
15612          
15613       }
15614       if (stalecontext)
15615          ast_context_destroy(ast_context_find(stalecontext), "SIP");
15616    }
15617 }
15618 
15619 /*! 
15620  * \brief Match dialogs that need to be destroyed
15621  *
15622  * \details This is used with ao2_callback to unlink/delete all dialogs that
15623  * are marked needdestroy. It will return CMP_MATCH for candidates, and they
15624  * will be unlinked.
15625  *
15626  * \todo Re-work this to improve efficiency.  Currently, this function is called
15627  * on _every_ dialog after processing _every_ incoming SIP/UDP packet, or
15628  * potentially even more often when the scheduler has entries to run.
15629  */
15630 
15631 static int dialog_needdestroy(void *dialogobj, void *arg, int flags) 
15632 {
15633    struct sip_pvt *dialog = dialogobj;
15634    time_t *t = arg;
15635 
15636    if (sip_pvt_trylock(dialog)) {
15637       /* Don't block the monitor thread.  This function is called often enough
15638        * that we can wait for the next time around. */
15639       return 0;
15640    }
15641    
15642    /* Check RTP timeouts and kill calls if we have a timeout set and do not get RTP */
15643    check_rtp_timeout(dialog, *t);
15644 
15645    /* If we have sessions that needs to be destroyed, do it now */
15646    /* Check if we have outstanding requests not responsed to or an active call
15647       - if that's the case, wait with destruction */
15648    if (dialog->needdestroy && !dialog->packets && !dialog->owner) {
15649       /* We absolutely cannot destroy the rtp struct while a bridge is active or we WILL crash */
15650       if (dialog->rtp && ast_rtp_get_bridged(dialog->rtp)) {
15651          ast_debug(2, "Bridge still active.  Delaying destruction of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
15652          sip_pvt_unlock(dialog);
15653          return 0;
15654       }
15655       
15656       if (dialog->vrtp && ast_rtp_get_bridged(dialog->vrtp)) {
15657          ast_debug(2, "Bridge still active.  Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
15658          sip_pvt_unlock(dialog);
15659          return 0;
15660       }
15661 
15662       sip_pvt_unlock(dialog);
15663       /* no, the unlink should handle this: dialog_unref(dialog, "needdestroy: one more refcount decrement to allow dialog to be destroyed"); */
15664       /* the CMP_MATCH will unlink this dialog from the dialog hash table */
15665       dialog_unlink_all(dialog, TRUE, FALSE);
15666       return 0; /* the unlink_all should unlink this from the table, so.... no need to return a match */
15667    }
15668 
15669    sip_pvt_unlock(dialog);
15670 
15671    return 0;
15672 }
15673 
15674 /*! \brief Remove temporary realtime objects from memory (CLI) */
15675 /*! \todo XXXX Propably needs an overhaul after removal of the devices */
15676 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15677 {
15678    struct sip_peer *peer, *pi;
15679    int prunepeer = FALSE;
15680    int multi = FALSE;
15681    char *name = NULL;
15682    regex_t regexbuf;
15683    int havepattern = 0;
15684    struct ao2_iterator i;
15685    static char *choices[] = { "all", "like", NULL };
15686    char *cmplt;
15687    
15688    if (cmd == CLI_INIT) {
15689       e->command = "sip prune realtime [peer|all]";
15690       e->usage =
15691          "Usage: sip prune realtime [peer [<name>|all|like <pattern>]|all]\n"
15692          "       Prunes object(s) from the cache.\n"
15693          "       Optional regular expression pattern is used to filter the objects.\n";
15694       return NULL;
15695    } else if (cmd == CLI_GENERATE) {
15696       if (a->pos == 4 && !strcasecmp(a->argv[3], "peer")) {
15697          cmplt = ast_cli_complete(a->word, choices, a->n);
15698          if (!cmplt)
15699             cmplt = complete_sip_peer(a->word, a->n - sizeof(choices), SIP_PAGE2_RTCACHEFRIENDS);
15700          return cmplt;
15701       }
15702       if (a->pos == 5 && !strcasecmp(a->argv[4], "like"))
15703          return complete_sip_peer(a->word, a->n, SIP_PAGE2_RTCACHEFRIENDS);
15704       return NULL;
15705    }
15706    switch (a->argc) {
15707    case 4:
15708       name = a->argv[3];
15709       /* we accept a name in position 3, but keywords are not good. */
15710       if (!strcasecmp(name, "peer") || !strcasecmp(name, "like"))
15711          return CLI_SHOWUSAGE;
15712       prunepeer = TRUE;
15713       if (!strcasecmp(name, "all")) {
15714          multi = TRUE;
15715          name = NULL;
15716       }
15717       /* else a single name, already set */
15718       break;
15719    case 5:
15720       /* sip prune realtime {peer|like} name */
15721       name = a->argv[4];
15722       if (!strcasecmp(a->argv[3], "peer"))
15723          prunepeer = TRUE;
15724       else if (!strcasecmp(a->argv[3], "like")) {
15725          prunepeer = TRUE;
15726          multi = TRUE;
15727       } else
15728          return CLI_SHOWUSAGE;
15729       if (!strcasecmp(name, "like"))
15730          return CLI_SHOWUSAGE;
15731       if (!multi && !strcasecmp(name, "all")) {
15732          multi = TRUE;
15733          name = NULL;
15734       }
15735       break;
15736    case 6:
15737       name = a->argv[5];
15738       multi = TRUE;
15739       /* sip prune realtime {peer} like name */
15740       if (strcasecmp(a->argv[4], "like"))
15741          return CLI_SHOWUSAGE;
15742       if (!strcasecmp(a->argv[3], "peer")) {
15743          prunepeer = TRUE;
15744       } else
15745          return CLI_SHOWUSAGE;
15746       break;
15747    default:
15748       return CLI_SHOWUSAGE;
15749    }
15750 
15751    if (multi && name) {
15752       if (regcomp(&regexbuf, name, REG_EXTENDED | REG_NOSUB)) {
15753          return CLI_SHOWUSAGE;
15754       }
15755       havepattern = 1;
15756    }
15757 
15758    if (multi) {
15759       if (prunepeer) {
15760          int pruned = 0;
15761          
15762          i = ao2_iterator_init(peers, 0);
15763          while ((pi = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
15764             ao2_lock(pi);
15765             if (name && regexec(&regexbuf, pi->name, 0, NULL, 0)) {
15766                unref_peer(pi, "toss iterator peer ptr before continue");
15767                ao2_unlock(pi);
15768                continue;
15769             };
15770             if (ast_test_flag(&pi->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
15771                pi->the_mark = 1;
15772                pruned++;
15773             }
15774             ao2_unlock(pi);
15775             unref_peer(pi, "toss iterator peer ptr");
15776          }
15777          ao2_iterator_destroy(&i);
15778          if (pruned) {
15779             unlink_marked_peers_from_tables();
15780             ast_cli(a->fd, "%d peers pruned.\n", pruned);
15781          } else
15782             ast_cli(a->fd, "No peers found to prune.\n");
15783       }
15784    } else {
15785       if (prunepeer) {
15786          struct sip_peer tmp;
15787          ast_copy_string(tmp.name, name, sizeof(tmp.name));
15788          if ((peer = ao2_t_find(peers, &tmp, OBJ_POINTER | OBJ_UNLINK, "finding to unlink from peers"))) {
15789             if (peer->addr.sin_addr.s_addr) {
15790                ao2_t_unlink(peers_by_ip, peer, "unlinking peer from peers_by_ip also");
15791             }
15792             if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
15793                ast_cli(a->fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
15794                /* put it back! */
15795                ao2_t_link(peers, peer, "link peer into peer table");
15796                if (peer->addr.sin_addr.s_addr) {
15797                   ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
15798                }
15799                
15800             } else
15801                ast_cli(a->fd, "Peer '%s' pruned.\n", name);
15802             unref_peer(peer, "sip_prune_realtime: unref_peer: tossing temp peer ptr");
15803          } else
15804             ast_cli(a->fd, "Peer '%s' not found.\n", name);
15805       }
15806    }
15807 
15808    if (havepattern) {
15809       regfree(&regexbuf);
15810    }
15811 
15812    return CLI_SUCCESS;
15813 }
15814 
15815 /*! \brief Print codec list from preference to CLI/manager */
15816 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
15817 {
15818    int x, codec;
15819 
15820    for(x = 0; x < 32 ; x++) {
15821       codec = ast_codec_pref_index(pref, x);
15822       if (!codec)
15823          break;
15824       ast_cli(fd, "%s", ast_getformatname(codec));
15825       ast_cli(fd, ":%d", pref->framing[x]);
15826       if (x < 31 && ast_codec_pref_index(pref, x + 1))
15827          ast_cli(fd, ",");
15828    }
15829    if (!x)
15830       ast_cli(fd, "none");
15831 }
15832 
15833 /*! \brief Print domain mode to cli */
15834 static const char *domain_mode_to_text(const enum domain_mode mode)
15835 {
15836    switch (mode) {
15837    case SIP_DOMAIN_AUTO:
15838       return "[Automatic]";
15839    case SIP_DOMAIN_CONFIG:
15840       return "[Configured]";
15841    }
15842 
15843    return "";
15844 }
15845 
15846 /*! \brief CLI command to list local domains */
15847 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15848 {
15849    struct domain *d;
15850 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
15851 
15852    switch (cmd) {
15853    case CLI_INIT:
15854       e->command = "sip show domains";
15855       e->usage =
15856          "Usage: sip show domains\n"
15857          "       Lists all configured SIP local domains.\n"
15858          "       Asterisk only responds to SIP messages to local domains.\n";
15859       return NULL;
15860    case CLI_GENERATE:
15861       return NULL;
15862    }
15863 
15864    if (AST_LIST_EMPTY(&domain_list)) {
15865       ast_cli(a->fd, "SIP Domain support not enabled.\n\n");
15866       return CLI_SUCCESS;
15867    } else {
15868       ast_cli(a->fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
15869       AST_LIST_LOCK(&domain_list);
15870       AST_LIST_TRAVERSE(&domain_list, d, list)
15871          ast_cli(a->fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
15872             domain_mode_to_text(d->mode));
15873       AST_LIST_UNLOCK(&domain_list);
15874       ast_cli(a->fd, "\n");
15875       return CLI_SUCCESS;
15876    }
15877 }
15878 #undef FORMAT
15879 
15880 static char mandescr_show_peer[] = 
15881 "Description: Show one SIP peer with details on current status.\n"
15882 "Variables: \n"
15883 "  Peer: <name>           The peer name you want to check.\n"
15884 "  ActionID: <id>   Optional action ID for this AMI transaction.\n";
15885 
15886 /*! \brief Show SIP peers in the manager API  */
15887 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
15888 {
15889    const char *a[4];
15890    const char *peer;
15891 
15892    peer = astman_get_header(m, "Peer");
15893    if (ast_strlen_zero(peer)) {
15894       astman_send_error(s, m, "Peer: <name> missing.");
15895       return 0;
15896    }
15897    a[0] = "sip";
15898    a[1] = "show";
15899    a[2] = "peer";
15900    a[3] = peer;
15901 
15902    _sip_show_peer(1, -1, s, m, 4, a);
15903    astman_append(s, "\r\n\r\n" );
15904    return 0;
15905 }
15906 
15907 /*! \brief Show one peer in detail */
15908 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15909 {
15910    switch (cmd) {
15911    case CLI_INIT:
15912       e->command = "sip show peer";
15913       e->usage =
15914          "Usage: sip show peer <name> [load]\n"
15915          "       Shows all details on one SIP peer and the current status.\n"
15916          "       Option \"load\" forces lookup of peer in realtime storage.\n";
15917       return NULL;
15918    case CLI_GENERATE:
15919       return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
15920    }
15921    return _sip_show_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
15922 }
15923 
15924 /*! \brief Send qualify message to peer from cli or manager. Mostly for debugging. */
15925 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
15926 {
15927    struct sip_peer *peer;
15928    int load_realtime;
15929 
15930    if (argc < 4)
15931       return CLI_SHOWUSAGE;
15932 
15933    load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
15934    if ((peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0))) {
15935       sip_poke_peer(peer, 1);
15936       unref_peer(peer, "qualify: done with peer");
15937    } else if (type == 0) {
15938       ast_cli(fd, "Peer '%s' not found\n", argv[3]);
15939    } else {
15940       astman_send_error(s, m, "Peer not found");
15941    }
15942    return CLI_SUCCESS;
15943 }
15944 
15945 /*! \brief Qualify SIP peers in the manager API  */
15946 static int manager_sip_qualify_peer(struct mansession *s, const struct message *m)
15947 {
15948    const char *a[4];
15949    const char *peer;
15950 
15951    peer = astman_get_header(m, "Peer");
15952    if (ast_strlen_zero(peer)) {
15953       astman_send_error(s, m, "Peer: <name> missing.");
15954       return 0;
15955    }
15956    a[0] = "sip";
15957    a[1] = "qualify";
15958    a[2] = "peer";
15959    a[3] = peer;
15960 
15961    _sip_qualify_peer(1, -1, s, m, 4, a);
15962    astman_append(s, "\r\n\r\n" );
15963    return 0;
15964 }
15965 
15966 /*! \brief Send an OPTIONS packet to a SIP peer */
15967 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15968 {
15969    switch (cmd) {
15970    case CLI_INIT:
15971       e->command = "sip qualify peer";
15972       e->usage =
15973          "Usage: sip qualify peer <name> [load]\n"
15974          "       Requests a response from one SIP peer and the current status.\n"
15975          "       Option \"load\" forces lookup of peer in realtime storage.\n";
15976       return NULL;
15977    case CLI_GENERATE:
15978       return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
15979    }
15980    return _sip_qualify_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
15981 }
15982 
15983 /*! \brief list peer mailboxes to CLI */
15984 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer)
15985 {
15986    struct sip_mailbox *mailbox;
15987 
15988    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
15989       ast_str_append(mailbox_str, 0, "%s%s%s%s",
15990          mailbox->mailbox,
15991          ast_strlen_zero(mailbox->context) ? "" : "@",
15992          S_OR(mailbox->context, ""),
15993          AST_LIST_NEXT(mailbox, entry) ? "," : "");
15994    }
15995 }
15996 
15997 static struct _map_x_s faxecmodes[] = {
15998    { SIP_PAGE2_T38SUPPORT_UDPTL,       "None"},
15999    { SIP_PAGE2_T38SUPPORT_UDPTL_FEC,      "FEC"},
16000    { SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY,  "Redundancy"},
16001    { -1,                NULL},
16002 };
16003 
16004 static const char *faxec2str(int faxec)
16005 {
16006    return map_x_s(faxecmodes, faxec, "Unknown");
16007 }
16008 
16009 /*! \brief Show one peer in detail (main function) */
16010 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
16011 {
16012    char status[30] = "";
16013    char cbuf[256];
16014    struct sip_peer *peer;
16015    char codec_buf[512];
16016    struct ast_codec_pref *pref;
16017    struct ast_variable *v;
16018    struct sip_auth *auth;
16019    int x = 0, codec = 0, load_realtime;
16020    int realtimepeers;
16021 
16022    realtimepeers = ast_check_realtime("sippeers");
16023 
16024    if (argc < 4)
16025       return CLI_SHOWUSAGE;
16026 
16027    load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
16028    peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0);
16029 
16030    if (s) {    /* Manager */
16031       if (peer) {
16032          const char *id = astman_get_header(m, "ActionID");
16033 
16034          astman_append(s, "Response: Success\r\n");
16035          if (!ast_strlen_zero(id))
16036             astman_append(s, "ActionID: %s\r\n", id);
16037       } else {
16038          snprintf (cbuf, sizeof(cbuf), "Peer %s not found.", argv[3]);
16039          astman_send_error(s, m, cbuf);
16040          return CLI_SUCCESS;
16041       }
16042    }
16043    if (peer && type==0 ) { /* Normal listing */
16044       struct ast_str *mailbox_str = ast_str_alloca(512);
16045       ast_cli(fd, "\n\n");
16046       ast_cli(fd, "  * Name       : %s\n", peer->name);
16047       if (realtimepeers) { /* Realtime is enabled */
16048          ast_cli(fd, "  Realtime peer: %s\n", peer->is_realtime ? "Yes, cached" : "No");
16049       }
16050       ast_cli(fd, "  Secret       : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
16051       ast_cli(fd, "  MD5Secret    : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
16052       ast_cli(fd, "  Remote Secret: %s\n", ast_strlen_zero(peer->remotesecret)?"<Not set>":"<Set>");
16053       for (auth = peer->auth; auth; auth = auth->next) {
16054          ast_cli(fd, "  Realm-auth   : Realm %-15.15s User %-10.20s ", auth->realm, auth->username);
16055          ast_cli(fd, "%s\n", !ast_strlen_zero(auth->secret)?"<Secret set>":(!ast_strlen_zero(auth->md5secret)?"<MD5secret set>" : "<Not set>"));
16056       }
16057       ast_cli(fd, "  Context      : %s\n", peer->context);
16058       ast_cli(fd, "  Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
16059       ast_cli(fd, "  Language     : %s\n", peer->language);
16060       if (!ast_strlen_zero(peer->accountcode))
16061          ast_cli(fd, "  Accountcode  : %s\n", peer->accountcode);
16062       ast_cli(fd, "  AMA flags    : %s\n", ast_cdr_flags2str(peer->amaflags));
16063       ast_cli(fd, "  Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
16064       ast_cli(fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(peer->callingpres));
16065       if (!ast_strlen_zero(peer->fromuser))
16066          ast_cli(fd, "  FromUser     : %s\n", peer->fromuser);
16067       if (!ast_strlen_zero(peer->fromdomain))
16068          ast_cli(fd, "  FromDomain   : %s\n", peer->fromdomain);
16069       ast_cli(fd, "  Callgroup    : ");
16070       print_group(fd, peer->callgroup, 0);
16071       ast_cli(fd, "  Pickupgroup  : ");
16072       print_group(fd, peer->pickupgroup, 0);
16073       peer_mailboxes_to_str(&mailbox_str, peer);
16074       ast_cli(fd, "  Mailbox      : %s\n", mailbox_str->str);
16075       ast_cli(fd, "  VM Extension : %s\n", peer->vmexten);
16076       ast_cli(fd, "  LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
16077       ast_cli(fd, "  Call limit   : %d\n", peer->call_limit);
16078       if (peer->busy_level)
16079          ast_cli(fd, "  Busy level   : %d\n", peer->busy_level);
16080       ast_cli(fd, "  Dynamic      : %s\n", cli_yesno(peer->host_dynamic));
16081       ast_cli(fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
16082       ast_cli(fd, "  MaxCallBR    : %d kbps\n", peer->maxcallbitrate);
16083       ast_cli(fd, "  Expire       : %ld\n", ast_sched_when(sched, peer->expire));
16084       ast_cli(fd, "  Insecure     : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
16085       ast_cli(fd, "  Nat          : %s\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
16086       ast_cli(fd, "  ACL          : %s\n", cli_yesno(peer->ha != NULL));
16087       ast_cli(fd, "  T.38 support : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
16088       ast_cli(fd, "  T.38 EC mode : %s\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
16089       ast_cli(fd, "  T.38 MaxDtgrm: %d\n", peer->t38_maxdatagram);
16090       ast_cli(fd, "  DirectMedia  : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)));
16091       ast_cli(fd, "  PromiscRedir : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)));
16092       ast_cli(fd, "  User=Phone   : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)));
16093       ast_cli(fd, "  Video Support: %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) || ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS)));
16094       ast_cli(fd, "  Text Support : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)));
16095       ast_cli(fd, "  Ign SDP ver  : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_IGNORESDPVERSION)));
16096       ast_cli(fd, "  Trust RPID   : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_TRUSTRPID)));
16097       ast_cli(fd, "  Send RPID    : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_SENDRPID)));
16098       ast_cli(fd, "  Subscriptions: %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
16099       ast_cli(fd, "  Overlap dial : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP)));
16100       ast_cli(fd, "  Forward Loop : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_FORWARD_LOOP_DETECTED)));
16101       if (peer->outboundproxy)
16102          ast_cli(fd, "  Outb. proxy  : %s %s\n", ast_strlen_zero(peer->outboundproxy->name) ? "<not set>" : peer->outboundproxy->name,
16103                      peer->outboundproxy->force ? "(forced)" : "");
16104 
16105       /* - is enumerated */
16106       ast_cli(fd, "  DTMFmode     : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
16107       ast_cli(fd, "  Timer T1     : %d\n", peer->timer_t1);
16108       ast_cli(fd, "  Timer B      : %d\n", peer->timer_b);
16109       ast_cli(fd, "  ToHost       : %s\n", peer->tohost);
16110       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));
16111       ast_cli(fd, "  Defaddr->IP  : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
16112       ast_cli(fd, "  Prim.Transp. : %s\n", get_transport(peer->socket.type));
16113       ast_cli(fd, "  Allowed.Trsp : %s\n", get_transport_list(peer->transports)); 
16114       if (!ast_strlen_zero(global_regcontext))
16115          ast_cli(fd, "  Reg. exten   : %s\n", peer->regexten);
16116       ast_cli(fd, "  Def. Username: %s\n", peer->username);
16117       ast_cli(fd, "  SIP Options  : ");
16118       if (peer->sipoptions) {
16119          int lastoption = -1;
16120          for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
16121             if (sip_options[x].id != lastoption) {
16122                if (peer->sipoptions & sip_options[x].id)
16123                   ast_cli(fd, "%s ", sip_options[x].text);
16124                lastoption = x;
16125             }
16126          }
16127       } else
16128          ast_cli(fd, "(none)");
16129 
16130       ast_cli(fd, "\n");
16131       ast_cli(fd, "  Codecs       : ");
16132       ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
16133       ast_cli(fd, "%s\n", codec_buf);
16134       ast_cli(fd, "  Codec Order  : (");
16135       print_codec_to_cli(fd, &peer->prefs);
16136       ast_cli(fd, ")\n");
16137 
16138       ast_cli(fd, "  Auto-Framing :  %s \n", cli_yesno(peer->autoframing));
16139       ast_cli(fd, "  100 on REG   : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_REGISTERTRYING) ? "Yes" : "No");
16140       ast_cli(fd, "  Status       : ");
16141       peer_status(peer, status, sizeof(status));
16142       ast_cli(fd, "%s\n", status);
16143       ast_cli(fd, "  Useragent    : %s\n", peer->useragent);
16144       ast_cli(fd, "  Reg. Contact : %s\n", peer->fullcontact);
16145       ast_cli(fd, "  Qualify Freq : %d ms\n", peer->qualifyfreq);
16146       if (peer->chanvars) {
16147          ast_cli(fd, "  Variables    :\n");
16148          for (v = peer->chanvars ; v ; v = v->next)
16149             ast_cli(fd, "                 %s = %s\n", v->name, v->value);
16150       }
16151 
16152       ast_cli(fd, "  Sess-Timers  : %s\n", stmode2str(peer->stimer.st_mode_oper));
16153       ast_cli(fd, "  Sess-Refresh : %s\n", strefresher2str(peer->stimer.st_ref));
16154       ast_cli(fd, "  Sess-Expires : %d secs\n", peer->stimer.st_max_se);
16155       ast_cli(fd, "  Min-Sess     : %d secs\n", peer->stimer.st_min_se);
16156       ast_cli(fd, "  Parkinglot   : %s\n", peer->parkinglot);
16157       ast_cli(fd, "\n");
16158       peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer ptr");
16159    } else  if (peer && type == 1) { /* manager listing */
16160       char buffer[256];
16161       struct ast_str *mailbox_str = ast_str_alloca(512);
16162       astman_append(s, "Channeltype: SIP\r\n");
16163       astman_append(s, "ObjectName: %s\r\n", peer->name);
16164       astman_append(s, "ChanObjectType: peer\r\n");
16165       astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
16166       astman_append(s, "RemoteSecretExist: %s\r\n", ast_strlen_zero(peer->remotesecret)?"N":"Y");
16167       astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
16168       astman_append(s, "Context: %s\r\n", peer->context);
16169       astman_append(s, "Language: %s\r\n", peer->language);
16170       if (!ast_strlen_zero(peer->accountcode))
16171          astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
16172       astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
16173       astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
16174       if (!ast_strlen_zero(peer->fromuser))
16175          astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
16176       if (!ast_strlen_zero(peer->fromdomain))
16177          astman_append(s, "SIP-FromDomain: %s\r\n", peer->fromdomain);
16178       astman_append(s, "Callgroup: ");
16179       astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->callgroup));
16180       astman_append(s, "Pickupgroup: ");
16181       astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->pickupgroup));
16182       peer_mailboxes_to_str(&mailbox_str, peer);
16183       astman_append(s, "VoiceMailbox: %s\r\n", mailbox_str->str);
16184       astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
16185       astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
16186       astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
16187       astman_append(s, "Busy-level: %d\r\n", peer->busy_level);
16188       astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
16189       astman_append(s, "Dynamic: %s\r\n", peer->host_dynamic?"Y":"N");
16190       astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
16191       astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched, peer->expire));
16192       astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
16193       astman_append(s, "SIP-NatSupport: %s\r\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
16194       astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
16195       astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
16196       astman_append(s, "SIP-DirectMedia: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
16197       astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
16198       astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
16199       astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
16200       astman_append(s, "SIP-TextSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)?"Y":"N"));
16201       astman_append(s, "SIP-T.38Support: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)?"Y":"N"));
16202       astman_append(s, "SIP-T.38EC: %s\r\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
16203       astman_append(s, "SIP-T.38MaxDtgrm: %d\r\n", peer->t38_maxdatagram);
16204       astman_append(s, "SIP-Sess-Timers: %s\r\n", stmode2str(peer->stimer.st_mode_oper));
16205       astman_append(s, "SIP-Sess-Refresh: %s\r\n", strefresher2str(peer->stimer.st_ref));
16206       astman_append(s, "SIP-Sess-Expires: %d\r\n", peer->stimer.st_max_se);
16207       astman_append(s, "SIP-Sess-Min: %d\r\n", peer->stimer.st_min_se);
16208 
16209       /* - is enumerated */
16210       astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
16211       astman_append(s, "ToHost: %s\r\n", peer->tohost);
16212       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));
16213       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));
16214       astman_append(s, "Default-Username: %s\r\n", peer->username);
16215       if (!ast_strlen_zero(global_regcontext))
16216          astman_append(s, "RegExtension: %s\r\n", peer->regexten);
16217       astman_append(s, "Codecs: ");
16218       ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
16219       astman_append(s, "%s\r\n", codec_buf);
16220       astman_append(s, "CodecOrder: ");
16221       pref = &peer->prefs;
16222       for(x = 0; x < 32 ; x++) {
16223          codec = ast_codec_pref_index(pref, x);
16224          if (!codec)
16225             break;
16226          astman_append(s, "%s", ast_getformatname(codec));
16227          if (x < 31 && ast_codec_pref_index(pref, x+1))
16228             astman_append(s, ",");
16229       }
16230 
16231       astman_append(s, "\r\n");
16232       astman_append(s, "Status: ");
16233       peer_status(peer, status, sizeof(status));
16234       astman_append(s, "%s\r\n", status);
16235       astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
16236       astman_append(s, "Reg-Contact: %s\r\n", peer->fullcontact);
16237       astman_append(s, "QualifyFreq: %d ms\r\n", peer->qualifyfreq);
16238       astman_append(s, "Parkinglot: %s\r\n", peer->parkinglot);
16239       if (peer->chanvars) {
16240          for (v = peer->chanvars ; v ; v = v->next) {
16241             astman_append(s, "ChanVariable: %s=%s\r\n", v->name, v->value);
16242          }
16243       }
16244 
16245       peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer");
16246 
16247    } else {
16248       ast_cli(fd, "Peer %s not found.\n", argv[3]);
16249       ast_cli(fd, "\n");
16250    }
16251 
16252    return CLI_SUCCESS;
16253 }
16254 
16255 /*! \brief Do completion on user name */
16256 static char *complete_sip_user(const char *word, int state)
16257 {
16258    char *result = NULL;
16259    int wordlen = strlen(word);
16260    int which = 0;
16261    struct ao2_iterator user_iter;
16262    struct sip_peer *user;
16263 
16264    user_iter = ao2_iterator_init(peers, 0);
16265    while ((user = ao2_t_iterator_next(&user_iter, "iterate thru peers table"))) {
16266       ao2_lock(user);
16267       if (!(user->type & SIP_TYPE_USER)) {
16268          ao2_unlock(user);
16269          unref_peer(user, "complete sip user");
16270          continue;
16271       }
16272       /* locking of the object is not required because only the name and flags are being compared */
16273       if (!strncasecmp(word, user->name, wordlen) && ++which > state) {
16274          result = ast_strdup(user->name);
16275       }
16276       ao2_unlock(user);
16277       unref_peer(user, "complete sip user");
16278       if (result) {
16279          break;
16280       }
16281    }
16282    ao2_iterator_destroy(&user_iter);
16283    return result;
16284 }
16285 /*! \brief Support routine for 'sip show user' CLI */
16286 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
16287 {
16288    if (pos == 3)
16289       return complete_sip_user(word, state);
16290 
16291    return NULL;
16292 }
16293 
16294 /*! \brief Show one user in detail */
16295 static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16296 {
16297    char cbuf[256];
16298    struct sip_peer *user;
16299    struct ast_variable *v;
16300    int load_realtime;
16301 
16302    switch (cmd) {
16303    case CLI_INIT:
16304       e->command = "sip show user";
16305       e->usage =
16306          "Usage: sip show user <name> [load]\n"
16307          "       Shows all details on one SIP user and the current status.\n"
16308          "       Option \"load\" forces lookup of peer in realtime storage.\n";
16309       return NULL;
16310    case CLI_GENERATE:
16311       return complete_sip_show_user(a->line, a->word, a->pos, a->n);
16312    }
16313 
16314    if (a->argc < 4)
16315       return CLI_SHOWUSAGE;
16316 
16317    /* Load from realtime storage? */
16318    load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? TRUE : FALSE;
16319 
16320    if ((user = find_peer(a->argv[3], NULL, load_realtime, FINDUSERS, FALSE, 0))) {
16321       ao2_lock(user);
16322       ast_cli(a->fd, "\n\n");
16323       ast_cli(a->fd, "  * Name       : %s\n", user->name);
16324       ast_cli(a->fd, "  Secret       : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
16325       ast_cli(a->fd, "  MD5Secret    : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
16326       ast_cli(a->fd, "  Context      : %s\n", user->context);
16327       ast_cli(a->fd, "  Language     : %s\n", user->language);
16328       if (!ast_strlen_zero(user->accountcode))
16329          ast_cli(a->fd, "  Accountcode  : %s\n", user->accountcode);
16330       ast_cli(a->fd, "  AMA flags    : %s\n", ast_cdr_flags2str(user->amaflags));
16331       ast_cli(a->fd, "  Transfer mode: %s\n", transfermode2str(user->allowtransfer));
16332       ast_cli(a->fd, "  MaxCallBR    : %d kbps\n", user->maxcallbitrate);
16333       ast_cli(a->fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(user->callingpres));
16334       ast_cli(a->fd, "  Call limit   : %d\n", user->call_limit);
16335       ast_cli(a->fd, "  Callgroup    : ");
16336       print_group(a->fd, user->callgroup, 0);
16337       ast_cli(a->fd, "  Pickupgroup  : ");
16338       print_group(a->fd, user->pickupgroup, 0);
16339       ast_cli(a->fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
16340       ast_cli(a->fd, "  ACL          : %s\n", cli_yesno(user->ha != NULL));
16341       ast_cli(a->fd, "  Sess-Timers  : %s\n", stmode2str(user->stimer.st_mode_oper));
16342       ast_cli(a->fd, "  Sess-Refresh : %s\n", strefresher2str(user->stimer.st_ref));
16343       ast_cli(a->fd, "  Sess-Expires : %d secs\n", user->stimer.st_max_se);
16344       ast_cli(a->fd, "  Sess-Min-SE  : %d secs\n", user->stimer.st_min_se);
16345 
16346       ast_cli(a->fd, "  Codec Order  : (");
16347       print_codec_to_cli(a->fd, &user->prefs);
16348       ast_cli(a->fd, ")\n");
16349 
16350       ast_cli(a->fd, "  Auto-Framing:  %s \n", cli_yesno(user->autoframing));
16351       if (user->chanvars) {
16352          ast_cli(a->fd, "  Variables    :\n");
16353          for (v = user->chanvars ; v ; v = v->next)
16354             ast_cli(a->fd, "                 %s = %s\n", v->name, v->value);
16355       }
16356 
16357       ast_cli(a->fd, "\n");
16358 
16359       ao2_unlock(user);
16360       unref_peer(user, "sip show user");
16361    } else {
16362       ast_cli(a->fd, "User %s not found.\n", a->argv[3]);
16363       ast_cli(a->fd, "\n");
16364    }
16365 
16366    return CLI_SUCCESS;
16367 }
16368 
16369 
16370 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16371 {
16372    struct ast_str *cbuf;
16373    struct ast_cb_names cbnames = {9, { "retrans_pkt",
16374                                         "__sip_autodestruct",
16375                                         "expire_register",
16376                                         "auto_congest",
16377                                         "sip_reg_timeout",
16378                                         "sip_poke_peer_s",
16379                                         "sip_poke_noanswer",
16380                                         "sip_reregister",
16381                                         "sip_reinvite_retry"},
16382                            { retrans_pkt,
16383                                      __sip_autodestruct,
16384                                      expire_register,
16385                                      auto_congest,
16386                                      sip_reg_timeout,
16387                                      sip_poke_peer_s,
16388                                      sip_poke_noanswer,
16389                                      sip_reregister,
16390                                      sip_reinvite_retry}};
16391    
16392    switch (cmd) {
16393    case CLI_INIT:
16394       e->command = "sip show sched";
16395       e->usage =
16396          "Usage: sip show sched\n"
16397          "       Shows stats on what's in the sched queue at the moment\n";
16398       return NULL;
16399    case CLI_GENERATE:
16400       return NULL;
16401    }
16402 
16403    cbuf = ast_str_alloca(2048);
16404 
16405    ast_cli(a->fd, "\n");
16406    ast_sched_report(sched, &cbuf, &cbnames);
16407    ast_cli(a->fd, "%s", cbuf->str);
16408 
16409    return CLI_SUCCESS;
16410 }
16411 
16412 /*! \brief  Show SIP Registry (registrations with other SIP proxies */
16413 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16414 {
16415 #define FORMAT2 "%-30.30s %-6.6s %-12.12s  %8.8s %-20.20s %-25.25s\n"
16416 #define FORMAT  "%-30.30s %-6.6s %-12.12s  %8d %-20.20s %-25.25s\n"
16417    char host[80];
16418    char tmpdat[256];
16419    struct ast_tm tm;
16420    int counter = 0;
16421 
16422    switch (cmd) {
16423    case CLI_INIT:
16424       e->command = "sip show registry";
16425       e->usage =
16426          "Usage: sip show registry\n"
16427          "       Lists all registration requests and status.\n";
16428       return NULL;
16429    case CLI_GENERATE:
16430       return NULL;
16431    }
16432 
16433    if (a->argc != 3)
16434       return CLI_SHOWUSAGE;
16435    ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Refresh", "State", "Reg.Time");
16436    
16437    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
16438       ASTOBJ_RDLOCK(iterator);
16439       snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
16440       if (iterator->regtime.tv_sec) {
16441          ast_localtime(&iterator->regtime, &tm, NULL);
16442          ast_strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
16443       } else 
16444          tmpdat[0] = '\0';
16445       ast_cli(a->fd, FORMAT, host, (iterator->dnsmgr) ? "Y" : "N", iterator->username, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
16446       ASTOBJ_UNLOCK(iterator);
16447       counter++;
16448    } while(0));
16449    ast_cli(a->fd, "%d SIP registrations.\n", counter);
16450    return CLI_SUCCESS;
16451 #undef FORMAT
16452 #undef FORMAT2
16453 }
16454 
16455 /*! \brief Unregister (force expiration) a SIP peer in the registry via CLI 
16456    \note This function does not tell the SIP device what's going on,
16457    so use it with great care.
16458 */
16459 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16460 {
16461    struct sip_peer *peer;
16462    int load_realtime = 0;
16463 
16464    switch (cmd) {
16465    case CLI_INIT:
16466       e->command = "sip unregister";
16467       e->usage =
16468          "Usage: sip unregister <peer>\n"
16469          "       Unregister (force expiration) a SIP peer from the registry\n";
16470       return NULL;
16471    case CLI_GENERATE:
16472       return complete_sip_unregister(a->line, a->word, a->pos, a->n);
16473    }
16474    
16475    if (a->argc != 3)
16476       return CLI_SHOWUSAGE;
16477    
16478    if ((peer = find_peer(a->argv[2], NULL, load_realtime, FINDPEERS, TRUE, 0))) {
16479       if (peer->expire > 0) {
16480          AST_SCHED_DEL_UNREF(sched, peer->expire,
16481             unref_peer(peer, "remove register expire ref"));
16482          expire_register(ref_peer(peer, "ref for expire_register"));
16483          ast_cli(a->fd, "Unregistered peer \'%s\'\n\n", a->argv[2]);
16484       } else {
16485          ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
16486       }
16487       unref_peer(peer, "sip_unregister: unref_peer via sip_unregister: done with peer from find_peer call");
16488    } else {
16489       ast_cli(a->fd, "Peer unknown: \'%s\'. Not unregistered.\n", a->argv[2]);
16490    }
16491    
16492    return CLI_SUCCESS;
16493 }
16494 
16495 /*! \brief Callback for show_chanstats */
16496 static int show_chanstats_cb(void *__cur, void *__arg, int flags)
16497 {
16498 #define FORMAT2 "%-15.15s  %-11.11s  %-8.8s %-10.10s  %-10.10s (     %%) %-6.6s %-10.10s  %-10.10s (     %%) %-6.6s\n"
16499 #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"
16500    struct sip_pvt *cur = __cur;
16501    unsigned int rxcount, txcount, rxploss, txploss;
16502    char durbuf[10];
16503         int duration;
16504         int durh, durm, durs;
16505    struct ast_channel *c = cur->owner;
16506    struct __show_chan_arg *arg = __arg;
16507    int fd = arg->fd;
16508 
16509 
16510    if (cur->subscribed != NONE) /* Subscriptions */
16511       return 0;   /* don't care, we scan all channels */
16512 
16513    if (!cur->rtp) {
16514       if (sipdebug)
16515          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");
16516       return 0;   /* don't care, we scan all channels */
16517    }
16518    rxcount = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXCOUNT);
16519    txcount = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXCOUNT);
16520    rxploss = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXPLOSS);
16521    txploss = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXPLOSS);
16522 
16523    /* Find the duration of this channel */
16524    if (c && c->cdr && !ast_tvzero(c->cdr->start)) {
16525       duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
16526       durh = duration / 3600;
16527       durm = (duration % 3600) / 60;
16528       durs = duration % 60;
16529       snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
16530    } else {
16531       durbuf[0] = '\0';
16532    }
16533    /* Print stats for every call with RTP */
16534    ast_cli(fd, FORMAT, 
16535       ast_inet_ntoa(cur->sa.sin_addr), 
16536       cur->callid, 
16537       durbuf,
16538       rxcount > (unsigned int) 100000 ? (unsigned int) (rxcount)/(unsigned int) 1000 : rxcount,
16539       rxcount > (unsigned int) 100000 ? "K":" ",
16540       rxploss,
16541       (rxcount + rxploss) > 0 ? (double) rxploss / (rxcount + rxploss) * 100 : 0,
16542       ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXJITTER),
16543       txcount > (unsigned int) 100000 ? (unsigned int) (txcount)/(unsigned int) 1000 : txcount,
16544       txcount > (unsigned int) 100000 ? "K":" ",
16545       txploss,
16546       txcount > 0 ? (double) txploss / txcount * 100 : 0,
16547       ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXJITTER)
16548    );
16549    arg->numchans++;
16550 
16551    return 0;   /* don't care, we scan all channels */
16552 }
16553 
16554 /*! \brief SIP show channelstats CLI (main function) */
16555 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16556 {
16557    struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
16558 
16559    switch (cmd) {
16560    case CLI_INIT:
16561       e->command = "sip show channelstats";
16562       e->usage =
16563          "Usage: sip show channelstats\n"
16564          "       Lists all currently active SIP channel's RTCP statistics.\n"
16565          "       Note that calls in the much optimized RTP P2P bridge mode will not show any packets here.";
16566       return NULL;
16567    case CLI_GENERATE:
16568       return NULL;
16569    }
16570 
16571    if (a->argc != 3)
16572       return CLI_SHOWUSAGE;
16573 
16574    ast_cli(a->fd, FORMAT2, "Peer", "Call ID", "Duration", "Recv: Pack", "Lost", "Jitter", "Send: Pack", "Lost", "Jitter");
16575    /* iterate on the container and invoke the callback on each item */
16576    ao2_t_callback(dialogs, OBJ_NODATA, show_chanstats_cb, &arg, "callback to sip show chanstats");
16577    ast_cli(a->fd, "%d active SIP channel%s\n", arg.numchans, (arg.numchans != 1) ? "s" : ""); 
16578    return CLI_SUCCESS;
16579 }
16580 #undef FORMAT
16581 #undef FORMAT2
16582 
16583 /*! \brief List global settings for the SIP channel */
16584 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16585 {
16586    int realtimepeers;
16587    int realtimeregs;
16588    char codec_buf[SIPBUFSIZE];
16589    const char *msg;  /* temporary msg pointer */
16590 
16591    switch (cmd) {
16592    case CLI_INIT:
16593       e->command = "sip show settings";
16594       e->usage =
16595          "Usage: sip show settings\n"
16596          "       Provides detailed list of the configuration of the SIP channel.\n";
16597       return NULL;
16598    case CLI_GENERATE:
16599       return NULL;
16600    }
16601 
16602 
16603    realtimepeers = ast_check_realtime("sippeers");
16604    realtimeregs = ast_check_realtime("sipregs");
16605 
16606    if (a->argc != 3)
16607       return CLI_SHOWUSAGE;
16608    ast_cli(a->fd, "\n\nGlobal Settings:\n");
16609    ast_cli(a->fd, "----------------\n");
16610    ast_cli(a->fd, "  UDP SIP Port:           %d\n", ntohs(bindaddr.sin_port));
16611    ast_cli(a->fd, "  UDP Bindaddress:        %s\n", ast_inet_ntoa(bindaddr.sin_addr));
16612    ast_cli(a->fd, "  TCP SIP Port:           ");
16613    if (sip_tcp_desc.local_address.sin_family == AF_INET) {
16614       ast_cli(a->fd, "%d\n", ntohs(sip_tcp_desc.local_address.sin_port));
16615       ast_cli(a->fd, "  TCP Bindaddress:        %s\n", ast_inet_ntoa(sip_tcp_desc.local_address.sin_addr));
16616    } else {
16617       ast_cli(a->fd, "Disabled\n");
16618    }
16619    ast_cli(a->fd, "  TLS SIP Port:           ");
16620    if (default_tls_cfg.enabled != FALSE) {
16621       ast_cli(a->fd, "%d\n", ntohs(sip_tls_desc.local_address.sin_port));
16622       ast_cli(a->fd, "  TLS Bindaddress:        %s\n", ast_inet_ntoa(sip_tls_desc.local_address.sin_addr));
16623    } else {
16624       ast_cli(a->fd, "Disabled\n");
16625    }
16626    ast_cli(a->fd, "  Videosupport:           %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT)));
16627    ast_cli(a->fd, "  Textsupport:            %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT)));
16628    ast_cli(a->fd, "  Ignore SDP sess. ver.:  %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION)));
16629    ast_cli(a->fd, "  AutoCreate Peer:        %s\n", cli_yesno(sip_cfg.autocreatepeer));
16630    ast_cli(a->fd, "  Match Auth Username:    %s\n", cli_yesno(global_match_auth_username));
16631    ast_cli(a->fd, "  Allow unknown access:   %s\n", cli_yesno(sip_cfg.allowguest));
16632    ast_cli(a->fd, "  Allow subscriptions:    %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
16633    ast_cli(a->fd, "  Allow overlap dialing:  %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)));
16634    ast_cli(a->fd, "  Allow promsic. redir:   %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_PROMISCREDIR)));
16635    ast_cli(a->fd, "  Enable call counters:   %s\n", cli_yesno(global_callcounter));
16636    ast_cli(a->fd, "  SIP domain support:     %s\n", cli_yesno(!AST_LIST_EMPTY(&domain_list)));
16637    ast_cli(a->fd, "  Realm. auth:            %s\n", cli_yesno(authl != NULL));
16638    ast_cli(a->fd, "  Our auth realm          %s\n", sip_cfg.realm);
16639    ast_cli(a->fd, "  Call to non-local dom.: %s\n", cli_yesno(sip_cfg.allow_external_domains));
16640    ast_cli(a->fd, "  URI user is phone no:   %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_USEREQPHONE)));
16641    ast_cli(a->fd, "  Always auth rejects:    %s\n", cli_yesno(sip_cfg.alwaysauthreject));
16642    ast_cli(a->fd, "  Direct RTP setup:       %s\n", cli_yesno(sip_cfg.directrtpsetup));
16643    ast_cli(a->fd, "  User Agent:             %s\n", global_useragent);
16644    ast_cli(a->fd, "  SDP Session Name:       %s\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
16645    ast_cli(a->fd, "  SDP Owner Name:         %s\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner);
16646    ast_cli(a->fd, "  Reg. context:           %s\n", S_OR(global_regcontext, "(not set)"));
16647    ast_cli(a->fd, "  Regexten on Qualify:    %s\n", cli_yesno(sip_cfg.regextenonqualify));
16648    ast_cli(a->fd, "  Caller ID:              %s\n", default_callerid);
16649    ast_cli(a->fd, "  From: Domain:           %s\n", default_fromdomain);
16650    ast_cli(a->fd, "  Record SIP history:     %s\n", recordhistory ? "On" : "Off");
16651    ast_cli(a->fd, "  Call Events:            %s\n", sip_cfg.callevents ? "On" : "Off");
16652    ast_cli(a->fd, "  Auth. Failure Events:   %s\n", global_authfailureevents ? "On" : "Off");
16653 
16654    ast_cli(a->fd, "  T.38 support:           %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
16655    ast_cli(a->fd, "  T.38 EC mode:           %s\n", faxec2str(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
16656    ast_cli(a->fd, "  T.38 MaxDtgrm:          %d\n", global_t38_maxdatagram);
16657 
16658    if (!realtimepeers && !realtimeregs)
16659       ast_cli(a->fd, "  SIP realtime:           Disabled\n" );
16660    else
16661       ast_cli(a->fd, "  SIP realtime:           Enabled\n" );
16662    ast_cli(a->fd, "  Qualify Freq :          %d ms\n", global_qualifyfreq);
16663    ast_cli(a->fd, "\nNetwork QoS Settings:\n");
16664    ast_cli(a->fd, "---------------------------\n");
16665    ast_cli(a->fd, "  IP ToS SIP:             %s\n", ast_tos2str(global_tos_sip));
16666    ast_cli(a->fd, "  IP ToS RTP audio:       %s\n", ast_tos2str(global_tos_audio));
16667    ast_cli(a->fd, "  IP ToS RTP video:       %s\n", ast_tos2str(global_tos_video));
16668    ast_cli(a->fd, "  IP ToS RTP text:        %s\n", ast_tos2str(global_tos_text));
16669    ast_cli(a->fd, "  802.1p CoS SIP:         %d\n", global_cos_sip);
16670    ast_cli(a->fd, "  802.1p CoS RTP audio:   %d\n", global_cos_audio);
16671    ast_cli(a->fd, "  802.1p CoS RTP video:   %d\n", global_cos_video);
16672    ast_cli(a->fd, "  802.1p CoS RTP text:    %d\n", global_cos_text);
16673    ast_cli(a->fd, "  Jitterbuffer enabled:   %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_ENABLED)));
16674    ast_cli(a->fd, "  Jitterbuffer forced:    %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_FORCED)));
16675    ast_cli(a->fd, "  Jitterbuffer max size:  %ld\n", global_jbconf.max_size);
16676    ast_cli(a->fd, "  Jitterbuffer resync:    %ld\n", global_jbconf.resync_threshold);
16677    ast_cli(a->fd, "  Jitterbuffer impl:      %s\n", global_jbconf.impl);
16678    ast_cli(a->fd, "  Jitterbuffer log:       %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_LOG)));
16679 
16680    ast_cli(a->fd, "\nNetwork Settings:\n");
16681    ast_cli(a->fd, "---------------------------\n");
16682    /* determine if/how SIP address can be remapped */
16683    if (localaddr == NULL)
16684       msg = "Disabled, no localnet list";
16685    else if (externip.sin_addr.s_addr == 0)
16686       msg = "Disabled, externip is 0.0.0.0";
16687    else if (stunaddr.sin_addr.s_addr != 0)
16688       msg = "Enabled using STUN";
16689    else if (!ast_strlen_zero(externhost))
16690       msg = "Enabled using externhost";
16691    else
16692       msg = "Enabled using externip";
16693    ast_cli(a->fd, "  SIP address remapping:  %s\n", msg);
16694    ast_cli(a->fd, "  Externhost:             %s\n", S_OR(externhost, "<none>"));
16695    ast_cli(a->fd, "  Externip:               %s:%d\n", ast_inet_ntoa(externip.sin_addr), ntohs(externip.sin_port));
16696    ast_cli(a->fd, "  Externrefresh:          %d\n", externrefresh);
16697    {
16698       struct ast_ha *d;
16699       const char *prefix = "Localnet:";
16700       char buf[INET_ADDRSTRLEN]; /* need to print two addresses */
16701 
16702       for (d = localaddr; d ; prefix = "", d = d->next) {
16703          ast_cli(a->fd, "  %-24s%s/%s\n",
16704              prefix, ast_inet_ntoa(d->netaddr),
16705              inet_ntop(AF_INET, &d->netmask, buf, sizeof(buf)) );
16706       }
16707    }
16708    ast_cli(a->fd, "  STUN server:            %s:%d\n", ast_inet_ntoa(stunaddr.sin_addr), ntohs(stunaddr.sin_port));
16709  
16710    ast_cli(a->fd, "\nGlobal Signalling Settings:\n");
16711    ast_cli(a->fd, "---------------------------\n");
16712    ast_cli(a->fd, "  Codecs:                 ");
16713    ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, global_capability);
16714    ast_cli(a->fd, "%s\n", codec_buf);
16715    ast_cli(a->fd, "  Codec Order:            ");
16716    print_codec_to_cli(a->fd, &default_prefs);
16717    ast_cli(a->fd, "\n");
16718    ast_cli(a->fd, "  Relax DTMF:             %s\n", cli_yesno(global_relaxdtmf));
16719    ast_cli(a->fd, "  RFC2833 Compensation:   %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE)));
16720    ast_cli(a->fd, "  Compact SIP headers:    %s\n", cli_yesno(sip_cfg.compactheaders));
16721    ast_cli(a->fd, "  RTP Keepalive:          %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
16722    ast_cli(a->fd, "  RTP Timeout:            %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
16723    ast_cli(a->fd, "  RTP Hold Timeout:       %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
16724    ast_cli(a->fd, "  MWI NOTIFY mime type:   %s\n", default_notifymime);
16725    ast_cli(a->fd, "  DNS SRV lookup:         %s\n", cli_yesno(sip_cfg.srvlookup));
16726    ast_cli(a->fd, "  Pedantic SIP support:   %s\n", cli_yesno(sip_cfg.pedanticsipchecking));
16727    ast_cli(a->fd, "  Reg. min duration       %d secs\n", min_expiry);
16728    ast_cli(a->fd, "  Reg. max duration:      %d secs\n", max_expiry);
16729    ast_cli(a->fd, "  Reg. default duration:  %d secs\n", default_expiry);
16730    ast_cli(a->fd, "  Outbound reg. timeout:  %d secs\n", global_reg_timeout);
16731    ast_cli(a->fd, "  Outbound reg. attempts: %d\n", global_regattempts_max);
16732    ast_cli(a->fd, "  Notify ringing state:   %s\n", cli_yesno(sip_cfg.notifyringing));
16733    if (sip_cfg.notifyringing) {
16734       ast_cli(a->fd, "    Include CID:          %s%s\n",
16735             cli_yesno(sip_cfg.notifycid),
16736             sip_cfg.notifycid == IGNORE_CONTEXT ? " (Ignoring context)" : "");
16737    }
16738    ast_cli(a->fd, "  Notify hold state:      %s\n", cli_yesno(sip_cfg.notifyhold));
16739    ast_cli(a->fd, "  SIP Transfer mode:      %s\n", transfermode2str(sip_cfg.allowtransfer));
16740    ast_cli(a->fd, "  Max Call Bitrate:       %d kbps\n", default_maxcallbitrate);
16741    ast_cli(a->fd, "  Auto-Framing:           %s\n", cli_yesno(global_autoframing));
16742    ast_cli(a->fd, "  Outb. proxy:            %s %s\n", ast_strlen_zero(sip_cfg.outboundproxy.name) ? "<not set>" : sip_cfg.outboundproxy.name,
16743                      sip_cfg.outboundproxy.force ? "(forced)" : "");
16744    ast_cli(a->fd, "  Session Timers:         %s\n", stmode2str(global_st_mode));
16745    ast_cli(a->fd, "  Session Refresher:      %s\n", strefresher2str (global_st_refresher));
16746    ast_cli(a->fd, "  Session Expires:        %d secs\n", global_max_se);
16747    ast_cli(a->fd, "  Session Min-SE:         %d secs\n", global_min_se);
16748    ast_cli(a->fd, "  Timer T1:               %d\n", global_t1);
16749    ast_cli(a->fd, "  Timer T1 minimum:       %d\n", global_t1min);
16750    ast_cli(a->fd, "  Timer B:                %d\n", global_timer_b);
16751    ast_cli(a->fd, "  No premature media:     %s\n", global_prematuremediafilter ? "Yes" : "No");
16752 
16753    ast_cli(a->fd, "\nDefault Settings:\n");
16754    ast_cli(a->fd, "-----------------\n");
16755    ast_cli(a->fd, "  Allowed transports:     %s\n", get_transport_list(default_transports)); 
16756    ast_cli(a->fd, "  Outbound transport:    %s\n", get_transport(default_primary_transport));
16757    ast_cli(a->fd, "  Context:                %s\n", sip_cfg.default_context);
16758    ast_cli(a->fd, "  Nat:                    %s\n", nat2str(ast_test_flag(&global_flags[0], SIP_NAT)));
16759    ast_cli(a->fd, "  DTMF:                   %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
16760    ast_cli(a->fd, "  Qualify:                %d\n", default_qualify);
16761    ast_cli(a->fd, "  Use ClientCode:         %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_USECLIENTCODE)));
16762    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" );
16763    ast_cli(a->fd, "  Language:               %s\n", default_language);
16764    ast_cli(a->fd, "  MOH Interpret:          %s\n", default_mohinterpret);
16765    ast_cli(a->fd, "  MOH Suggest:            %s\n", default_mohsuggest);
16766    ast_cli(a->fd, "  Voice Mail Extension:   %s\n", default_vmexten);
16767    ast_cli(a->fd, "  Forward Detected Loops: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_FORWARD_LOOP_DETECTED)));
16768    
16769    if (realtimepeers || realtimeregs) {
16770       ast_cli(a->fd, "\nRealtime SIP Settings:\n");
16771       ast_cli(a->fd, "----------------------\n");
16772       ast_cli(a->fd, "  Realtime Peers:         %s\n", cli_yesno(realtimepeers));
16773       ast_cli(a->fd, "  Realtime Regs:          %s\n", cli_yesno(realtimeregs));
16774       ast_cli(a->fd, "  Cache Friends:          %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)));
16775       ast_cli(a->fd, "  Update:                 %s\n", cli_yesno(sip_cfg.peer_rtupdate));
16776       ast_cli(a->fd, "  Ignore Reg. Expire:     %s\n", cli_yesno(sip_cfg.ignore_regexpire));
16777       ast_cli(a->fd, "  Save sys. name:         %s\n", cli_yesno(sip_cfg.rtsave_sysname));
16778       ast_cli(a->fd, "  Auto Clear:             %d (%s)\n", sip_cfg.rtautoclear, ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR) ? "Enabled" : "Disabled");
16779    }
16780    ast_cli(a->fd, "\n----\n");
16781    return CLI_SUCCESS;
16782 }
16783 
16784 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16785 {
16786 #define FORMAT  "%-30.30s  %-12.12s  %-10.10s  %-10.10s\n"
16787    char host[80];
16788    
16789    switch (cmd) {
16790    case CLI_INIT:
16791       e->command = "sip show mwi";
16792       e->usage =
16793          "Usage: sip show mwi\n"
16794          "       Provides a list of MWI subscriptions and status.\n";
16795       return NULL;
16796    case CLI_GENERATE:
16797       return NULL;
16798    }
16799    
16800    ast_cli(a->fd, FORMAT, "Host", "Username", "Mailbox", "Subscribed");
16801    
16802    ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
16803       ASTOBJ_RDLOCK(iterator);
16804       snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
16805       ast_cli(a->fd, FORMAT, host, iterator->username, iterator->mailbox, iterator->subscribed ? "Yes" : "No");
16806       ASTOBJ_UNLOCK(iterator);
16807    } while(0));
16808 
16809    return CLI_SUCCESS;
16810 #undef FORMAT
16811 }
16812 
16813 
16814 /*! \brief Show subscription type in string format */
16815 static const char *subscription_type2str(enum subscriptiontype subtype)
16816 {
16817    int i;
16818 
16819    for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
16820       if (subscription_types[i].type == subtype) {
16821          return subscription_types[i].text;
16822       }
16823    }
16824    return subscription_types[0].text;
16825 }
16826 
16827 /*! \brief Find subscription type in array */
16828 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
16829 {
16830    int i;
16831 
16832    for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
16833       if (subscription_types[i].type == subtype) {
16834          return &subscription_types[i];
16835       }
16836    }
16837    return &subscription_types[0];
16838 }
16839 
16840 /*
16841  * We try to structure all functions that loop on data structures as
16842  * a handler for individual entries, and a mainloop that iterates
16843  * on the main data structure. This way, moving the code to containers
16844  * that support iteration through callbacks will be a lot easier.
16845  */
16846 
16847 #define FORMAT4 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-13.13s  %-15.15s %-10.10s %-6.6d\n"
16848 #define FORMAT3 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-13.13s  %-15.15s %-10.10s %-6.6s\n"
16849 #define FORMAT2 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-7.7s  %-15.15s %-6.6s\n"
16850 #define FORMAT  "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-3.3s %-3.3s  %-15.15s %-10.10s\n"
16851 
16852 /*! \brief callback for show channel|subscription */
16853 static int show_channels_cb(void *__cur, void *__arg, int flags)
16854 {
16855    struct sip_pvt *cur = __cur;
16856    struct __show_chan_arg *arg = __arg;
16857    const struct sockaddr_in *dst = sip_real_dst(cur);
16858    
16859    /* XXX indentation preserved to reduce diff. Will be fixed later */
16860    if (cur->subscribed == NONE && !arg->subscriptions) {
16861       /* set if SIP transfer in progress */
16862       const char *referstatus = cur->refer ? referstatus2str(cur->refer->status) : "";
16863       char formatbuf[SIPBUFSIZE/2];
16864       
16865       ast_cli(arg->fd, FORMAT, ast_inet_ntoa(dst->sin_addr), 
16866             S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
16867             cur->callid, 
16868             ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0),
16869             cli_yesno(ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD)),
16870             cur->needdestroy ? "(d)" : "",
16871             cur->lastmsg ,
16872             referstatus
16873          );
16874       arg->numchans++;
16875    }
16876    if (cur->subscribed != NONE && arg->subscriptions) {
16877       struct ast_str *mailbox_str = ast_str_alloca(512);
16878       if (cur->subscribed == MWI_NOTIFICATION && cur->relatedpeer)
16879          peer_mailboxes_to_str(&mailbox_str, cur->relatedpeer);
16880       ast_cli(arg->fd, FORMAT4, ast_inet_ntoa(dst->sin_addr),
16881             S_OR(cur->username, S_OR(cur->cid_num, "(None)")), 
16882                cur->callid,
16883             /* the 'complete' exten/context is hidden in the refer_to field for subscriptions */
16884             cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
16885             cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate), 
16886             subscription_type2str(cur->subscribed),
16887             cur->subscribed == MWI_NOTIFICATION ? S_OR(mailbox_str->str, "<none>") : "<none>",
16888             cur->expiry
16889          );
16890       arg->numchans++;
16891    }
16892    return 0;   /* don't care, we scan all channels */
16893 }
16894 
16895 /*! \brief CLI for show channels or subscriptions.
16896  * This is a new-style CLI handler so a single function contains
16897  * the prototype for the function, the 'generator' to produce multiple
16898  * entries in case it is required, and the actual handler for the command.
16899  */
16900 static char *sip_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16901 {
16902    struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
16903 
16904 
16905    if (cmd == CLI_INIT) {
16906       e->command = "sip show {channels|subscriptions}";
16907       e->usage =
16908          "Usage: sip show channels\n"
16909          "       Lists all currently active SIP calls (dialogs).\n"
16910          "Usage: sip show subscriptions\n"
16911          "       Lists active SIP subscriptions.\n";
16912       return NULL;
16913    } else if (cmd == CLI_GENERATE)
16914       return NULL;
16915 
16916    if (a->argc != e->args)
16917       return CLI_SHOWUSAGE;
16918    arg.subscriptions = !strcasecmp(a->argv[e->args - 1], "subscriptions");
16919    if (!arg.subscriptions)
16920       ast_cli(arg.fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Format", "Hold", "Last Message", "Expiry");
16921    else
16922       ast_cli(arg.fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox", "Expiry");
16923 
16924    /* iterate on the container and invoke the callback on each item */
16925    ao2_t_callback(dialogs, OBJ_NODATA, show_channels_cb, &arg, "callback to show channels");
16926    
16927    /* print summary information */
16928    ast_cli(arg.fd, "%d active SIP %s%s\n", arg.numchans,
16929       (arg.subscriptions ? "subscription" : "dialog"),
16930       ESS(arg.numchans));  /* ESS(n) returns an "s" if n>1 */
16931    return CLI_SUCCESS;
16932 #undef FORMAT
16933 #undef FORMAT2
16934 #undef FORMAT3
16935 }
16936 
16937 /*! \brief Support routine for 'sip show channel' and 'sip show history' CLI
16938  * This is in charge of generating all strings that match a prefix in the
16939  * given position. As many functions of this kind, each invokation has
16940  * O(state) time complexity so be careful in using it.
16941  */
16942 static char *complete_sipch(const char *line, const char *word, int pos, int state)
16943 {
16944    int which=0;
16945    struct sip_pvt *cur;
16946    char *c = NULL;
16947    int wordlen = strlen(word);
16948    struct ao2_iterator i;
16949 
16950    if (pos != 3) {
16951       return NULL;
16952    }
16953 
16954    i = ao2_iterator_init(dialogs, 0);
16955    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
16956       sip_pvt_lock(cur);
16957       if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
16958          c = ast_strdup(cur->callid);
16959          sip_pvt_unlock(cur);
16960          dialog_unref(cur, "drop ref in iterator loop break");
16961          break;
16962       }
16963       sip_pvt_unlock(cur);
16964       dialog_unref(cur, "drop ref in iterator loop");
16965    }
16966    ao2_iterator_destroy(&i);
16967    return c;
16968 }
16969 
16970 
16971 /*! \brief Do completion on peer name */
16972 static char *complete_sip_peer(const char *word, int state, int flags2)
16973 {
16974    char *result = NULL;
16975    int wordlen = strlen(word);
16976    int which = 0;
16977    struct ao2_iterator i = ao2_iterator_init(peers, 0);
16978    struct sip_peer *peer;
16979 
16980    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
16981       /* locking of the object is not required because only the name and flags are being compared */
16982       if (!strncasecmp(word, peer->name, wordlen) &&
16983             (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
16984             ++which > state)
16985          result = ast_strdup(peer->name);
16986       unref_peer(peer, "toss iterator peer ptr before break");
16987       if (result) {
16988          break;
16989       }
16990    }
16991    ao2_iterator_destroy(&i);
16992    return result;
16993 }
16994 
16995 /*! \brief Do completion on registered peer name */
16996 static char *complete_sip_registered_peer(const char *word, int state, int flags2)
16997 {
16998        char *result = NULL;
16999        int wordlen = strlen(word);
17000        int which = 0;
17001        struct ao2_iterator i;
17002        struct sip_peer *peer;
17003        
17004        i = ao2_iterator_init(peers, 0);
17005        while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
17006           if (!strncasecmp(word, peer->name, wordlen) &&
17007          (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
17008          ++which > state && peer->expire > 0)
17009              result = ast_strdup(peer->name);
17010           if (result) {
17011              unref_peer(peer, "toss iterator peer ptr before break");
17012              break;
17013           }
17014           unref_peer(peer, "toss iterator peer ptr");
17015        }
17016        ao2_iterator_destroy(&i);
17017        return result;
17018 }
17019 
17020 /*! \brief Support routine for 'sip show history' CLI */
17021 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state)
17022 {
17023    if (pos == 3)
17024       return complete_sipch(line, word, pos, state);
17025 
17026    return NULL;
17027 }
17028 
17029 /*! \brief Support routine for 'sip show peer' CLI */
17030 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
17031 {
17032    if (pos == 3) {
17033       return complete_sip_peer(word, state, 0);
17034    }
17035 
17036    return NULL;
17037 }
17038 
17039 /*! \brief Support routine for 'sip unregister' CLI */
17040 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state)
17041 {
17042        if (pos == 2)
17043                return complete_sip_registered_peer(word, state, 0);
17044 
17045        return NULL;
17046 }
17047 
17048 /*! \brief Support routine for 'sip notify' CLI */
17049 static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
17050 {
17051    char *c = NULL;
17052 
17053    if (pos == 2) {
17054       int which = 0;
17055       char *cat = NULL;
17056       int wordlen = strlen(word);
17057 
17058       /* do completion for notify type */
17059 
17060       if (!notify_types)
17061          return NULL;
17062       
17063       while ( (cat = ast_category_browse(notify_types, cat)) ) {
17064          if (!strncasecmp(word, cat, wordlen) && ++which > state) {
17065             c = ast_strdup(cat);
17066             break;
17067          }
17068       }
17069       return c;
17070    }
17071 
17072    if (pos > 2)
17073       return complete_sip_peer(word, state, 0);
17074 
17075    return NULL;
17076 }
17077 
17078 /*! \brief Show details of one active dialog */
17079 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17080 {
17081    struct sip_pvt *cur;
17082    size_t len;
17083    int found = 0;
17084    struct ao2_iterator i;
17085 
17086    switch (cmd) {
17087    case CLI_INIT:
17088       e->command = "sip show channel";
17089       e->usage =
17090          "Usage: sip show channel <call-id>\n"
17091          "       Provides detailed status on a given SIP dialog (identified by SIP call-id).\n";
17092       return NULL;
17093    case CLI_GENERATE:
17094       return complete_sipch(a->line, a->word, a->pos, a->n);
17095    }
17096 
17097    if (a->argc != 4)
17098       return CLI_SHOWUSAGE;
17099    len = strlen(a->argv[3]);
17100    
17101    i = ao2_iterator_init(dialogs, 0);
17102    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
17103       sip_pvt_lock(cur);
17104 
17105       if (!strncasecmp(cur->callid, a->argv[3], len)) {
17106          char formatbuf[SIPBUFSIZE/2];
17107          ast_cli(a->fd, "\n");
17108          if (cur->subscribed != NONE)
17109             ast_cli(a->fd, "  * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
17110          else
17111             ast_cli(a->fd, "  * SIP Call\n");
17112          ast_cli(a->fd, "  Curr. trans. direction:  %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
17113          ast_cli(a->fd, "  Call-ID:                %s\n", cur->callid);
17114          ast_cli(a->fd, "  Owner channel ID:       %s\n", cur->owner ? cur->owner->name : "<none>");
17115          ast_cli(a->fd, "  Our Codec Capability:   %d\n", cur->capability);
17116          ast_cli(a->fd, "  Non-Codec Capability (DTMF):   %d\n", cur->noncodeccapability);
17117          ast_cli(a->fd, "  Their Codec Capability:   %d\n", cur->peercapability);
17118          ast_cli(a->fd, "  Joint Codec Capability:   %d\n", cur->jointcapability);
17119          ast_cli(a->fd, "  Format:                 %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
17120          ast_cli(a->fd, "  T.38 support            %s\n", cli_yesno(cur->udptl != NULL));
17121          ast_cli(a->fd, "  Video support           %s\n", cli_yesno(cur->vrtp != NULL));
17122          ast_cli(a->fd, "  MaxCallBR:              %d kbps\n", cur->maxcallbitrate);
17123          ast_cli(a->fd, "  Theoretical Address:    %s:%d\n", ast_inet_ntoa(cur->sa.sin_addr), ntohs(cur->sa.sin_port));
17124          ast_cli(a->fd, "  Received Address:       %s:%d\n", ast_inet_ntoa(cur->recv.sin_addr), ntohs(cur->recv.sin_port));
17125          ast_cli(a->fd, "  SIP Transfer mode:      %s\n", transfermode2str(cur->allowtransfer));
17126          ast_cli(a->fd, "  NAT Support:            %s\n", nat2str(ast_test_flag(&cur->flags[0], SIP_NAT)));
17127          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)" );
17128          ast_cli(a->fd, "  Our Tag:                %s\n", cur->tag);
17129          ast_cli(a->fd, "  Their Tag:              %s\n", cur->theirtag);
17130          ast_cli(a->fd, "  SIP User agent:         %s\n", cur->useragent);
17131          if (!ast_strlen_zero(cur->username))
17132             ast_cli(a->fd, "  Username:               %s\n", cur->username);
17133          if (!ast_strlen_zero(cur->peername))
17134             ast_cli(a->fd, "  Peername:               %s\n", cur->peername);
17135          if (!ast_strlen_zero(cur->uri))
17136             ast_cli(a->fd, "  Original uri:           %s\n", cur->uri);
17137          if (!ast_strlen_zero(cur->cid_num))
17138             ast_cli(a->fd, "  Caller-ID:              %s\n", cur->cid_num);
17139          ast_cli(a->fd, "  Need Destroy:           %s\n", cli_yesno(cur->needdestroy));
17140          ast_cli(a->fd, "  Last Message:           %s\n", cur->lastmsg);
17141          ast_cli(a->fd, "  Promiscuous Redir:      %s\n", cli_yesno(ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR)));
17142          ast_cli(a->fd, "  Route:                  %s\n", cur->route ? cur->route->hop : "N/A");
17143          ast_cli(a->fd, "  DTMF Mode:              %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
17144          ast_cli(a->fd, "  SIP Options:            ");
17145          if (cur->sipoptions) {
17146             int x;
17147             for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
17148                if (cur->sipoptions & sip_options[x].id)
17149                   ast_cli(a->fd, "%s ", sip_options[x].text);
17150             }
17151             ast_cli(a->fd, "\n");
17152          } else
17153             ast_cli(a->fd, "(none)\n");
17154 
17155          if (!cur->stimer)
17156             ast_cli(a->fd, "  Session-Timer:          Uninitiallized\n");
17157          else {
17158             ast_cli(a->fd, "  Session-Timer:          %s\n", cur->stimer->st_active ? "Active" : "Inactive");
17159             if (cur->stimer->st_active == TRUE) {
17160                ast_cli(a->fd, "  S-Timer Interval:       %d\n", cur->stimer->st_interval);
17161                ast_cli(a->fd, "  S-Timer Refresher:      %s\n", strefresher2str(cur->stimer->st_ref));
17162                ast_cli(a->fd, "  S-Timer Expirys:        %d\n", cur->stimer->st_expirys);
17163                ast_cli(a->fd, "  S-Timer Sched Id:       %d\n", cur->stimer->st_schedid);
17164                ast_cli(a->fd, "  S-Timer Peer Sts:       %s\n", cur->stimer->st_active_peer_ua ? "Active" : "Inactive");
17165                ast_cli(a->fd, "  S-Timer Cached Min-SE:  %d\n", cur->stimer->st_cached_min_se);
17166                ast_cli(a->fd, "  S-Timer Cached SE:      %d\n", cur->stimer->st_cached_max_se);
17167                ast_cli(a->fd, "  S-Timer Cached Ref:     %s\n", strefresher2str(cur->stimer->st_cached_ref));
17168                ast_cli(a->fd, "  S-Timer Cached Mode:    %s\n", stmode2str(cur->stimer->st_cached_mode));
17169             }
17170          }
17171 
17172          ast_cli(a->fd, "\n\n");
17173 
17174          found++;
17175       }
17176 
17177       sip_pvt_unlock(cur);
17178 
17179       ao2_t_ref(cur, -1, "toss dialog ptr set by iterator_next");
17180    }
17181    ao2_iterator_destroy(&i);
17182 
17183    if (!found) 
17184       ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
17185 
17186    return CLI_SUCCESS;
17187 }
17188 
17189 /*! \brief Show history details of one dialog */
17190 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17191 {
17192    struct sip_pvt *cur;
17193    size_t len;
17194    int found = 0;
17195    struct ao2_iterator i;
17196 
17197    switch (cmd) {
17198    case CLI_INIT:
17199       e->command = "sip show history";
17200       e->usage =
17201          "Usage: sip show history <call-id>\n"
17202          "       Provides detailed dialog history on a given SIP call (specified by call-id).\n";
17203       return NULL;
17204    case CLI_GENERATE:
17205       return complete_sip_show_history(a->line, a->word, a->pos, a->n);
17206    }
17207 
17208    if (a->argc != 4)
17209       return CLI_SHOWUSAGE;
17210 
17211    if (!recordhistory)
17212       ast_cli(a->fd, "\n***Note: History recording is currently DISABLED.  Use 'sip set history on' to ENABLE.\n");
17213 
17214    len = strlen(a->argv[3]);
17215 
17216    i = ao2_iterator_init(dialogs, 0);
17217    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
17218       sip_pvt_lock(cur);
17219       if (!strncasecmp(cur->callid, a->argv[3], len)) {
17220          struct sip_history *hist;
17221          int x = 0;
17222 
17223          ast_cli(a->fd, "\n");
17224          if (cur->subscribed != NONE)
17225             ast_cli(a->fd, "  * Subscription\n");
17226          else
17227             ast_cli(a->fd, "  * SIP Call\n");
17228          if (cur->history)
17229             AST_LIST_TRAVERSE(cur->history, hist, list)
17230                ast_cli(a->fd, "%d. %s\n", ++x, hist->event);
17231          if (x == 0)
17232             ast_cli(a->fd, "Call '%s' has no history\n", cur->callid);
17233          found++;
17234       }
17235       sip_pvt_unlock(cur);
17236       ao2_t_ref(cur, -1, "toss dialog ptr from iterator_next");
17237    }
17238    ao2_iterator_destroy(&i);
17239 
17240    if (!found) 
17241       ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
17242 
17243    return CLI_SUCCESS;
17244 }
17245 
17246 /*! \brief Dump SIP history to debug log file at end of lifespan for SIP dialog */
17247 static void sip_dump_history(struct sip_pvt *dialog)
17248 {
17249    int x = 0;
17250    struct sip_history *hist;
17251    static int errmsg = 0;
17252 
17253    if (!dialog)
17254       return;
17255 
17256    if (!option_debug && !sipdebug) {
17257       if (!errmsg) {
17258          ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
17259          errmsg = 1;
17260       }
17261       return;
17262    }
17263 
17264    ast_debug(1, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
17265    if (dialog->subscribed)
17266       ast_debug(1, "  * Subscription\n");
17267    else
17268       ast_debug(1, "  * SIP Call\n");
17269    if (dialog->history)
17270       AST_LIST_TRAVERSE(dialog->history, hist, list)
17271          ast_debug(1, "  %-3.3d. %s\n", ++x, hist->event);
17272    if (!x)
17273       ast_debug(1, "Call '%s' has no history\n", dialog->callid);
17274    ast_debug(1, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
17275 }
17276 
17277 
17278 /*! \brief  Receive SIP INFO Message */
17279 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
17280 {
17281    char buf[1024];
17282    unsigned int event;
17283    const char *c = get_header(req, "Content-Type");
17284 
17285    /* Need to check the media/type */
17286    if (!strcasecmp(c, "application/dtmf-relay") ||
17287        !strcasecmp(c, "application/vnd.nortelnetworks.digits")) {
17288       unsigned int duration = 0;
17289 
17290       if (!p->owner) {  /* not a PBX call */
17291          transmit_response(p, "481 Call leg/transaction does not exist", req);
17292          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17293          return;
17294       }
17295 
17296       /* Try getting the "signal=" part */
17297       if (ast_strlen_zero(c = get_body(req, "Signal", '=')) && ast_strlen_zero(c = get_body(req, "d", '='))) {
17298          ast_log(LOG_WARNING, "Unable to retrieve DTMF signal from INFO message from %s\n", p->callid);
17299          transmit_response(p, "200 OK", req); /* Should return error */
17300          return;
17301       } else {
17302          ast_copy_string(buf, c, sizeof(buf));
17303       }
17304 
17305       if (!ast_strlen_zero((c = get_body(req, "Duration", '='))))
17306          duration = atoi(c);
17307       if (!duration)
17308          duration = 100; /* 100 ms */
17309 
17310 
17311       if (ast_strlen_zero(buf)) {
17312          transmit_response(p, "200 OK", req);
17313          return;
17314       }
17315 
17316       if (buf[0] == '*')
17317          event = 10;
17318       else if (buf[0] == '#')
17319          event = 11;
17320       else if ((buf[0] >= 'A') && (buf[0] <= 'D'))
17321          event = 12 + buf[0] - 'A';
17322       else if (buf[0] == '!')
17323          event = 16;
17324       else
17325          event = atoi(buf);
17326       if (event == 16) {
17327          /* send a FLASH event */
17328          struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
17329          ast_queue_frame(p->owner, &f);
17330          if (sipdebug)
17331             ast_verbose("* DTMF-relay event received: FLASH\n");
17332       } else {
17333          /* send a DTMF event */
17334          struct ast_frame f = { AST_FRAME_DTMF, };
17335          if (event < 10) {
17336             f.subclass = '0' + event;
17337          } else if (event < 11) {
17338             f.subclass = '*';
17339          } else if (event < 12) {
17340             f.subclass = '#';
17341          } else if (event < 16) {
17342             f.subclass = 'A' + (event - 12);
17343          }
17344          f.len = duration;
17345          ast_queue_frame(p->owner, &f);
17346          if (sipdebug)
17347             ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
17348       }
17349       transmit_response(p, "200 OK", req);
17350       return;
17351    } else if (!strcasecmp(c, "application/dtmf")) {
17352       /*! \todo Note: Doesn't read the duration of the DTMF. Should be fixed. */
17353       unsigned int duration = 0;
17354 
17355       if (!p->owner) {  /* not a PBX call */
17356          transmit_response(p, "481 Call leg/transaction does not exist", req);
17357          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17358          return;
17359       }
17360 
17361       get_msg_text(buf, sizeof(buf), req, TRUE);
17362       duration = 100; /* 100 ms */
17363 
17364       if (ast_strlen_zero(buf)) {
17365          transmit_response(p, "200 OK", req);
17366          return;
17367       }
17368       event = atoi(buf);
17369       if (event == 16) {
17370          /* send a FLASH event */
17371          struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
17372          ast_queue_frame(p->owner, &f);
17373          if (sipdebug)
17374             ast_verbose("* DTMF-relay event received: FLASH\n");
17375       } else {
17376          /* send a DTMF event */
17377          struct ast_frame f = { AST_FRAME_DTMF, };
17378          if (event < 10) {
17379             f.subclass = '0' + event;
17380          } else if (event < 11) {
17381             f.subclass = '*';
17382          } else if (event < 12) {
17383             f.subclass = '#';
17384          } else if (event < 16) {
17385             f.subclass = 'A' + (event - 12);
17386          }
17387          f.len = duration;
17388          ast_queue_frame(p->owner, &f);
17389          if (sipdebug)
17390             ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
17391       }
17392       transmit_response(p, "200 OK", req);
17393       return;
17394 
17395    } else if (!strcasecmp(c, "application/media_control+xml")) {
17396       /* Eh, we'll just assume it's a fast picture update for now */
17397       if (p->owner)
17398          ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
17399       transmit_response(p, "200 OK", req);
17400       return;
17401    } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
17402       /* Client code (from SNOM phone) */
17403       if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
17404          if (p->owner && p->owner->cdr)
17405             ast_cdr_setuserfield(p->owner, c);
17406          if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
17407             ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
17408          transmit_response(p, "200 OK", req);
17409       } else {
17410          transmit_response(p, "403 Forbidden", req);
17411       }
17412       return;
17413    } else if (!ast_strlen_zero(c = get_header(req, "Record"))) {
17414       /* INFO messages generated by some phones to start/stop recording
17415          on phone calls. 
17416          OEJ: I think this should be something that is enabled/disabled
17417          per device. I don't want incoming callers to record calls in my
17418          pbx.
17419       */
17420       /* first, get the feature string, if it exists */
17421       struct ast_call_feature *feat;
17422       int j;
17423       struct ast_frame f = { AST_FRAME_DTMF, };
17424 
17425       ast_rdlock_call_features();
17426       feat = ast_find_call_feature("automon");
17427       if (!feat || ast_strlen_zero(feat->exten)) {
17428          ast_log(LOG_WARNING, "Recording requested, but no One Touch Monitor registered. (See features.conf)\n");
17429          /* 403 means that we don't support this feature, so don't request it again */
17430          transmit_response(p, "403 Forbidden", req);
17431          ast_unlock_call_features();
17432          return;
17433       } 
17434       /* Send the feature code to the PBX as DTMF, just like the handset had sent it */
17435       f.len = 100;
17436       for (j=0; j < strlen(feat->exten); j++) {
17437          f.subclass = feat->exten[j];
17438          ast_queue_frame(p->owner, &f);
17439          if (sipdebug)
17440             ast_verbose("* DTMF-relay event faked: %c\n", f.subclass);
17441       }
17442       ast_unlock_call_features();
17443 
17444       ast_debug(1, "Got a Request to Record the channel, state %s\n", c);
17445       transmit_response(p, "200 OK", req);
17446       return;
17447    } else if (ast_strlen_zero(c = get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
17448       /* This is probably just a packet making sure the signalling is still up, just send back a 200 OK */
17449       transmit_response(p, "200 OK", req);
17450       return;
17451    }
17452 
17453    /* Other type of INFO message, not really understood by Asterisk */
17454    /* if (get_msg_text(buf, sizeof(buf), req)) { */
17455 
17456    ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
17457    transmit_response(p, "415 Unsupported media type", req);
17458    return;
17459 }
17460 
17461 /*! \brief Enable SIP Debugging for a single IP */
17462 static char *sip_do_debug_ip(int fd, char *arg)
17463 {
17464    struct hostent *hp;
17465    struct ast_hostent ahp;
17466    int port = 0;
17467    char *p;
17468 
17469    p = arg;
17470    strsep(&p, ":");
17471    if (p)
17472       port = atoi(p);
17473    hp = ast_gethostbyname(arg, &ahp);
17474    if (hp == NULL)
17475       return CLI_SHOWUSAGE;
17476 
17477    debugaddr.sin_family = AF_INET;
17478    memcpy(&debugaddr.sin_addr, hp->h_addr, sizeof(debugaddr.sin_addr));
17479    debugaddr.sin_port = htons(port);
17480    if (port == 0)
17481       ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_inet_ntoa(debugaddr.sin_addr));
17482    else
17483       ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), port);
17484 
17485    sipdebug |= sip_debug_console;
17486 
17487    return CLI_SUCCESS;
17488 }
17489 
17490 /*! \brief  Turn on SIP debugging for a given peer */
17491 static char *sip_do_debug_peer(int fd, char *arg)
17492 {
17493    struct sip_peer *peer = find_peer(arg, NULL, TRUE, FINDPEERS, FALSE, 0);
17494    if (!peer)
17495       ast_cli(fd, "No such peer '%s'\n", arg);
17496    else if (peer->addr.sin_addr.s_addr == 0)
17497       ast_cli(fd, "Unable to get IP address of peer '%s'\n", arg);
17498    else {
17499       debugaddr.sin_family = AF_INET;
17500       debugaddr.sin_addr = peer->addr.sin_addr;
17501       debugaddr.sin_port = peer->addr.sin_port;
17502       ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n",
17503          ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
17504       sipdebug |= sip_debug_console;
17505    }
17506    if (peer)
17507       unref_peer(peer, "sip_do_debug_peer: unref_peer, from find_peer call");
17508    return CLI_SUCCESS;
17509 }
17510 
17511 /*! \brief Turn on SIP debugging (CLI command) */
17512 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17513 {
17514    int oldsipdebug = sipdebug & sip_debug_console;
17515    char *what;
17516 
17517    if (cmd == CLI_INIT) {
17518       e->command = "sip set debug {on|off|ip|peer}";
17519       e->usage =
17520          "Usage: sip set debug {off|on|ip addr[:port]|peer peername}\n"
17521          "       Globally disables dumping of SIP packets,\n"
17522          "       or enables it either globally or for a (single)\n"
17523          "       IP address or registered peer.\n";
17524       return NULL;
17525    } else if (cmd == CLI_GENERATE) {
17526       if (a->pos == 4 && !strcasecmp(a->argv[3], "peer")) 
17527          return complete_sip_peer(a->word, a->n, 0);
17528       return NULL;
17529         }
17530 
17531    what = a->argv[e->args-1];      /* guaranteed to exist */
17532    if (a->argc == e->args) {       /* on/off */
17533       if (!strcasecmp(what, "on")) {
17534          sipdebug |= sip_debug_console;
17535          sipdebug_text = 1;   /*! \note this can be a special debug command - "sip debug text" or something */
17536          memset(&debugaddr, 0, sizeof(debugaddr));
17537          ast_cli(a->fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
17538          return CLI_SUCCESS;
17539       } else if (!strcasecmp(what, "off")) {
17540          sipdebug &= ~sip_debug_console;
17541          sipdebug_text = 0;
17542          ast_cli(a->fd, "SIP Debugging Disabled\n");
17543          return CLI_SUCCESS;
17544       }
17545    } else if (a->argc == e->args +1) {/* ip/peer */
17546       if (!strcasecmp(what, "ip"))
17547          return sip_do_debug_ip(a->fd, a->argv[e->args]);
17548       else if (!strcasecmp(what, "peer"))
17549          return sip_do_debug_peer(a->fd, a->argv[e->args]);
17550    }
17551    return CLI_SHOWUSAGE;   /* default, failure */
17552 }
17553 
17554 /*! \brief Cli command to send SIP notify to peer */
17555 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17556 {
17557    struct ast_variable *varlist;
17558    int i;
17559 
17560    switch (cmd) {
17561    case CLI_INIT:
17562       e->command = "sip notify";
17563       e->usage =
17564          "Usage: sip notify <type> <peer> [<peer>...]\n"
17565          "       Send a NOTIFY message to a SIP peer or peers\n"
17566          "       Message types are defined in sip_notify.conf\n";
17567       return NULL;
17568    case CLI_GENERATE:
17569       return complete_sipnotify(a->line, a->word, a->pos, a->n);
17570    }
17571 
17572    if (a->argc < 4)
17573       return CLI_SHOWUSAGE;
17574 
17575    if (!notify_types) {
17576       ast_cli(a->fd, "No %s file found, or no types listed there\n", notify_config);
17577       return CLI_FAILURE;
17578    }
17579 
17580    varlist = ast_variable_browse(notify_types, a->argv[2]);
17581 
17582    if (!varlist) {
17583       ast_cli(a->fd, "Unable to find notify type '%s'\n", a->argv[2]);
17584       return CLI_FAILURE;
17585    }
17586 
17587    for (i = 3; i < a->argc; i++) {
17588       struct sip_pvt *p;
17589 
17590       if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
17591          ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
17592          return CLI_FAILURE;
17593       }
17594 
17595       if (create_addr(p, a->argv[i], NULL, 1)) {
17596          /* Maybe they're not registered, etc. */
17597          dialog_unlink_all(p, TRUE, TRUE);
17598          dialog_unref(p, "unref dialog inside for loop" );
17599          /* sip_destroy(p); */
17600          ast_cli(a->fd, "Could not create address for '%s'\n", a->argv[i]);
17601          continue;
17602       }
17603 
17604       /* Notify is outgoing call */
17605       ast_set_flag(&p->flags[0], SIP_OUTGOING);
17606 
17607       /* Recalculate our side, and recalculate Call ID */
17608       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
17609       build_via(p);
17610       ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
17611       build_callid_pvt(p);
17612       ao2_t_link(dialogs, p, "Linking in new name");
17613       ast_cli(a->fd, "Sending NOTIFY of type '%s' to '%s'\n", a->argv[2], a->argv[i]);
17614       dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
17615       sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
17616       transmit_notify_custom(p, varlist);
17617    }
17618 
17619    return CLI_SUCCESS;
17620 }
17621 
17622 /*! \brief Enable/Disable SIP History logging (CLI) */
17623 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17624 {
17625    switch (cmd) {
17626    case CLI_INIT:
17627       e->command = "sip set history {on|off}";
17628       e->usage =
17629          "Usage: sip set history {on|off}\n"
17630          "       Enables/Disables recording of SIP dialog history for debugging purposes.\n"
17631          "       Use 'sip show history' to view the history of a call number.\n";
17632       return NULL;
17633    case CLI_GENERATE:
17634       return NULL;
17635    }
17636 
17637    if (a->argc != e->args)
17638       return CLI_SHOWUSAGE;
17639 
17640    if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
17641       recordhistory = TRUE;
17642       ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
17643    } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
17644       recordhistory = FALSE;
17645       ast_cli(a->fd, "SIP History Recording Disabled\n");
17646    } else {
17647       return CLI_SHOWUSAGE;
17648    }
17649    return CLI_SUCCESS;
17650 }
17651 
17652 /*! \brief Authenticate for outbound registration */
17653 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code)
17654 {
17655    char *header, *respheader;
17656    char digest[1024];
17657 
17658    p->authtries++;
17659    auth_headers(code, &header, &respheader);
17660    memset(digest, 0, sizeof(digest));
17661    if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
17662       /* There's nothing to use for authentication */
17663       /* No digest challenge in request */
17664       if (sip_debug_test_pvt(p) && p->registry)
17665          ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
17666          /* No old challenge */
17667       return -1;
17668    }
17669    if (p->do_history)
17670       append_history(p, "RegistryAuth", "Try: %d", p->authtries);
17671    if (sip_debug_test_pvt(p) && p->registry)
17672       ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
17673    return transmit_register(p->registry, SIP_REGISTER, digest, respheader); 
17674 }
17675 
17676 /*! \brief Add authentication on outbound SIP packet */
17677 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code, int sipmethod, int init)
17678 {
17679    char *header, *respheader;
17680    char digest[1024];
17681 
17682    if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
17683       return -2;
17684 
17685    p->authtries++;
17686    auth_headers(code, &header, &respheader);
17687    ast_debug(2, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
17688    memset(digest, 0, sizeof(digest));
17689    if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
17690       /* No way to authenticate */
17691       return -1;
17692    }
17693    /* Now we have a reply digest */
17694    p->options->auth = digest;
17695    p->options->authheader = respheader;
17696    return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init); 
17697 }
17698 
17699 /*! \brief  reply to authentication for outbound registrations
17700 \return  Returns -1 if we have no auth 
17701 \note This is used for register= servers in sip.conf, SIP proxies we register
17702    with  for receiving calls from.  */
17703 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod,  char *digest, int digest_len)
17704 {
17705    char tmp[512];
17706    char *c;
17707    char oldnonce[256];
17708 
17709    /* table of recognised keywords, and places where they should be copied */
17710    const struct x {
17711       const char *key;
17712       const ast_string_field *field;
17713    } *i, keys[] = {
17714       { "realm=", &p->realm },
17715       { "nonce=", &p->nonce },
17716       { "opaque=", &p->opaque },
17717       { "qop=", &p->qop },
17718       { "domain=", &p->domain },
17719       { NULL, 0 },
17720    };
17721 
17722    ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
17723    if (ast_strlen_zero(tmp)) 
17724       return -1;
17725    if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
17726       ast_log(LOG_WARNING, "missing Digest.\n");
17727       return -1;
17728    }
17729    c = tmp + strlen("Digest ");
17730    ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
17731    while (c && *(c = ast_skip_blanks(c))) {  /* lookup for keys */
17732       for (i = keys; i->key != NULL; i++) {
17733          char *src, *separator;
17734          if (strncasecmp(c, i->key, strlen(i->key)) != 0)
17735             continue;
17736          /* Found. Skip keyword, take text in quotes or up to the separator. */
17737          c += strlen(i->key);
17738          if (*c == '"') {
17739             src = ++c;
17740             separator = "\"";
17741          } else {
17742             src = c;
17743             separator = ",";
17744          }
17745          strsep(&c, separator); /* clear separator and move ptr */
17746          ast_string_field_ptr_set(p, i->field, src);
17747          break;
17748       }
17749       if (i->key == NULL) /* not found, try ',' */
17750          strsep(&c, ",");
17751    }
17752    /* Reset nonce count */
17753    if (strcmp(p->nonce, oldnonce)) 
17754       p->noncecount = 0;
17755 
17756    /* Save auth data for following registrations */
17757    if (p->registry) {
17758       struct sip_registry *r = p->registry;
17759 
17760       if (strcmp(r->nonce, p->nonce)) {
17761          ast_string_field_set(r, realm, p->realm);
17762          ast_string_field_set(r, nonce, p->nonce);
17763          ast_string_field_set(r, domain, p->domain);
17764          ast_string_field_set(r, opaque, p->opaque);
17765          ast_string_field_set(r, qop, p->qop);
17766          r->noncecount = 0;
17767       }
17768    }
17769    return build_reply_digest(p, sipmethod, digest, digest_len); 
17770 }
17771 
17772 /*! \brief  Build reply digest 
17773 \return  Returns -1 if we have no auth 
17774 \note Build digest challenge for authentication of registrations and calls
17775    Also used for authentication of BYE 
17776 */
17777 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
17778 {
17779    char a1[256];
17780    char a2[256];
17781    char a1_hash[256];
17782    char a2_hash[256];
17783    char resp[256];
17784    char resp_hash[256];
17785    char uri[256];
17786    char opaque[256] = "";
17787    char cnonce[80];
17788    const char *username;
17789    const char *secret;
17790    const char *md5secret;
17791    struct sip_auth *auth = NULL; /* Realm authentication */
17792 
17793    if (!ast_strlen_zero(p->domain))
17794       ast_copy_string(uri, p->domain, sizeof(uri));
17795    else if (!ast_strlen_zero(p->uri))
17796       ast_copy_string(uri, p->uri, sizeof(uri));
17797    else
17798       snprintf(uri, sizeof(uri), "sip:%s@%s", p->username, ast_inet_ntoa(p->sa.sin_addr));
17799 
17800    snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
17801 
17802    /* Check if we have separate auth credentials */
17803    if(!(auth = find_realm_authentication(p->peerauth, p->realm))) /* Start with peer list */
17804       auth = find_realm_authentication(authl, p->realm); /* If not, global list */
17805 
17806    if (auth) {
17807       ast_debug(3, "use realm [%s] from peer [%s][%s]\n", auth->username, p->peername, p->username);
17808       username = auth->username;
17809       secret = auth->secret;
17810       md5secret = auth->md5secret;
17811       if (sipdebug)
17812          ast_debug(1, "Using realm %s authentication for call %s\n", p->realm, p->callid);
17813    } else {
17814       /* No authentication, use peer or register= config */
17815       username = p->authname;
17816       secret = p->relatedpeer 
17817          && !ast_strlen_zero(p->relatedpeer->remotesecret)
17818          ? p->relatedpeer->remotesecret : p->peersecret;
17819       md5secret = p->peermd5secret;
17820    }
17821    if (ast_strlen_zero(username))   /* We have no authentication */
17822       return -1;
17823 
17824    /* Calculate SIP digest response */
17825    snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
17826    snprintf(a2, sizeof(a2), "%s:%s", sip_methods[method].text, uri);
17827    if (!ast_strlen_zero(md5secret))
17828       ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
17829    else
17830       ast_md5_hash(a1_hash, a1);
17831    ast_md5_hash(a2_hash, a2);
17832 
17833    p->noncecount++;
17834    if (!ast_strlen_zero(p->qop))
17835       snprintf(resp, sizeof(resp), "%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
17836    else
17837       snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, p->nonce, a2_hash);
17838    ast_md5_hash(resp_hash, resp);
17839 
17840    /* only include the opaque string if it's set */
17841    if (!ast_strlen_zero(p->opaque)) {
17842      snprintf(opaque, sizeof(opaque), ", opaque=\"%s\"", p->opaque);
17843    }
17844 
17845    /* XXX We hard code our qop to "auth" for now.  XXX */
17846    if (!ast_strlen_zero(p->qop))
17847       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);
17848    else
17849       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);
17850 
17851    append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
17852 
17853    return 0;
17854 }
17855    
17856 /*! \brief Read SIP header (dialplan function) */
17857 static int func_header_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len) 
17858 {
17859    struct sip_pvt *p;
17860    const char *content = NULL;
17861    AST_DECLARE_APP_ARGS(args,
17862       AST_APP_ARG(header);
17863       AST_APP_ARG(number);
17864    );
17865    int i, number, start = 0;
17866 
17867    if (ast_strlen_zero(data)) {
17868       ast_log(LOG_WARNING, "This function requires a header name.\n");
17869       return -1;
17870    }
17871 
17872    ast_channel_lock(chan);
17873    if (!IS_SIP_TECH(chan->tech)) {
17874       ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
17875       ast_channel_unlock(chan);
17876       return -1;
17877    }
17878 
17879    AST_STANDARD_APP_ARGS(args, data);
17880    if (!args.number) {
17881       number = 1;
17882    } else {
17883       sscanf(args.number, "%30d", &number);
17884       if (number < 1)
17885          number = 1;
17886    }
17887 
17888    p = chan->tech_pvt;
17889 
17890    /* If there is no private structure, this channel is no longer alive */
17891    if (!p) {
17892       ast_channel_unlock(chan);
17893       return -1;
17894    }
17895 
17896    for (i = 0; i < number; i++)
17897       content = __get_header(&p->initreq, args.header, &start);
17898 
17899    if (ast_strlen_zero(content)) {
17900       ast_channel_unlock(chan);
17901       return -1;
17902    }
17903 
17904    ast_copy_string(buf, content, len);
17905    ast_channel_unlock(chan);
17906 
17907    return 0;
17908 }
17909 
17910 static struct ast_custom_function sip_header_function = {
17911    .name = "SIP_HEADER",
17912    .read = func_header_read,
17913 };
17914 
17915 /*! \brief  Dial plan function to check if domain is local */
17916 static int func_check_sipdomain(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
17917 {
17918    if (ast_strlen_zero(data)) {
17919       ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
17920       return -1;
17921    }
17922    if (check_sip_domain(data, NULL, 0))
17923       ast_copy_string(buf, data, len);
17924    else
17925       buf[0] = '\0';
17926    return 0;
17927 }
17928 
17929 static struct ast_custom_function checksipdomain_function = {
17930    .name = "CHECKSIPDOMAIN",
17931    .read = func_check_sipdomain,
17932 };
17933 
17934 /*! \brief  ${SIPPEER()} Dialplan function - reads peer data */
17935 static int function_sippeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
17936 {
17937    struct sip_peer *peer;
17938    char *colname;
17939 
17940    if ((colname = strchr(data, ':'))) {   /*! \todo Will be deprecated after 1.4 */
17941       static int deprecation_warning = 0;
17942       *colname++ = '\0';
17943       if (deprecation_warning++ % 10 == 0)
17944          ast_log(LOG_WARNING, "SIPPEER(): usage of ':' to separate arguments is deprecated.  Please use ',' instead.\n");
17945    } else if ((colname = strchr(data, ',')))
17946       *colname++ = '\0';
17947    else
17948       colname = "ip";
17949 
17950    if (!(peer = find_peer(data, NULL, TRUE, FINDPEERS, FALSE, 0)))
17951       return -1;
17952 
17953    if (!strcasecmp(colname, "ip")) {
17954       ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len);
17955    } else  if (!strcasecmp(colname, "port")) {
17956       snprintf(buf, len, "%d", ntohs(peer->addr.sin_port));
17957    } else  if (!strcasecmp(colname, "status")) {
17958       peer_status(peer, buf, len);
17959    } else  if (!strcasecmp(colname, "language")) {
17960       ast_copy_string(buf, peer->language, len);
17961    } else  if (!strcasecmp(colname, "regexten")) {
17962       ast_copy_string(buf, peer->regexten, len);
17963    } else  if (!strcasecmp(colname, "limit")) {
17964       snprintf(buf, len, "%d", peer->call_limit);
17965    } else  if (!strcasecmp(colname, "busylevel")) {
17966       snprintf(buf, len, "%d", peer->busy_level);
17967    } else  if (!strcasecmp(colname, "curcalls")) {
17968       snprintf(buf, len, "%d", peer->inUse);
17969    } else  if (!strcasecmp(colname, "accountcode")) {
17970       ast_copy_string(buf, peer->accountcode, len);
17971    } else  if (!strcasecmp(colname, "callgroup")) {
17972       ast_print_group(buf, len, peer->callgroup);
17973    } else  if (!strcasecmp(colname, "pickupgroup")) {
17974       ast_print_group(buf, len, peer->pickupgroup);
17975    } else  if (!strcasecmp(colname, "useragent")) {
17976       ast_copy_string(buf, peer->useragent, len);
17977    } else  if (!strcasecmp(colname, "mailbox")) {
17978       struct ast_str *mailbox_str = ast_str_alloca(512);
17979       peer_mailboxes_to_str(&mailbox_str, peer);
17980       ast_copy_string(buf, mailbox_str->str, len);
17981    } else  if (!strcasecmp(colname, "context")) {
17982       ast_copy_string(buf, peer->context, len);
17983    } else  if (!strcasecmp(colname, "expire")) {
17984       snprintf(buf, len, "%d", peer->expire);
17985    } else  if (!strcasecmp(colname, "dynamic")) {
17986       ast_copy_string(buf, peer->host_dynamic ? "yes" : "no", len);
17987    } else  if (!strcasecmp(colname, "callerid_name")) {
17988       ast_copy_string(buf, peer->cid_name, len);
17989    } else  if (!strcasecmp(colname, "callerid_num")) {
17990       ast_copy_string(buf, peer->cid_num, len);
17991    } else  if (!strcasecmp(colname, "codecs")) {
17992       ast_getformatname_multiple(buf, len -1, peer->capability);
17993    } else  if (!strncasecmp(colname, "chanvar[", 8)) {
17994       char *chanvar=colname + 8;
17995       struct ast_variable *v;
17996    
17997       chanvar = strsep(&chanvar, "]");
17998       for (v = peer->chanvars ; v ; v = v->next) {
17999          if (!strcasecmp(v->name, chanvar)) {
18000             ast_copy_string(buf, v->value, len);
18001          }
18002       }
18003    } else  if (!strncasecmp(colname, "codec[", 6)) {
18004       char *codecnum;
18005       int codec = 0;
18006       
18007       codecnum = colname + 6; /* move past the '[' */
18008       codecnum = strsep(&codecnum, "]"); /* trim trailing ']' if any */
18009       if((codec = ast_codec_pref_index(&peer->prefs, atoi(codecnum)))) {
18010          ast_copy_string(buf, ast_getformatname(codec), len);
18011       } else {
18012          buf[0] = '\0';
18013       }
18014    } else {
18015       buf[0] = '\0';
18016    }
18017 
18018    unref_peer(peer, "unref_peer from function_sippeer, just before return");
18019 
18020    return 0;
18021 }
18022 
18023 /*! \brief Structure to declare a dialplan function: SIPPEER */
18024 static struct ast_custom_function sippeer_function = {
18025    .name = "SIPPEER",
18026    .read = function_sippeer,
18027 };
18028 
18029 /*! \brief ${SIPCHANINFO()} Dialplan function - reads sip channel data */
18030 static int function_sipchaninfo_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
18031 {
18032    struct sip_pvt *p;
18033    static int deprecated = 0;
18034 
18035    *buf = 0;
18036    
18037    if (!data) {
18038       ast_log(LOG_WARNING, "This function requires a parameter name.\n");
18039       return -1;
18040    }
18041 
18042    ast_channel_lock(chan);
18043    if (!IS_SIP_TECH(chan->tech)) {
18044       ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
18045       ast_channel_unlock(chan);
18046       return -1;
18047    }
18048 
18049    if (deprecated++ % 20 == 0) {
18050       /* Deprecated in 1.6.1 */
18051       ast_log(LOG_WARNING, "SIPCHANINFO() is deprecated.  Please transition to using CHANNEL().\n");
18052    }
18053 
18054    p = chan->tech_pvt;
18055 
18056    /* If there is no private structure, this channel is no longer alive */
18057    if (!p) {
18058       ast_channel_unlock(chan);
18059       return -1;
18060    }
18061 
18062    if (!strcasecmp(data, "peerip")) {
18063       ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", len);
18064    } else  if (!strcasecmp(data, "recvip")) {
18065       ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", len);
18066    } else  if (!strcasecmp(data, "from")) {
18067       ast_copy_string(buf, p->from, len);
18068    } else  if (!strcasecmp(data, "uri")) {
18069       ast_copy_string(buf, p->uri, len);
18070    } else  if (!strcasecmp(data, "useragent")) {
18071       ast_copy_string(buf, p->useragent, len);
18072    } else  if (!strcasecmp(data, "peername")) {
18073       ast_copy_string(buf, p->peername, len);
18074    } else if (!strcasecmp(data, "t38passthrough")) {
18075       if (p->t38.state == T38_DISABLED) {
18076          ast_copy_string(buf, "0", len);
18077       } else { /* T38 is offered or enabled in this call */
18078          ast_copy_string(buf, "1", len);
18079       }
18080    } else {
18081       ast_channel_unlock(chan);
18082       return -1;
18083    }
18084    ast_channel_unlock(chan);
18085 
18086    return 0;
18087 }
18088 
18089 /*! \brief Structure to declare a dialplan function: SIPCHANINFO */
18090 static struct ast_custom_function sipchaninfo_function = {
18091    .name = "SIPCHANINFO",
18092    .read = function_sipchaninfo_read,
18093 };
18094 
18095 /*! \brief Parse 302 Moved temporalily response 
18096    \todo XXX Doesn't redirect over TLS on sips: uri's.
18097       If we get a redirect to a SIPS: uri, this needs to be going back to the
18098       dialplan (this is a request for a secure signalling path).
18099       Note that transport=tls is deprecated, but we need to support it on incoming requests.
18100 */
18101 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req)
18102 {
18103    char tmp[SIPBUFSIZE];
18104    char *s, *e, *t, *trans;
18105    char *domain;
18106    enum sip_transport transport = SIP_TRANSPORT_UDP;
18107 
18108    ast_copy_string(tmp, get_header(req, "Contact"), sizeof(tmp));
18109    if ((t = strchr(tmp, ',')))
18110       *t = '\0';
18111 
18112    s = get_in_brackets(tmp);
18113    if ((trans = strcasestr(s, ";transport="))) do {
18114       trans += 11;
18115 
18116       if ((e = strchr(trans, ';')))
18117          *e = '\0';
18118 
18119       if (!strncasecmp(trans, "tcp", 3))
18120          transport = SIP_TRANSPORT_TCP;
18121       else if (!strncasecmp(trans, "tls", 3))
18122          transport = SIP_TRANSPORT_TLS;
18123       else {
18124          if (strncasecmp(trans, "udp", 3))
18125             ast_debug(1, "received contact with an invalid transport, '%s'\n", s);
18126          /* This will assume UDP for all unknown transports */
18127          transport = SIP_TRANSPORT_UDP;
18128       }
18129    } while(0);
18130    s = remove_uri_parameters(s);
18131 
18132    if (p->socket.tcptls_session) {
18133       ao2_ref(p->socket.tcptls_session, -1);
18134       p->socket.tcptls_session = NULL;
18135    }
18136 
18137    set_socket_transport(&p->socket, transport);
18138 
18139    if (ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
18140       char *host = NULL;
18141       if (!strncasecmp(s, "sip:", 4))
18142          s += 4;
18143       else if (!strncasecmp(s, "sips:", 5))
18144          s += 5;
18145       e = strchr(s, '/');
18146       if (e)
18147          *e = '\0';
18148       if ((host = strchr(s, '@'))) {
18149          *host++ = '\0';
18150          ast_debug(2, "Found promiscuous redirection to 'SIP/%s::::%s@%s'\n", s, get_transport(transport), host);
18151          if (p->owner)
18152             ast_string_field_build(p->owner, call_forward, "SIP/%s::::%s@%s", s, get_transport(transport), host);
18153       } else {
18154          ast_debug(2, "Found promiscuous redirection to 'SIP/::::%s@%s'\n", get_transport(transport), s);
18155          if (p->owner)
18156             ast_string_field_build(p->owner, call_forward, "SIP/::::%s@%s", get_transport(transport), s);
18157       }
18158    } else {
18159       e = strchr(tmp, '@');
18160       if (e) {
18161          *e++ = '\0';
18162          domain = e;
18163       } else {
18164          /* No username part */
18165          domain = tmp;
18166       }
18167       e = strchr(tmp, '/');   /* WHEN do we hae a forward slash in the URI? */
18168       if (e)
18169          *e = '\0';
18170 
18171       if (!strncasecmp(s, "sip:", 4))
18172          s += 4;
18173       else if (!strncasecmp(s, "sips:", 5))
18174          s += 5;
18175       e = strchr(s, ';');  /* And username ; parameters? */
18176       if (e)
18177          *e = '\0';  
18178       ast_uri_decode(s);
18179       ast_debug(2, "Received 302 Redirect to extension '%s' (domain %s)\n", s, domain);
18180       if (p->owner) {
18181          pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
18182          ast_string_field_set(p->owner, call_forward, s);
18183       }
18184    }
18185 }
18186 
18187 /*! \brief Check pending actions on SIP call 
18188  *
18189  * \note both sip_pvt and sip_pvt's owner channel (if present)
18190  *  must be locked for this function.
18191  */
18192 static void check_pendings(struct sip_pvt *p)
18193 {
18194    if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
18195       /* if we can't BYE, then this is really a pending CANCEL */
18196       if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA) {
18197          p->invitestate = INV_CANCELLED;
18198          transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
18199          /* Actually don't destroy us yet, wait for the 487 on our original 
18200             INVITE, but do set an autodestruct just in case we never get it. */
18201       } else {
18202          /* We have a pending outbound invite, don't send something
18203             new in-transaction */
18204          if (p->pendinginvite)
18205             return;
18206 
18207          if (p->owner) {
18208             ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
18209          }
18210          /* Perhaps there is an SD change INVITE outstanding */
18211          transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
18212       }
18213       ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);   
18214       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18215    } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
18216       /* if we can't REINVITE, hold it for later */
18217       if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
18218          ast_debug(2, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
18219       } else {
18220          ast_debug(2, "Sending pending reinvite on '%s'\n", p->callid);
18221          /* Didn't get to reinvite yet, so do it now */
18222          transmit_reinvite_with_sdp(p, (p->t38.state == T38_LOCAL_REINVITE ? TRUE : FALSE), FALSE);
18223          ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE); 
18224       }
18225    }
18226 }
18227 
18228 /*! \brief Reset the NEEDREINVITE flag after waiting when we get 491 on a Re-invite
18229    to avoid race conditions between asterisk servers.
18230    Called from the scheduler.
18231 */
18232 static int sip_reinvite_retry(const void *data)
18233 {
18234    struct sip_pvt *p = (struct sip_pvt *) data;
18235    struct ast_channel *owner;
18236 
18237    sip_pvt_lock(p); /* called from schedule thread which requires a lock */
18238    while ((owner = p->owner) && ast_channel_trylock(owner)) {
18239       sip_pvt_unlock(p);
18240       usleep(1);
18241       sip_pvt_lock(p);
18242    }
18243    ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
18244    p->waitid = -1;
18245    check_pendings(p);
18246    sip_pvt_unlock(p);
18247    if (owner) {
18248       ast_channel_unlock(owner);
18249    }
18250    dialog_unref(p, "unref the dialog ptr from sip_reinvite_retry, because it held a dialog ptr");
18251    return 0;
18252 }
18253 
18254 
18255 /*! \brief Handle SIP response to INVITE dialogue */
18256 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18257 {
18258    int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
18259    int res = 0;
18260    int xmitres = 0;
18261    int reinvite = (p->owner && p->owner->_state == AST_STATE_UP);
18262    char *p_hdrval;
18263    int rtn;
18264 
18265    if (reinvite)
18266       ast_debug(4, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
18267    else
18268       ast_debug(4, "SIP response %d to standard invite\n", resp);
18269 
18270    if (p->alreadygone) { /* This call is already gone */
18271       ast_debug(1, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
18272       return;
18273    }
18274 
18275    /* Acknowledge sequence number - This only happens on INVITE from SIP-call */
18276    /* Don't auto congest anymore since we've gotten something useful back */
18277    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"));
18278 
18279    /* RFC3261 says we must treat every 1xx response (but not 100)
18280       that we don't recognize as if it was 183.
18281    */
18282    if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 182 && resp != 183)
18283       resp = 183;
18284 
18285    /* Any response between 100 and 199 is PROCEEDING */
18286    if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING)
18287       p->invitestate = INV_PROCEEDING;
18288  
18289    /* Final response, not 200 ? */
18290    if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA ))
18291       p->invitestate = INV_COMPLETED;
18292    
18293    /* Final response, clear out pending invite */
18294    if ((resp == 200 || resp >= 300) && p->pendinginvite && seqno == p->pendinginvite)
18295       p->pendinginvite = 0;
18296 
18297    switch (resp) {
18298    case 100:   /* Trying */
18299    case 101:   /* Dialog establishment */
18300       if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
18301          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
18302       check_pendings(p);
18303       break;
18304 
18305    case 180:   /* 180 Ringing */
18306    case 182:       /* 182 Queued */
18307       if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
18308          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
18309       if (!req->ignore && p->owner) {
18310          ast_queue_control(p->owner, AST_CONTROL_RINGING);
18311          if (p->owner->_state != AST_STATE_UP) {
18312             ast_setstate(p->owner, AST_STATE_RINGING);
18313          }
18314       }
18315       if (find_sdp(req)) {
18316          if (p->invitestate != INV_CANCELLED)
18317             p->invitestate = INV_EARLY_MEDIA;
18318          res = process_sdp(p, req, SDP_T38_NONE);
18319          if (!req->ignore && p->owner) {
18320             /* Queue a progress frame only if we have SDP in 180 or 182 */
18321             ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
18322          }
18323       }
18324       check_pendings(p);
18325       break;
18326 
18327    case 183:   /* Session progress */
18328       if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
18329          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
18330       if (find_sdp(req)) {
18331          if (p->invitestate != INV_CANCELLED)
18332             p->invitestate = INV_EARLY_MEDIA;
18333          res = process_sdp(p, req, SDP_T38_NONE);
18334          if (!req->ignore && p->owner) {
18335             /* Queue a progress frame */
18336             ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
18337          }
18338       } else {
18339          /* Alcatel PBXs are known to send 183s with no SDP after sending
18340           * a 100 Trying response. We're just going to treat this sort of thing
18341           * the same as we would treat a 180 Ringing
18342           */
18343          if (!req->ignore && p->owner) {
18344             ast_queue_control(p->owner, AST_CONTROL_RINGING);
18345          }
18346       }
18347       check_pendings(p);
18348       break;
18349 
18350    case 200:   /* 200 OK on invite - someone's answering our call */
18351       if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
18352          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
18353       p->authtries = 0;
18354       if (find_sdp(req)) {
18355          if ((res = process_sdp(p, req, SDP_T38_ACCEPT)) && !req->ignore)
18356             if (!reinvite)
18357                /* This 200 OK's SDP is not acceptable, so we need to ack, then hangup */
18358                /* For re-invites, we try to recover */
18359                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
18360       }
18361 
18362       /* Parse contact header for continued conversation */
18363       /* When we get 200 OK, we know which device (and IP) to contact for this call */
18364       /* This is important when we have a SIP proxy between us and the phone */
18365       if (outgoing) {
18366          update_call_counter(p, DEC_CALL_RINGING);
18367          parse_ok_contact(p, req);
18368          /* Save Record-Route for any later requests we make on this dialogue */
18369          if (!reinvite)
18370             build_route(p, req, 1);
18371 
18372          if(set_address_from_contact(p)) {
18373             /* Bad contact - we don't know how to reach this device */
18374             /* We need to ACK, but then send a bye */
18375             if (!p->route && !req->ignore)
18376                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
18377          } 
18378 
18379       }
18380 
18381       if (!req->ignore && p->owner) {
18382          if (!reinvite) {
18383             ast_queue_control(p->owner, AST_CONTROL_ANSWER);
18384             if (sip_cfg.callevents)
18385                manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
18386                   "Channel: %s\r\nChanneltype: %s\r\nUniqueid: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
18387                   p->owner->name, "SIP", p->owner->uniqueid, p->callid, p->fullcontact, p->peername);
18388          } else { /* RE-invite */
18389             ast_queue_frame(p->owner, &ast_null_frame);
18390          }
18391       } else {
18392           /* It's possible we're getting an 200 OK after we've tried to disconnect
18393               by sending CANCEL */
18394          /* First send ACK, then send bye */
18395          if (!req->ignore)
18396             ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
18397       }
18398 
18399       /* Check for Session-Timers related headers */
18400       if (st_get_mode(p, 0) != SESSION_TIMER_MODE_REFUSE && p->outgoing_call == TRUE && !reinvite) {
18401          p_hdrval = (char*)get_header(req, "Session-Expires");
18402          if (!ast_strlen_zero(p_hdrval)) {
18403             /* UAS supports Session-Timers */
18404             enum st_refresher tmp_st_ref = SESSION_TIMER_REFRESHER_AUTO;
18405             int tmp_st_interval = 0;
18406             rtn = parse_session_expires(p_hdrval, &tmp_st_interval, &tmp_st_ref);
18407             if (rtn != 0) {
18408                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
18409             }
18410             if (tmp_st_ref == SESSION_TIMER_REFRESHER_UAC || 
18411                tmp_st_ref == SESSION_TIMER_REFRESHER_UAS) {
18412                p->stimer->st_ref = tmp_st_ref;
18413             } 
18414             if (tmp_st_interval) {
18415                p->stimer->st_interval = tmp_st_interval;
18416             }
18417             p->stimer->st_active = TRUE;
18418             p->stimer->st_active_peer_ua = TRUE;
18419             start_session_timer(p);
18420          } else {
18421             /* UAS doesn't support Session-Timers */
18422             if (st_get_mode(p, 0) == SESSION_TIMER_MODE_ORIGINATE) {
18423                p->stimer->st_ref = SESSION_TIMER_REFRESHER_UAC;
18424                p->stimer->st_active_peer_ua = FALSE;
18425                start_session_timer(p);
18426             }
18427          }
18428       }
18429 
18430 
18431       /* If I understand this right, the branch is different for a non-200 ACK only */
18432       p->invitestate = INV_TERMINATED;
18433       ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
18434       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
18435       check_pendings(p);
18436       break;
18437 
18438    case 407: /* Proxy authentication */
18439    case 401: /* Www auth */
18440       /* First we ACK */
18441       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18442       if (p->options)
18443          p->options->auth_type = resp;
18444 
18445       /* Then we AUTH */
18446       ast_string_field_set(p, theirtag, NULL);  /* forget their old tag, so we don't match tags when getting response */
18447       if (!req->ignore) {
18448          if (p->authtries < MAX_AUTHTRIES)
18449             p->invitestate = INV_CALLING;
18450          if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, SIP_INVITE, 1)) {
18451             ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
18452             pvt_set_needdestroy(p, "failed to authenticate on INVITE");
18453             sip_alreadygone(p);
18454             if (p->owner)
18455                ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18456          }
18457       }
18458       break;
18459 
18460    case 403: /* Forbidden */
18461       /* First we ACK */
18462       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18463       ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
18464       if (!req->ignore && p->owner)
18465          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18466       pvt_set_needdestroy(p, "received 403 response");
18467       sip_alreadygone(p);
18468       break;
18469 
18470    case 404: /* Not found */
18471       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18472       if (p->owner && !req->ignore)
18473          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18474       sip_alreadygone(p);
18475       break;
18476 
18477    case 408: /* Request timeout */
18478    case 481: /* Call leg does not exist */
18479       /* Could be REFER caused INVITE with replaces */
18480       ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
18481       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18482       if (p->owner)
18483          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18484       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18485       break;
18486 
18487    case 422: /* Session-Timers: Session interval too small */
18488       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18489       ast_string_field_set(p, theirtag, NULL);
18490       proc_422_rsp(p, req);
18491       break;
18492 
18493    case 428: /* Use identity header - rfc 4474 - not supported by Asterisk yet */
18494       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18495       append_history(p, "Identity", "SIP identity is required. Not supported by Asterisk.");
18496       ast_log(LOG_WARNING, "SIP identity required by proxy. SIP dialog '%s'. Giving up.\n", p->callid);
18497       if (p->owner)
18498          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18499       break;
18500 
18501       
18502 
18503    case 487: /* Cancelled transaction */
18504       /* We have sent CANCEL on an outbound INVITE 
18505          This transaction is already scheduled to be killed by sip_hangup().
18506       */
18507       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18508       if (p->owner && !req->ignore) {
18509          ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_CLEARING);
18510          append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
18511       } else if (!req->ignore) {
18512          update_call_counter(p, DEC_CALL_LIMIT);
18513          append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
18514          pvt_set_needdestroy(p, "received 487 response");
18515          sip_alreadygone(p);
18516       }
18517       break;
18518    case 415: /* Unsupported media type */
18519    case 488: /* Not acceptable here */
18520    case 606: /* Not Acceptable */
18521       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18522       if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
18523          change_t38_state(p, T38_DISABLED);
18524          /* Try to reset RTP timers */
18525          ast_rtp_set_rtptimers_onhold(p->rtp);
18526 
18527          /* Trigger a reinvite back to audio */
18528          transmit_reinvite_with_sdp(p, FALSE, FALSE);
18529       } else {
18530          /* We can't set up this call, so give up */
18531          if (p->owner && !req->ignore)
18532             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18533          pvt_set_needdestroy(p, "received 488 response");
18534          /* If there's no dialog to end, then mark p as already gone */
18535          if (!reinvite)
18536             sip_alreadygone(p);
18537       }
18538       break;
18539    case 491: /* Pending */
18540       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18541       if (p->owner && !req->ignore) {
18542          if (p->owner->_state != AST_STATE_UP) {
18543             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18544             pvt_set_needdestroy(p, "received 491 response");
18545          } else {
18546             /* This is a re-invite that failed. */
18547             /* Reset the flag after a while 
18548              */
18549             int wait;
18550             /* RFC 3261, if owner of call, wait between 2.1 to 4 seconds,
18551              * if not owner of call, wait 0 to 2 seconds */
18552             if (p->outgoing_call) {
18553                wait = 2100 + ast_random() % 2000;
18554             } else {
18555                wait = ast_random() % 2000;
18556             }
18557             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."));
18558             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);
18559             ast_debug(2, "Reinvite race. Waiting %d secs before retry\n", wait);
18560          }
18561       }
18562       break;
18563 
18564    case 501: /* Not implemented */
18565       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18566       if (p->owner)
18567          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18568       break;
18569    }
18570    if (xmitres == XMIT_ERROR)
18571       ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
18572 }
18573 
18574 /* \brief Handle SIP response in NOTIFY transaction
18575        We've sent a NOTIFY, now handle responses to it
18576   */
18577 static void handle_response_notify(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18578 {
18579    switch (resp) {
18580    case 200:   /* Notify accepted */
18581       /* They got the notify, this is the end */
18582       if (p->owner) {
18583          if (!p->refer) {
18584             ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
18585             ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_UNSPECIFIED);
18586          } else {
18587             ast_debug(4, "Got OK on REFER Notify message\n");
18588          }
18589       } else {
18590          if (p->subscribed == NONE) {
18591             ast_debug(4, "Got 200 accepted on NOTIFY\n");
18592             pvt_set_needdestroy(p, "received 200 response");
18593          }
18594          if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
18595             /* Ready to send the next state we have on queue */
18596             ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
18597             cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
18598          }
18599       }
18600       break;
18601    case 401:   /* Not www-authorized on SIP method */
18602    case 407:   /* Proxy auth */
18603       if (!p->notify_headers) {
18604          break; /* Only device notify can use NOTIFY auth */
18605       }
18606       ast_string_field_set(p, theirtag, NULL);
18607       if (ast_strlen_zero(p->authname)) {
18608          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));
18609          pvt_set_needdestroy(p, "unable to authenticate NOTIFY");
18610       }
18611       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_NOTIFY, 0)) {
18612          ast_log(LOG_NOTICE, "Failed to authenticate on NOTIFY to '%s'\n", get_header(&p->initreq, "From"));
18613          pvt_set_needdestroy(p, "failed to authenticate NOTIFY");
18614       }
18615       break;
18616    }
18617 }
18618 
18619 /* \brief Handle SIP response in SUBSCRIBE transaction */
18620 static void handle_response_subscribe(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18621 {
18622    if (!p->mwi) {
18623       return;
18624    }
18625 
18626    switch (resp) {
18627    case 200: /* Subscription accepted */
18628       ast_debug(3, "Got 200 OK on subscription for MWI\n");
18629       if (p->options) {
18630          ast_free(p->options);
18631          p->options = NULL;
18632       }
18633       p->mwi->subscribed = 1;
18634       if ((p->mwi->resub = ast_sched_add(sched, mwi_expiry * 1000, sip_subscribe_mwi_do, ASTOBJ_REF(p->mwi))) < 0) {
18635          ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18636       }
18637       break;
18638    case 401:
18639    case 407:
18640       ast_string_field_set(p, theirtag, NULL);
18641       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_SUBSCRIBE, 0)) {
18642          ast_log(LOG_NOTICE, "Failed to authenticate on SUBSCRIBE to '%s'\n", get_header(&p->initreq, "From"));
18643          p->mwi->call = NULL;
18644          ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18645          pvt_set_needdestroy(p, "failed to authenticate SUBSCRIBE");
18646       }
18647       break;
18648    case 403:
18649       transmit_response_with_date(p, "200 OK", req);
18650       ast_log(LOG_WARNING, "Authentication failed while trying to subscribe for MWI.\n");
18651       p->mwi->call = NULL;
18652       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18653       pvt_set_needdestroy(p, "received 403 response");
18654       sip_alreadygone(p);
18655       break;
18656    case 404:
18657       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that a mailbox may not have been configured.\n");
18658       p->mwi->call = NULL;
18659       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18660       pvt_set_needdestroy(p, "received 404 response");
18661       break;
18662    case 481:
18663       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that our dialog did not exist.\n");
18664       p->mwi->call = NULL;
18665       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18666       pvt_set_needdestroy(p, "received 481 response");
18667       break;
18668    case 500:
18669    case 501:
18670       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side may have suffered a heart attack.\n");
18671       p->mwi->call = NULL;
18672       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18673       pvt_set_needdestroy(p, "received 500/501 response");
18674       break;
18675    }
18676 }
18677 
18678 /* \brief Handle SIP response in REFER transaction
18679    We've sent a REFER, now handle responses to it 
18680   */
18681 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18682 {
18683    /* If no refer structure exists, then do nothing */
18684    if (!p->refer)
18685       return;
18686 
18687    switch (resp) {
18688    case 202:   /* Transfer accepted */
18689       /* We need  to do something here */
18690       /* The transferee is now sending INVITE to target */
18691       p->refer->status = REFER_ACCEPTED;
18692       /* Now wait for next message */
18693       ast_debug(3, "Got 202 accepted on transfer\n");
18694       /* We should hang along, waiting for NOTIFY's here */
18695       break;
18696 
18697    case 401:   /* Not www-authorized on SIP method */
18698    case 407:   /* Proxy auth */
18699       if (ast_strlen_zero(p->authname)) {
18700          ast_log(LOG_WARNING, "Asked to authenticate REFER to %s:%d but we have no matching peer or realm auth!\n",
18701             ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
18702          pvt_set_needdestroy(p, "unable to authenticate REFER");
18703       }
18704       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_REFER, 0)) {
18705          ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
18706          p->refer->status = REFER_NOAUTH;
18707          pvt_set_needdestroy(p, "failed to authenticat REFER");
18708       }
18709       break;
18710    case 481: /* Call leg does not exist */
18711 
18712       /* A transfer with Replaces did not work */
18713       /* OEJ: We should Set flag, cancel the REFER, go back
18714       to original call - but right now we can't */
18715       ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
18716       if (p->owner)
18717          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18718       pvt_set_needdestroy(p, "received 481 response");
18719       break;
18720 
18721    case 500:   /* Server error */
18722    case 501:   /* Method not implemented */
18723       /* Return to the current call onhold */
18724       /* Status flag needed to be reset */
18725       ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
18726       pvt_set_needdestroy(p, "received 500/501 response");
18727       p->refer->status = REFER_FAILED;
18728       break;
18729    case 603:   /* Transfer declined */
18730       ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
18731       p->refer->status = REFER_FAILED;
18732       pvt_set_needdestroy(p, "received 603 response");
18733       break;
18734    }
18735 }
18736 
18737 /*! \brief Handle responses on REGISTER to services */
18738 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18739 {
18740    int expires, expires_ms;
18741    struct sip_registry *r;
18742    r=p->registry;
18743    
18744    switch (resp) {
18745    case 401:   /* Unauthorized */
18746       if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
18747          ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
18748          pvt_set_needdestroy(p, "failed to authenticate REGISTER");
18749       }
18750       break;
18751    case 403:   /* Forbidden */
18752       ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
18753       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 403"));
18754       r->regstate = REG_STATE_NOAUTH;
18755       pvt_set_needdestroy(p, "received 403 response");
18756       break;
18757    case 404:   /* Not found */
18758       ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username, p->registry->hostname);
18759       pvt_set_needdestroy(p, "received 404 response");
18760       if (r->call)
18761          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 404");
18762       r->regstate = REG_STATE_REJECTED;
18763       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 404"));
18764       break;
18765    case 407:   /* Proxy auth */
18766       if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
18767          ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
18768          pvt_set_needdestroy(p, "failed to authenticate REGISTER");
18769       }
18770       break;
18771    case 408:   /* Request timeout */
18772       /* Got a timeout response, so reset the counter of failed responses */
18773       if (r) {
18774          r->regattempts = 0;
18775       } else {
18776          ast_log(LOG_WARNING, "Got a 408 response to our REGISTER on call %s after we had destroyed the registry object\n", p->callid);
18777       }
18778       break;
18779    case 423:   /* Interval too brief */
18780       r->expiry = atoi(get_header(req, "Min-Expires"));
18781       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);
18782       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 423"));
18783       if (r->call) {
18784          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 423");
18785          pvt_set_needdestroy(p, "received 423 response");
18786       }
18787       if (r->expiry > max_expiry) {
18788          ast_log(LOG_WARNING, "Required expiration time from %s@%s is too high, giving up\n", p->registry->username, p->registry->hostname);
18789          r->expiry = r->configured_expiry;
18790          r->regstate = REG_STATE_REJECTED;
18791       } else {
18792          r->regstate = REG_STATE_UNREGISTERED;
18793          transmit_register(r, SIP_REGISTER, NULL, NULL);
18794       }
18795       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));
18796       break;
18797    case 479:   /* SER: Not able to process the URI - address is wrong in register*/
18798       ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username, p->registry->hostname);
18799       pvt_set_needdestroy(p, "received 479 response");
18800       if (r->call)
18801          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 479");
18802       r->regstate = REG_STATE_REJECTED;
18803       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 479"));
18804       break;
18805    case 200:   /* 200 OK */
18806       if (!r) {
18807          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));
18808          pvt_set_needdestroy(p, "received erroneous 200 response");
18809          return 0;
18810       }
18811       
18812       r->regstate = REG_STATE_REGISTERED;
18813       r->regtime = ast_tvnow();     /* Reset time of last succesful registration */
18814       manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
18815       r->regattempts = 0;
18816       ast_debug(1, "Registration successful\n");
18817       if (r->timeout > -1) {
18818          ast_debug(1, "Cancelling timeout %d\n", r->timeout);
18819       }
18820       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 200"));
18821       if (r->call)
18822          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 200");
18823       p->registry = registry_unref(p->registry, "unref registry entry p->registry");
18824       /* Let this one hang around until we have all the responses */
18825       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18826       /* p->needdestroy = 1; */
18827       
18828       /* set us up for re-registering
18829        * figure out how long we got registered for
18830        * according to section 6.13 of RFC, contact headers override
18831        * expires headers, so check those first */
18832       expires = 0;
18833 
18834       /* XXX todo: try to save the extra call */
18835       if (!ast_strlen_zero(get_header(req, "Contact"))) {
18836          const char *contact = NULL;
18837          const char *tmptmp = NULL;
18838          int start = 0;
18839          for(;;) {
18840             contact = __get_header(req, "Contact", &start);
18841             /* this loop ensures we get a contact header about our register request */
18842             if(!ast_strlen_zero(contact)) {
18843                if( (tmptmp=strstr(contact, p->our_contact))) {
18844                   contact=tmptmp;
18845                   break;
18846                }
18847             } else
18848                break;
18849          }
18850          tmptmp = strcasestr(contact, "expires=");
18851          if (tmptmp) {
18852             if (sscanf(tmptmp + 8, "%30d;", &expires) != 1)
18853                expires = 0;
18854          }
18855          
18856       }
18857       if (!expires) 
18858          expires=atoi(get_header(req, "expires"));
18859       if (!expires)
18860          expires=default_expiry;
18861       
18862       expires_ms = expires * 1000;
18863       if (expires <= EXPIRY_GUARD_LIMIT)
18864          expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT), EXPIRY_GUARD_MIN);
18865       else
18866          expires_ms -= EXPIRY_GUARD_SECS * 1000;
18867       if (sipdebug)
18868          ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000); 
18869       
18870       r->refresh= (int) expires_ms / 1000;
18871       
18872       /* Schedule re-registration before we expire */
18873       AST_SCHED_REPLACE_UNREF(r->expire, sched, expires_ms, sip_reregister, r, 
18874                         registry_unref(_data,"unref in REPLACE del fail"), 
18875                         registry_unref(r,"unref in REPLACE add fail"), 
18876                         registry_addref(r,"The Addition side of REPLACE")); 
18877    }
18878    return 1;
18879 }
18880 
18881 /*! \brief Handle qualification responses (OPTIONS) */
18882 static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
18883 {
18884    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! */
18885    int statechanged, is_reachable, was_reachable;
18886    int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
18887 
18888    /*
18889     * Compute the response time to a ping (goes in peer->lastms.)
18890     * -1 means did not respond, 0 means unknown,
18891     * 1..maxms is a valid response, >maxms means late response.
18892     */
18893    if (pingtime < 1) /* zero = unknown, so round up to 1 */
18894       pingtime = 1;
18895 
18896    /* Now determine new state and whether it has changed.
18897     * Use some helper variables to simplify the writing
18898     * of the expressions.
18899     */
18900    was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
18901    is_reachable = pingtime <= peer->maxms;
18902    statechanged = peer->lastms == 0 /* yes, unknown before */
18903       || was_reachable != is_reachable;
18904 
18905    peer->lastms = pingtime;
18906    peer->call = dialog_unref(peer->call, "unref dialog peer->call");
18907    if (statechanged) {
18908       const char *s = is_reachable ? "Reachable" : "Lagged";
18909       char str_lastms[20];
18910       snprintf(str_lastms, sizeof(str_lastms), "%d", pingtime);
18911 
18912       ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
18913          peer->name, s, pingtime, peer->maxms);
18914       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
18915       if (sip_cfg.peer_rtupdate) {
18916          ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", str_lastms, SENTINEL);
18917       }
18918       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
18919          "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
18920          peer->name, s, pingtime);
18921       if (is_reachable && sip_cfg.regextenonqualify)
18922          register_peer_exten(peer, TRUE);
18923    }
18924 
18925    pvt_set_needdestroy(p, "got OPTIONS response");
18926 
18927    /* Try again eventually */
18928    AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
18929          is_reachable ? peer->qualifyfreq : DEFAULT_FREQ_NOTOK,
18930          sip_poke_peer_s, peer,
18931          unref_peer(_data, "removing poke peer ref"),
18932          unref_peer(peer, "removing poke peer ref"),
18933          ref_peer(peer, "adding poke peer ref"));
18934 }
18935 
18936 /*! \brief Immediately stop RTP, VRTP and UDPTL as applicable */
18937 static void stop_media_flows(struct sip_pvt *p)
18938 {
18939    /* Immediately stop RTP, VRTP and UDPTL as applicable */
18940    if (p->rtp)
18941       ast_rtp_stop(p->rtp);
18942    if (p->vrtp)
18943       ast_rtp_stop(p->vrtp);
18944    if (p->trtp)
18945       ast_rtp_stop(p->trtp);
18946    if (p->udptl)
18947       ast_udptl_stop(p->udptl);
18948 }
18949 
18950 /*! \brief Handle SIP response in dialogue
18951    \note only called by handle_incoming */
18952 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18953 {
18954    struct ast_channel *owner;
18955    int sipmethod;
18956    int res = 1;
18957    const char *c = get_header(req, "Cseq");
18958    /* 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 */
18959    char *c_copy = ast_strdupa(c);
18960    /* Skip the Cseq and its subsequent spaces */
18961    const char *msg = ast_skip_blanks(ast_skip_nonblanks(c_copy));
18962 
18963    if (!msg)
18964       msg = "";
18965 
18966    sipmethod = find_sip_method(msg);
18967 
18968    owner = p->owner;
18969    if (owner) 
18970       owner->hangupcause = hangup_sip2cause(resp);
18971 
18972    if (p->socket.type == SIP_TRANSPORT_UDP) {
18973       int ack_res;
18974 
18975       /* Acknowledge whatever it is destined for */
18976       if ((resp >= 100) && (resp <= 199)) {
18977          ack_res = __sip_semi_ack(p, seqno, 0, sipmethod);
18978       } else {
18979          ack_res = __sip_ack(p, seqno, 0, sipmethod);
18980       }
18981 
18982       if (ack_res == FALSE) {
18983          append_history(p, "Ignore", "Ignoring this retransmit\n");
18984          return;
18985       }
18986    }
18987 
18988    /* If this is a NOTIFY for a subscription clear the flag that indicates that we have a NOTIFY pending */
18989    if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite) 
18990       p->pendinginvite = 0;
18991 
18992    /* Get their tag if we haven't already */
18993    if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
18994       char tag[128];
18995 
18996       gettag(req, "To", tag, sizeof(tag));
18997       ast_string_field_set(p, theirtag, tag);
18998    }
18999    /* This needs to be configurable on a channel/peer level,
19000       not mandatory for all communication. Sadly enough, NAT implementations
19001       are not so stable so we can always rely on these headers. 
19002       Temporarily disabled, while waiting for fix.
19003       Fix assigned to Rizzo :-)
19004    */
19005    /* check_via_response(p, req); */
19006 
19007    /* RFC 3261 Section 15 specifies that if we receive a 408 or 481
19008     * in response to a BYE, then we should end the current dialog
19009     * and session.  It is known that at least one phone manufacturer
19010     * potentially will send a 404 in response to a BYE, so we'll be
19011     * liberal in what we accept and end the dialog and session if we
19012     * receive any of those responses to a BYE.
19013     */
19014    if ((resp == 404 || resp == 408 || resp == 481) && sipmethod == SIP_BYE) {
19015       pvt_set_needdestroy(p, "received 4XX response to a BYE");
19016       return;
19017    }
19018 
19019    if (p->relatedpeer && p->method == SIP_OPTIONS) {
19020       /* We don't really care what the response is, just that it replied back. 
19021          Well, as long as it's not a 100 response...  since we might
19022          need to hang around for something more "definitive" */
19023       if (resp != 100)
19024          handle_response_peerpoke(p, resp, req);
19025    } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
19026       switch(resp) {
19027       case 100:   /* 100 Trying */
19028       case 101:   /* 101 Dialog establishment */
19029       case 183:   /* 183 Session Progress */
19030       case 180:   /* 180 Ringing */
19031       case 182:   /* 182 Queued */
19032          if (sipmethod == SIP_INVITE)
19033             handle_response_invite(p, resp, rest, req, seqno);
19034          break;
19035       case 200:   /* 200 OK */
19036          p->authtries = 0; /* Reset authentication counter */
19037          if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
19038             /* We successfully transmitted a message 
19039                or a video update request in INFO */
19040             /* Nothing happens here - the message is inside a dialog */
19041          } else if (sipmethod == SIP_INVITE) {
19042             handle_response_invite(p, resp, rest, req, seqno);
19043          } else if (sipmethod == SIP_NOTIFY) {
19044             handle_response_notify(p, resp, rest, req, seqno);
19045          } else if (sipmethod == SIP_REGISTER) {
19046             res = handle_response_register(p, resp, rest, req, seqno);
19047          } else if (sipmethod == SIP_SUBSCRIBE) {
19048             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
19049             handle_response_subscribe(p, resp, rest, req, seqno);
19050          } else if (sipmethod == SIP_BYE) {     /* Ok, we're ready to go */
19051             pvt_set_needdestroy(p, "received 200 response");
19052             ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
19053          }
19054          break;
19055       case 202:   /* Transfer accepted */
19056          if (sipmethod == SIP_REFER) 
19057             handle_response_refer(p, resp, rest, req, seqno);
19058          break;
19059       case 401: /* Not www-authorized on SIP method */
19060       case 407: /* Proxy auth required */
19061          if (sipmethod == SIP_INVITE)
19062             handle_response_invite(p, resp, rest, req, seqno);
19063          else if (sipmethod == SIP_NOTIFY)
19064             handle_response_notify(p, resp, rest, req, seqno);
19065          else if (sipmethod == SIP_REFER)
19066             handle_response_refer(p, resp, rest, req, seqno);
19067          else if (sipmethod == SIP_SUBSCRIBE)
19068             handle_response_subscribe(p, resp, rest, req, seqno);
19069          else if (p->registry && sipmethod == SIP_REGISTER)
19070             res = handle_response_register(p, resp, rest, req, seqno);
19071          else if (sipmethod == SIP_BYE) {
19072             if (p->options)
19073                p->options->auth_type = resp;
19074             if (ast_strlen_zero(p->authname)) {
19075                ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
19076                      msg, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
19077                pvt_set_needdestroy(p, "unable to authenticate BYE");
19078             } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp,  sipmethod, 0)) {
19079                ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
19080                pvt_set_needdestroy(p, "failed to authenticate BYE");
19081             }
19082          } else {
19083             ast_log(LOG_WARNING, "Got authentication request (%d) on %s to '%s'\n", resp, sip_methods[sipmethod].text, get_header(req, "To"));
19084             pvt_set_needdestroy(p, "received 407 response");
19085          }
19086          break;
19087       case 403: /* Forbidden - we failed authentication */
19088          if (sipmethod == SIP_INVITE)
19089             handle_response_invite(p, resp, rest, req, seqno);
19090          else if (sipmethod == SIP_SUBSCRIBE)
19091             handle_response_subscribe(p, resp, rest, req, seqno);
19092          else if (p->registry && sipmethod == SIP_REGISTER) 
19093             res = handle_response_register(p, resp, rest, req, seqno);
19094          else {
19095             ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
19096             pvt_set_needdestroy(p, "received 403 response");
19097          }
19098          break;
19099       case 404: /* Not found */
19100          if (p->registry && sipmethod == SIP_REGISTER)
19101             res = handle_response_register(p, resp, rest, req, seqno);
19102          else if (sipmethod == SIP_INVITE)
19103             handle_response_invite(p, resp, rest, req, seqno);
19104          else if (sipmethod == SIP_SUBSCRIBE)
19105             handle_response_subscribe(p, resp, rest, req, seqno);
19106          else if (owner)
19107             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
19108          break;
19109       case 423: /* Interval too brief */
19110          if (sipmethod == SIP_REGISTER)
19111             res = handle_response_register(p, resp, rest, req, seqno);
19112          break;
19113       case 408: /* Request timeout - terminate dialog */
19114          if (sipmethod == SIP_INVITE)
19115             handle_response_invite(p, resp, rest, req, seqno);
19116          else if (sipmethod == SIP_REGISTER) 
19117             res = handle_response_register(p, resp, rest, req, seqno);
19118          else if (sipmethod == SIP_BYE) {
19119             pvt_set_needdestroy(p, "received 408 response");
19120             ast_debug(4, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
19121          } else {
19122             if (owner)
19123                ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
19124             pvt_set_needdestroy(p, "received 408 response");
19125          }
19126          break;
19127 
19128       case 422: /* Session-Timers: Session Interval Too Small */
19129          if (sipmethod == SIP_INVITE) {
19130             handle_response_invite(p, resp, rest, req, seqno);
19131          }
19132          break;
19133 
19134       case 481: /* Call leg does not exist */
19135          if (sipmethod == SIP_INVITE) {
19136             handle_response_invite(p, resp, rest, req, seqno);
19137          } else if (sipmethod == SIP_REFER) {
19138             handle_response_refer(p, resp, rest, req, seqno);
19139          } else if (sipmethod == SIP_SUBSCRIBE) {
19140             handle_response_subscribe(p, resp, rest, req, seqno);
19141          } else if (sipmethod == SIP_NOTIFY) {
19142             pvt_set_needdestroy(p, "received 481 response");
19143          } else if (sipmethod == SIP_BYE) {
19144             /* The other side has no transaction to bye,
19145             just assume it's all right then */
19146             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
19147          } else if (sipmethod == SIP_CANCEL) {
19148             /* The other side has no transaction to cancel,
19149             just assume it's all right then */
19150             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
19151          } else {
19152             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
19153             /* Guessing that this is not an important request */
19154          }
19155          break;
19156       case 487:
19157          if (sipmethod == SIP_INVITE)
19158             handle_response_invite(p, resp, rest, req, seqno);
19159          break;
19160       case 415: /* Unsupported media type */
19161       case 488: /* Not acceptable here - codec error */
19162       case 606: /* Not Acceptable */
19163          if (sipmethod == SIP_INVITE)
19164             handle_response_invite(p, resp, rest, req, seqno);
19165          break;
19166       case 491: /* Pending */
19167          if (sipmethod == SIP_INVITE)
19168             handle_response_invite(p, resp, rest, req, seqno);
19169          else {
19170             ast_debug(1, "Got 491 on %s, unsupported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
19171             pvt_set_needdestroy(p, "received 491 response");
19172          }
19173          break;
19174       case 501: /* Not Implemented */
19175          if (sipmethod == SIP_INVITE)
19176             handle_response_invite(p, resp, rest, req, seqno);
19177          else if (sipmethod == SIP_REFER)
19178             handle_response_refer(p, resp, rest, req, seqno);
19179          else
19180             ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_inet_ntoa(p->sa.sin_addr), msg);
19181          break;
19182       case 603:   /* Declined transfer */
19183          if (sipmethod == SIP_REFER) {
19184             handle_response_refer(p, resp, rest, req, seqno);
19185             break;
19186          }
19187          /* Fallthrough */
19188       default:
19189          if ((resp >= 300) && (resp < 700)) {
19190             /* Fatal response */
19191             if ((resp != 487))
19192                ast_verb(3, "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
19193    
19194             if (sipmethod == SIP_INVITE)
19195                stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
19196 
19197             /* XXX Locking issues?? XXX */
19198             switch(resp) {
19199             case 300: /* Multiple Choices */
19200             case 301: /* Moved permanently */
19201             case 302: /* Moved temporarily */
19202             case 305: /* Use Proxy */
19203                parse_moved_contact(p, req);
19204                /* Fall through */
19205             case 486: /* Busy here */
19206             case 600: /* Busy everywhere */
19207             case 603: /* Decline */
19208                if (p->owner)
19209                   ast_queue_control(p->owner, AST_CONTROL_BUSY);
19210                break;
19211             case 482: /* Loop Detected */
19212                /*
19213                   \note Asterisk has historically tried to do a call forward when it
19214                   gets a 482, but that behavior isn't necessarily the best course of
19215                   action. Go ahead and do it anyway by default, but allow the option
19216                   to immediately pass to the next line in the dialplan. */
19217                if (p->owner && ast_test_flag(&p->flags[1], SIP_PAGE2_FORWARD_LOOP_DETECTED)) {
19218                      ast_debug(1, "Hairpin detected, setting up call forward for what it's worth\n");
19219                      ast_string_field_build(p->owner, call_forward,
19220                            "Local/%s@%s", p->username, p->context);
19221                }
19222                /* Fall through */
19223             case 480: /* Temporarily Unavailable */
19224             case 404: /* Not Found */
19225             case 410: /* Gone */
19226             case 400: /* Bad Request */
19227             case 500: /* Server error */
19228                if (sipmethod == SIP_REFER) {
19229                   handle_response_refer(p, resp, rest, req, seqno);
19230                   break;
19231                } else if (sipmethod == SIP_SUBSCRIBE) {
19232                   handle_response_subscribe(p, resp, rest, req, seqno);
19233                   break;
19234                }
19235                /* Fall through */
19236             case 502: /* Bad gateway */
19237             case 503: /* Service Unavailable */
19238             case 504: /* Server Timeout */
19239                if (owner)
19240                   ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
19241                break;
19242             default:
19243                /* Send hangup */ 
19244                if (owner && sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO && sipmethod != SIP_BYE)
19245                   ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
19246                break;
19247             }
19248             /* ACK on invite */
19249             if (sipmethod == SIP_INVITE) 
19250                transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
19251             if (sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO) 
19252                sip_alreadygone(p);
19253             if (!p->owner) {
19254                pvt_set_needdestroy(p, "transaction completed");
19255             }
19256          } else if ((resp >= 100) && (resp < 200)) {
19257             if (sipmethod == SIP_INVITE) {
19258                if (!req->ignore && sip_cancel_destroy(p))
19259                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
19260                if (find_sdp(req))
19261                   process_sdp(p, req, SDP_T38_NONE);
19262                if (p->owner) {
19263                   /* Queue a progress frame */
19264                   ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
19265                }
19266             }
19267          } else
19268             ast_log(LOG_NOTICE, "Don't know how to handle a %d %s response from %s\n", resp, rest, p->owner ? p->owner->name : ast_inet_ntoa(p->sa.sin_addr));
19269       }
19270    } else { 
19271       /* Responses to OUTGOING SIP requests on INCOMING calls 
19272          get handled here. As well as out-of-call message responses */
19273       if (req->debug)
19274          ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
19275 
19276       if (sipmethod == SIP_INVITE && resp == 200) {
19277          /* Tags in early session is replaced by the tag in 200 OK, which is 
19278          the final reply to our INVITE */
19279          char tag[128];
19280 
19281          gettag(req, "To", tag, sizeof(tag));
19282          ast_string_field_set(p, theirtag, tag);
19283       }
19284 
19285       switch(resp) {
19286       case 200:
19287          if (sipmethod == SIP_INVITE) {
19288             handle_response_invite(p, resp, rest, req, seqno);
19289          } else if (sipmethod == SIP_CANCEL) {
19290             ast_debug(1, "Got 200 OK on CANCEL\n");
19291 
19292             /* Wait for 487, then destroy */
19293          } else if (sipmethod == SIP_NOTIFY) {
19294             /* They got the notify, this is the end */
19295             if (p->owner) {
19296                if (p->refer) {
19297                   ast_debug(1, "Got 200 OK on NOTIFY for transfer\n");
19298                } else
19299                   ast_log(LOG_WARNING, "Notify answer on an owned channel?\n");
19300                /* ast_queue_hangup(p->owner); Disabled */
19301             } else {
19302                if (!p->subscribed && !p->refer) {
19303                   pvt_set_needdestroy(p, "transaction completed");
19304                }
19305                if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
19306                   /* Ready to send the next state we have on queue */
19307                   ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
19308                   cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
19309                }
19310             }
19311          } else if (sipmethod == SIP_BYE) {
19312             pvt_set_needdestroy(p, "transaction completed");
19313          } else if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
19314             /* We successfully transmitted a message or
19315                a video update request in INFO */
19316             ;
19317          }
19318          break;
19319       case 202:   /* Transfer accepted */
19320          if (sipmethod == SIP_REFER) 
19321             handle_response_refer(p, resp, rest, req, seqno);
19322          break;
19323       case 401:   /* www-auth */
19324       case 407:
19325          if (sipmethod == SIP_REFER)
19326             handle_response_refer(p, resp, rest, req, seqno);
19327          else if (sipmethod == SIP_INVITE) 
19328             handle_response_invite(p, resp, rest, req, seqno);
19329          else if (sipmethod == SIP_BYE) {
19330             if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, sipmethod, 0)) {
19331                ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
19332                pvt_set_needdestroy(p, "failed to authenticate BYE");
19333             }
19334          }
19335          break;
19336       case 481:   /* Call leg does not exist */
19337          if (sipmethod == SIP_INVITE) {
19338             /* Re-invite failed */
19339             handle_response_invite(p, resp, rest, req, seqno);
19340          } else if (sipmethod == SIP_BYE) {
19341             pvt_set_needdestroy(p, "received 481 response");
19342          } else if (sipmethod == SIP_NOTIFY) {
19343             pvt_set_needdestroy(p, "received 481 response");
19344          } else if (sipdebug) {
19345             ast_debug(1, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
19346          }
19347          break;
19348       case 501: /* Not Implemented */
19349          if (sipmethod == SIP_INVITE) 
19350             handle_response_invite(p, resp, rest, req, seqno);
19351          else if (sipmethod == SIP_REFER) 
19352             handle_response_refer(p, resp, rest, req, seqno);
19353          break;
19354       case 603:   /* Declined transfer */
19355          if (sipmethod == SIP_REFER) {
19356             handle_response_refer(p, resp, rest, req, seqno);
19357             break;
19358          }
19359          /* Fallthrough */
19360       default: /* Errors without handlers */
19361          if ((resp >= 100) && (resp < 200)) {
19362             if (sipmethod == SIP_INVITE) {   /* re-invite */
19363                if (!req->ignore && sip_cancel_destroy(p))
19364                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
19365             }
19366          }
19367          if ((resp >= 300) && (resp < 700)) {
19368             if ((resp != 487))
19369                ast_verb(3, "Incoming call: Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
19370             switch(resp) {
19371             case 415: /* Unsupported media type */
19372             case 488: /* Not acceptable here - codec error */
19373             case 603: /* Decline */
19374             case 500: /* Server error */
19375             case 502: /* Bad gateway */
19376             case 503: /* Service Unavailable */
19377             case 504: /* Server timeout */
19378 
19379                /* re-invite failed */
19380                if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
19381                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
19382                break;
19383             }
19384          }
19385          break;
19386       }
19387    }
19388 }
19389 
19390 
19391 /*! \brief Park SIP call support function 
19392    Starts in a new thread, then parks the call
19393    XXX Should we add a wait period after streaming audio and before hangup?? Sometimes the
19394       audio can't be heard before hangup
19395 */
19396 static void *sip_park_thread(void *stuff)
19397 {
19398    struct ast_channel *transferee, *transferer; /* Chan1: The transferee, Chan2: The transferer */
19399    struct sip_dual *d;
19400    struct sip_request req = {0,};
19401    int ext;
19402    int res;
19403 
19404    d = stuff;
19405    transferee = d->chan1;
19406    transferer = d->chan2;
19407    copy_request(&req, &d->req);
19408 
19409    if (!transferee || !transferer) {
19410       ast_log(LOG_ERROR, "Missing channels for parking! Transferer %s Transferee %s\n", transferer ? "<available>" : "<missing>", transferee ? "<available>" : "<missing>" );
19411       deinit_req(&d->req);
19412       ast_free(d);
19413       return NULL;
19414    }
19415    ast_debug(4, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);
19416 
19417    ast_channel_lock(transferee);
19418    if (ast_do_masquerade(transferee)) {
19419       ast_log(LOG_WARNING, "Masquerade failed.\n");
19420       transmit_response(transferer->tech_pvt, "503 Internal error", &req);
19421       ast_channel_unlock(transferee);
19422       deinit_req(&d->req);
19423       ast_free(d);
19424       return NULL;
19425    } 
19426    ast_channel_unlock(transferee);
19427 
19428    res = ast_park_call(transferee, transferer, 0, &ext);
19429    
19430 
19431 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
19432    if (!res) {
19433       transmit_message_with_text(transferer->tech_pvt, "Unable to park call.\n");
19434    } else {
19435       /* Then tell the transferer what happened */
19436       sprintf(buf, "Call parked on extension '%d'", ext);
19437       transmit_message_with_text(transferer->tech_pvt, buf);
19438    }
19439 #endif
19440 
19441    /* Any way back to the current call??? */
19442    /* Transmit response to the REFER request */
19443    if (!res)   {
19444       /* Transfer succeeded */
19445       append_history(transferer->tech_pvt, "SIPpark", "Parked call on %d", ext);
19446       transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "200 OK", TRUE);
19447       transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
19448       ast_hangup(transferer); /* This will cause a BYE */
19449       ast_debug(1, "SIP Call parked on extension '%d'\n", ext);
19450    } else {
19451       transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "503 Service Unavailable", TRUE);
19452       append_history(transferer->tech_pvt, "SIPpark", "Parking failed\n");
19453       ast_debug(1, "SIP Call parked failed \n");
19454       /* Do not hangup call */
19455    }
19456    deinit_req(&d->req);
19457    ast_free(d);
19458    return NULL;
19459 }
19460 
19461 /*! \brief Park a call using the subsystem in res_features.c 
19462    This is executed in a separate thread
19463 */
19464 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno)
19465 {
19466    struct sip_dual *d;
19467    struct ast_channel *transferee, *transferer;
19468       /* Chan2m: The transferer, chan1m: The transferee */
19469    pthread_t th;
19470 
19471    transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan1->accountcode, chan1->exten, chan1->context, chan1->amaflags, "Parking/%s", chan1->name);
19472    transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->amaflags, "SIPPeer/%s", chan2->name);
19473    if ((!transferer) || (!transferee)) {
19474       if (transferee) {
19475          transferee->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
19476          ast_hangup(transferee);
19477       }
19478       if (transferer) {
19479          transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
19480          ast_hangup(transferer);
19481       }
19482       return -1;
19483    }
19484 
19485    /* Make formats okay */
19486    transferee->readformat = chan1->readformat;
19487    transferee->writeformat = chan1->writeformat;
19488 
19489    /* Prepare for taking over the channel */
19490    ast_channel_masquerade(transferee, chan1);
19491 
19492    /* Setup the extensions and such */
19493    ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
19494    ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
19495    transferee->priority = chan1->priority;
19496       
19497    /* We make a clone of the peer channel too, so we can play
19498       back the announcement */
19499 
19500    /* Make formats okay */
19501    transferer->readformat = chan2->readformat;
19502    transferer->writeformat = chan2->writeformat;
19503    if (!ast_strlen_zero(chan2->parkinglot))
19504       ast_string_field_set(transferer, parkinglot, chan2->parkinglot);
19505 
19506    /* Prepare for taking over the channel.  Go ahead and grab this channel
19507     * lock here to avoid a deadlock with callbacks into the channel driver
19508     * that hold the channel lock and want the pvt lock.  */
19509    while (ast_channel_trylock(chan2)) {
19510       struct sip_pvt *pvt = chan2->tech_pvt;
19511       sip_pvt_unlock(pvt);
19512       usleep(1);
19513       sip_pvt_lock(pvt);
19514    }
19515    ast_channel_masquerade(transferer, chan2);
19516    ast_channel_unlock(chan2);
19517 
19518    /* Setup the extensions and such */
19519    ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
19520    ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
19521    transferer->priority = chan2->priority;
19522 
19523    ast_channel_lock(transferer);
19524    if (ast_do_masquerade(transferer)) {
19525       ast_log(LOG_WARNING, "Masquerade failed :(\n");
19526       ast_channel_unlock(transferer);
19527       transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
19528       ast_hangup(transferer);
19529       return -1;
19530    }
19531    ast_channel_unlock(transferer);
19532    if (!transferer || !transferee) {
19533       if (!transferer) { 
19534          ast_debug(1, "No transferer channel, giving up parking\n");
19535       }
19536       if (!transferee) {
19537          ast_debug(1, "No transferee channel, giving up parking\n");
19538       }
19539       return -1;
19540    }
19541    if (!(d = ast_calloc(1, sizeof(*d)))) {
19542       return -1;
19543    }
19544 
19545    /* Save original request for followup */
19546    copy_request(&d->req, req);
19547    d->chan1 = transferee;  /* Transferee */
19548    d->chan2 = transferer;  /* Transferer */
19549    d->seqno = seqno;
19550    if (ast_pthread_create_detached_background(&th, NULL, sip_park_thread, d) < 0) {
19551       /* Could not start thread */
19552       deinit_req(&d->req);
19553       ast_free(d);   /* We don't need it anymore. If thread is created, d will be free'd
19554                by sip_park_thread() */
19555       return -1;
19556    }
19557    return 0;
19558 }
19559 
19560 
19561 /*! \brief SIP pickup support function
19562  * Starts in a new thread, then pickup the call
19563  */
19564 static void *sip_pickup_thread(void *stuff)
19565 {
19566    struct ast_channel *chan;
19567    chan = stuff;
19568 
19569    if (ast_pickup_call(chan)) {
19570       chan->hangupcause = AST_CAUSE_CALL_REJECTED;
19571    } else {
19572       chan->hangupcause = AST_CAUSE_NORMAL_CLEARING;
19573    }
19574    ast_hangup(chan);
19575    chan = NULL;
19576    return NULL;
19577 }
19578 
19579 /*! \brief Pickup a call using the subsystem in features.c
19580  * This is executed in a separate thread
19581  */
19582 static int sip_pickup(struct ast_channel *chan)
19583 {
19584    pthread_t threadid;
19585 
19586    if (ast_pthread_create_detached_background(&threadid, NULL, sip_pickup_thread, chan)) {
19587       ast_debug(1, "Unable to start Group pickup thread on channel %s\n", chan->name);
19588       return -1;
19589    }
19590    ast_debug(1, "Started Group pickup thread on channel %s\n", chan->name);
19591    return 0;
19592 }
19593 
19594 
19595 /*! \brief Turn off generator data 
19596    XXX Does this function belong in the SIP channel?
19597 */
19598 static void ast_quiet_chan(struct ast_channel *chan) 
19599 {
19600    if (chan && chan->_state == AST_STATE_UP) {
19601       if (ast_test_flag(chan, AST_FLAG_MOH))
19602          ast_moh_stop(chan);
19603       else if (chan->generatordata)
19604          ast_deactivate_generator(chan);
19605    }
19606 }
19607 
19608 /*! \brief Attempt transfer of SIP call 
19609    This fix for attended transfers on a local PBX */
19610 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
19611 {
19612    int res = 0;
19613    struct ast_channel *peera = NULL,   
19614       *peerb = NULL,
19615       *peerc = NULL,
19616       *peerd = NULL;
19617 
19618 
19619    /* We will try to connect the transferee with the target and hangup
19620       all channels to the transferer */   
19621    ast_debug(4, "Sip transfer:--------------------\n");
19622    if (transferer->chan1)
19623       ast_debug(4, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
19624    else
19625       ast_debug(4, "-- No transferer first channel - odd??? \n");
19626    if (target->chan1)
19627       ast_debug(4, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
19628    else
19629       ast_debug(4, "-- No target first channel ---\n");
19630    if (transferer->chan2)
19631       ast_debug(4, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
19632    else
19633       ast_debug(4, "-- No bridged call to transferee\n");
19634    if (target->chan2)
19635       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)");
19636    else
19637       ast_debug(4, "-- No target second channel ---\n");
19638    ast_debug(4, "-- END Sip transfer:--------------------\n");
19639    if (transferer->chan2) { /* We have a bridge on the transferer's channel */
19640       peera = transferer->chan1; /* Transferer - PBX -> transferee channel * the one we hangup */
19641       peerb = target->chan1;     /* Transferer - PBX -> target channel - This will get lost in masq */
19642       peerc = transferer->chan2; /* Asterisk to Transferee */
19643       peerd = target->chan2;     /* Asterisk to Target */
19644       ast_debug(3, "SIP transfer: Four channels to handle\n");
19645    } else if (target->chan2) {   /* Transferer has no bridge (IVR), but transferee */
19646       peera = target->chan1;     /* Transferer to PBX -> target channel */
19647       peerb = transferer->chan1; /* Transferer to IVR*/
19648       peerc = target->chan2;     /* Asterisk to Target */
19649       peerd = transferer->chan2; /* Nothing */
19650       ast_debug(3, "SIP transfer: Three channels to handle\n");
19651    }
19652 
19653    if (peera && peerb && peerc && (peerb != peerc)) {
19654       ast_quiet_chan(peera);     /* Stop generators */
19655       ast_quiet_chan(peerb);  
19656       ast_quiet_chan(peerc);
19657       if (peerd)
19658          ast_quiet_chan(peerd);
19659 
19660       ast_debug(4, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
19661       if (ast_channel_masquerade(peerb, peerc)) {
19662          ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
19663          res = -1;
19664       } else
19665          ast_debug(4, "SIP transfer: Succeeded to masquerade channels.\n");
19666       return res;
19667    } else {
19668       ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
19669       if (transferer->chan1)
19670          ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
19671       if (target->chan1)
19672          ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
19673       return -1;
19674    }
19675    return 0;
19676 }
19677 
19678 /*! \brief Get tag from packet 
19679  *
19680  * \return Returns the pointer to the provided tag buffer,
19681  *         or NULL if the tag was not found.
19682  */
19683 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
19684 {
19685    const char *thetag;
19686 
19687    if (!tagbuf)
19688       return NULL;
19689    tagbuf[0] = '\0';    /* reset the buffer */
19690    thetag = get_header(req, header);
19691    thetag = strcasestr(thetag, ";tag=");
19692    if (thetag) {
19693       thetag += 5;
19694       ast_copy_string(tagbuf, thetag, tagbufsize);
19695       return strsep(&tagbuf, ";");
19696    }
19697    return NULL;
19698 }
19699 
19700 /*! \brief Handle incoming notifications */
19701 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
19702 {
19703    /* This is mostly a skeleton for future improvements */
19704    /* Mostly created to return proper answers on notifications on outbound REFER's */
19705    int res = 0;
19706    const char *event = get_header(req, "Event");
19707    char *eventid = NULL;
19708    char *sep;
19709 
19710    if( (sep = strchr(event, ';')) ) {  /* XXX bug here - overwriting string ? */
19711       *sep++ = '\0';
19712       eventid = sep;
19713    }
19714    
19715    if (sipdebug)
19716       ast_debug(2, "Got NOTIFY Event: %s\n", event);
19717 
19718    if (!strcmp(event, "refer")) {
19719       /* Save nesting depth for now, since there might be other events we will
19720          support in the future */
19721 
19722       /* Handle REFER notifications */
19723 
19724       char buf[1024];
19725       char *cmd, *code;
19726       int respcode;
19727       int success = TRUE;
19728 
19729       /* EventID for each transfer... EventID is basically the REFER cseq 
19730 
19731        We are getting notifications on a call that we transfered
19732        We should hangup when we are getting a 200 OK in a sipfrag
19733        Check if we have an owner of this event */
19734       
19735       /* Check the content type */
19736       if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
19737          /* We need a sipfrag */
19738          transmit_response(p, "400 Bad request", req);
19739          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19740          return -1;
19741       }
19742 
19743       /* Get the text of the attachment */
19744       if (get_msg_text(buf, sizeof(buf), req, TRUE)) {
19745          ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
19746          transmit_response(p, "400 Bad request", req);
19747          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19748          return -1;
19749       }
19750 
19751       /*
19752       From the RFC...
19753       A minimal, but complete, implementation can respond with a single
19754       NOTIFY containing either the body:
19755          SIP/2.0 100 Trying
19756       
19757       if the subscription is pending, the body:
19758          SIP/2.0 200 OK
19759       if the reference was successful, the body:
19760          SIP/2.0 503 Service Unavailable
19761       if the reference failed, or the body:
19762          SIP/2.0 603 Declined
19763 
19764       if the REFER request was accepted before approval to follow the
19765       reference could be obtained and that approval was subsequently denied
19766       (see Section 2.4.7).
19767       
19768       If there are several REFERs in the same dialog, we need to
19769       match the ID of the event header...
19770       */
19771       ast_debug(3, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
19772       cmd = ast_skip_blanks(buf);
19773       code = cmd;
19774       /* We are at SIP/2.0 */
19775       while(*code && (*code > 32)) {   /* Search white space */
19776          code++;
19777       }
19778       *code++ = '\0';
19779       code = ast_skip_blanks(code);
19780       sep = code;
19781       sep++;
19782       while(*sep && (*sep > 32)) {  /* Search white space */
19783          sep++;
19784       }
19785       *sep++ = '\0';       /* Response string */
19786       respcode = atoi(code);
19787       switch (respcode) {
19788       case 100:   /* Trying: */
19789       case 101:   /* dialog establishment */
19790          /* Don't do anything yet */
19791          break;
19792       case 183:   /* Ringing: */
19793          /* Don't do anything yet */
19794          break;
19795       case 200:   /* OK: The new call is up, hangup this call */
19796          /* Hangup the call that we are replacing */
19797          break;
19798       case 301: /* Moved permenantly */
19799       case 302: /* Moved temporarily */
19800          /* Do we get the header in the packet in this case? */
19801          success = FALSE;
19802          break;
19803       case 503:   /* Service Unavailable: The new call failed */
19804             /* Cancel transfer, continue the call */
19805          success = FALSE;
19806          break;
19807       case 603:   /* Declined: Not accepted */
19808             /* Cancel transfer, continue the current call */
19809          success = FALSE;
19810          break;
19811       }
19812       if (!success) {
19813          ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
19814       }
19815       
19816       /* Confirm that we received this packet */
19817       transmit_response(p, "200 OK", req);
19818    } else if (p->mwi && !strcmp(event, "message-summary")) {
19819       char *c = ast_strdupa(get_body(req, "Voice-Message", ':'));
19820 
19821       if (!ast_strlen_zero(c)) {
19822          char *old = strsep(&c, " ");
19823          char *new = strsep(&old, "/");
19824          struct ast_event *event;
19825 
19826          if ((event = ast_event_new(AST_EVENT_MWI,
19827                      AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, p->mwi->mailbox,
19828                      AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, "SIP_Remote",
19829                      AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(new),
19830                      AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(old),
19831                      AST_EVENT_IE_END))) {
19832             ast_event_queue_and_cache(event);
19833          }
19834       }
19835 
19836       transmit_response(p, "200 OK", req);
19837    } else if (!strcmp(event, "keep-alive")) {
19838        /* Used by Sipura/Linksys for NAT pinhole,
19839         * just confirm that we received the packet. */
19840       transmit_response(p, "200 OK", req);
19841    } else {
19842       /* We don't understand this event. */
19843       transmit_response(p, "489 Bad event", req);
19844       res = -1;
19845    }
19846 
19847    if (!p->lastinvite)
19848       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19849 
19850    return res;
19851 }
19852 
19853 /*! \brief Handle incoming OPTIONS request 
19854    An OPTIONS request should be answered like an INVITE from the same UA, including SDP
19855 */
19856 static int handle_request_options(struct sip_pvt *p, struct sip_request *req)
19857 {
19858    int res;
19859 
19860    /*! XXX get_destination assumes we're already authenticated. This means that a request from
19861       a known device (peer) will end up in the wrong context if this is out-of-dialog.
19862       However, we want to handle OPTIONS as light as possible, so we might want to have
19863       a configuration option whether we care or not. Some devices use this for testing
19864       capabilities, which means that we need to match device to answer with proper 
19865       capabilities (including SDP).
19866       \todo Fix handle_request_options device handling with optional authentication
19867          (this needs to be fixed in 1.4 as well)
19868    */
19869 
19870    if (p->lastinvite) {
19871       /* if this is a request in an active dialog, just confirm that the dialog exists. */
19872       transmit_response_with_allow(p, "200 OK", req, 0);
19873       return 0;
19874    }
19875 
19876    res = get_destination(p, req);
19877    build_contact(p);
19878 
19879    if (ast_strlen_zero(p->context))
19880       ast_string_field_set(p, context, sip_cfg.default_context);
19881 
19882    if (ast_shutting_down())
19883       transmit_response_with_allow(p, "503 Unavailable", req, 0);
19884    else if (res < 0)
19885       transmit_response_with_allow(p, "404 Not Found", req, 0);
19886    else 
19887       transmit_response_with_allow(p, "200 OK", req, 0);
19888 
19889    /* Destroy if this OPTIONS was the opening request, but not if
19890       it's in the middle of a normal call flow. */
19891    sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19892 
19893    return res;
19894 }
19895 
19896 /*! \brief Handle the transfer part of INVITE with a replaces: header, 
19897     meaning a target pickup or an attended transfer.
19898     Used only once.
19899    XXX 'ignore' is unused.
19900 
19901    \note this function is called by handle_request_invite(). Four locks
19902    held at the beginning of this function, p, p->owner, p->refer->refer_call->owner...
19903    only p's lock should remain at the end of this function.  p's lock is held by sipsock_read()
19904  */
19905 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *nounlock)
19906 {
19907    int earlyreplace = 0;
19908    int oneleggedreplace = 0;     /* Call with no bridge, propably IVR or voice message */
19909    struct ast_channel *c = p->owner;   /* Our incoming call */
19910    struct ast_channel *replacecall = p->refer->refer_call->owner; /* The channel we're about to take over */
19911    struct ast_channel *targetcall;     /* The bridge to the take-over target */
19912 
19913    struct ast_channel *test;
19914 
19915    /* Check if we're in ring state */
19916    if (replacecall->_state == AST_STATE_RING)
19917       earlyreplace = 1;
19918 
19919    /* Check if we have a bridge */
19920    if (!(targetcall = ast_bridged_channel(replacecall))) {
19921       /* We have no bridge */
19922       if (!earlyreplace) {
19923          ast_debug(2, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
19924          oneleggedreplace = 1;
19925       }
19926    } 
19927    if (targetcall && targetcall->_state == AST_STATE_RINGING)
19928       ast_debug(4, "SIP transfer: Target channel is in ringing state\n");
19929 
19930    if (targetcall) 
19931       ast_debug(4, "SIP transfer: Invite Replace incoming channel should bridge to channel %s while hanging up channel %s\n", targetcall->name, replacecall->name); 
19932    else
19933       ast_debug(4, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name); 
19934 
19935    if (req->ignore) {
19936       ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
19937       /* We should answer something here. If we are here, the
19938          call we are replacing exists, so an accepted 
19939          can't harm */
19940       transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE);
19941       /* Do something more clever here */
19942       if (c) {
19943          *nounlock = 1;
19944          ast_channel_unlock(c);
19945       }
19946       ast_channel_unlock(replacecall);
19947       sip_pvt_unlock(p->refer->refer_call);
19948       return 1;
19949    } 
19950    if (!c) {
19951       /* What to do if no channel ??? */
19952       ast_log(LOG_ERROR, "Unable to create new channel.  Invite/replace failed.\n");
19953       transmit_response_reliable(p, "503 Service Unavailable", req);
19954       append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
19955       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19956       ast_channel_unlock(replacecall);
19957       sip_pvt_unlock(p->refer->refer_call);
19958       return 1;
19959    }
19960    append_history(p, "Xfer", "INVITE/Replace received");
19961    /* We have three channels to play with
19962       channel c: New incoming call
19963       targetcall: Call from PBX to target
19964       p->refer->refer_call: SIP pvt dialog from transferer to pbx.
19965       replacecall: The owner of the previous
19966       We need to masq C into refer_call to connect to 
19967       targetcall;
19968       If we are talking to internal audio stream, target call is null.
19969    */
19970 
19971    /* Fake call progress */
19972    transmit_response(p, "100 Trying", req);
19973    ast_setstate(c, AST_STATE_RING);
19974 
19975    /* Masquerade the new call into the referred call to connect to target call 
19976       Targetcall is not touched by the masq */
19977 
19978    /* Answer the incoming call and set channel to UP state */
19979    transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE);
19980       
19981    ast_setstate(c, AST_STATE_UP);
19982    
19983    /* Stop music on hold and other generators */
19984    ast_quiet_chan(replacecall);
19985    ast_quiet_chan(targetcall);
19986    ast_debug(4, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);
19987 
19988    /* Make sure that the masq does not free our PVT for the old call */
19989    if (! earlyreplace && ! oneleggedreplace )
19990       ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER);  /* Delay hangup */
19991 
19992    /* Prepare the masquerade - if this does not happen, we will be gone */
19993    if(ast_channel_masquerade(replacecall, c))
19994       ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
19995    else
19996       ast_debug(4, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);
19997 
19998    /* C should now be in place of replacecall */
19999    if (ast_do_masquerade(replacecall)) {
20000       ast_log(LOG_WARNING, "Failed to perform masquerade with INVITE replaces\n");
20001    }
20002 
20003    if (earlyreplace || oneleggedreplace ) {
20004       c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
20005    }
20006 
20007    ast_setstate(c, AST_STATE_DOWN);
20008    ast_debug(4, "After transfer:----------------------------\n");
20009    ast_debug(4, " -- C:        %s State %s\n", c->name, ast_state2str(c->_state));
20010    if (replacecall)
20011       ast_debug(4, " -- replacecall:        %s State %s\n", replacecall->name, ast_state2str(replacecall->_state));
20012    if (p->owner) {
20013       ast_debug(4, " -- P->owner: %s State %s\n", p->owner->name, ast_state2str(p->owner->_state));
20014       test = ast_bridged_channel(p->owner);
20015       if (test)
20016          ast_debug(4, " -- Call bridged to P->owner: %s State %s\n", test->name, ast_state2str(test->_state));
20017       else
20018          ast_debug(4, " -- No call bridged to C->owner \n");
20019    } else 
20020       ast_debug(4, " -- No channel yet \n");
20021    ast_debug(4, "End After transfer:----------------------------\n");
20022 
20023    /* unlock sip pvt and owner so hangup can do its thing */
20024    ast_channel_unlock(replacecall);
20025    ast_channel_unlock(c);
20026    sip_pvt_unlock(p->refer->refer_call);
20027    sip_pvt_unlock(p);
20028    *nounlock = 1;
20029 
20030    /* The call should be down with no ast_channel, so hang it up */
20031    c->tech_pvt = dialog_unref(c->tech_pvt, "unref dialog c->tech_pvt");
20032    ast_hangup(c);
20033    sip_pvt_lock(p); /* lock PVT structure again after hangup */
20034 
20035    return 0;
20036 }
20037 
20038 /*! \brief helper routine for sip_uri_cmp to compare URI parameters
20039  *
20040  * This takes the parameters from two SIP URIs and determines
20041  * if the URIs match. The rules for parameters *suck*. Here's a breakdown
20042  * 1. If a parameter appears in both URIs, then they must have the same value
20043  *    in order for the URIs to match
20044  * 2. If one URI has a user, maddr, ttl, or method parameter, then the other
20045  *    URI must also have that parameter and must have the same value
20046  *    in order for the URIs to match
20047  * 3. All other headers appearing in only one URI are not considered when
20048  *    determining if URIs match
20049  *
20050  * \param input1 Parameters from URI 1
20051  * \param input2 Parameters from URI 2
20052  * \retval 0 URIs' parameters match
20053  * \retval nonzero URIs' parameters do not match
20054  */
20055 static int sip_uri_params_cmp(const char *input1, const char *input2)
20056 {
20057    char *params1 = NULL;
20058    char *params2 = NULL;
20059    char *pos1;
20060    char *pos2;
20061    int zerolength1 = 0;
20062    int zerolength2 = 0;
20063    int maddrmatch = 0;
20064    int ttlmatch = 0;
20065    int usermatch = 0;
20066    int methodmatch = 0;
20067 
20068    if (ast_strlen_zero(input1)) {
20069       zerolength1 = 1;
20070    } else {
20071       params1 = ast_strdupa(input1);
20072    }
20073    if (ast_strlen_zero(input2)) {
20074       zerolength2 = 1;
20075    } else {
20076       params2 = ast_strdupa(input2);
20077    }
20078 
20079    /* Quick optimization. If both params are zero-length, then
20080     * they match
20081     */
20082    if (zerolength1 && zerolength2) {
20083       return 0;
20084    }
20085 
20086    for (pos1 = strsep(&params1, ";"); pos1; pos1 = strsep(&params1, ";")) {
20087       char *value1 = pos1;
20088       char *name1 = strsep(&value1, "=");
20089       char *params2dup = NULL;
20090       int matched = 0;
20091       if (!value1) {
20092          value1 = "";
20093       }
20094       /* Checkpoint reached. We have the name and value parsed for param1
20095        * We have to duplicate params2 each time through this loop
20096        * or else the inner loop below will not work properly.
20097        */
20098       if (!zerolength2) {
20099          params2dup = ast_strdupa(params2);
20100       }
20101       for (pos2 = strsep(&params2dup, ";"); pos2; pos2 = strsep(&params2dup, ";")) {
20102          char *name2 = pos2;
20103          char *value2 = strchr(pos2, '=');
20104          if (!value2) {
20105             value2 = "";
20106          } else {
20107             *value2++ = '\0';
20108          }
20109          if (!strcasecmp(name1, name2)) {
20110             if (strcasecmp(value1, value2)) {
20111                goto fail;
20112             } else {
20113                matched = 1;
20114                break;
20115             }
20116          }
20117       }
20118       /* Check to see if the parameter is one of the 'must-match' parameters */
20119       if (!strcasecmp(name1, "maddr")) {
20120          if (matched) {
20121             maddrmatch = 1;
20122          } else {
20123             goto fail;
20124          }
20125       } else if (!strcasecmp(name1, "ttl")) {
20126          if (matched) {
20127             ttlmatch = 1;
20128          } else {
20129             goto fail;
20130          }
20131       } else if (!strcasecmp(name1, "user")) {
20132          if (matched) {
20133             usermatch = 1;
20134          } else {
20135             goto fail;
20136          }
20137       } else if (!strcasecmp(name1, "method")) {
20138          if (matched) {
20139             methodmatch = 1;
20140          } else {
20141             goto fail;
20142          }
20143       }
20144    }
20145 
20146    /* We've made it out of that horrible O(m*n) construct and there are no
20147     * failures yet. We're not done yet, though, because params2 could have
20148     * an maddr, ttl, user, or method header and params1 did not.
20149     */
20150    for (pos2 = strsep(&params2, ";"); pos2; pos2 = strsep(&params2, ";")) {
20151       char *value2 = pos2;
20152       char *name2 = strsep(&value2, "=");
20153       if (!value2) {
20154          value2 = "";
20155       }
20156       if ((!strcasecmp(name2, "maddr") && !maddrmatch) ||
20157             (!strcasecmp(name2, "ttl") && !ttlmatch) ||
20158             (!strcasecmp(name2, "user") && !usermatch) ||
20159             (!strcasecmp(name2, "method") && !methodmatch)) {
20160          goto fail;
20161       }
20162    }
20163    return 0;
20164 
20165 fail:
20166    return 1;
20167 }
20168 
20169 /*! \brief helper routine for sip_uri_cmp
20170  *
20171  * This takes the "headers" from two SIP URIs and determines
20172  * if the URIs match. The rules for headers is simple. If a header
20173  * appears in one URI, then it must also appear in the other URI. The
20174  * order in which the headers appear does not matter.
20175  *
20176  * \param input1 Headers from URI 1
20177  * \param input2 Headers from URI 2
20178  * \return Return 0 if the URIs' headers match, 1 if they do not
20179  */
20180 static int sip_uri_headers_cmp(const char *input1, const char *input2)
20181 {
20182    char *headers1 = NULL;
20183    char *headers2 = NULL;
20184    int zerolength1 = 0;
20185    int zerolength2 = 0;
20186    int different = 0;
20187    char *header1;
20188 
20189    if (ast_strlen_zero(input1)) {
20190       zerolength1 = 1;
20191    } else {
20192       headers1 = ast_strdupa(input1);
20193    }
20194    
20195    if (ast_strlen_zero(input2)) {
20196       zerolength2 = 1;
20197    } else {
20198       headers2 = ast_strdupa(input2);
20199    }
20200 
20201    if ((zerolength1 && !zerolength2) ||
20202          (zerolength2 && !zerolength1))
20203       return 1;
20204 
20205    if (zerolength1 && zerolength2)
20206       return 0;
20207 
20208    /* At this point, we can definitively state that both inputs are
20209     * not zero-length. First, one more optimization. If the length
20210     * of the headers is not equal, then we definitely have no match
20211     */
20212    if (strlen(headers1) != strlen(headers2)) {
20213       return 1;
20214    }
20215 
20216    for (header1 = strsep(&headers1, "&"); header1; header1 = strsep(&headers1, "&")) {
20217       if (!strcasestr(headers2, header1)) {
20218          different = 1;
20219          break;
20220       }
20221    }
20222 
20223    return different;
20224 }
20225 
20226 static int sip_uri_cmp(const char *input1, const char *input2)
20227 {
20228    char *uri1 = ast_strdupa(input1);
20229    char *uri2 = ast_strdupa(input2);
20230    char *host1;
20231    char *host2;
20232    char *params1;
20233    char *params2;
20234    char *headers1;
20235    char *headers2;
20236 
20237    /* Strip off "sip:" from the URI. We know this is present
20238     * because it was checked back in parse_request()
20239     */
20240    strsep(&uri1, ":");
20241    strsep(&uri2, ":");
20242 
20243    if ((host1 = strchr(uri1, '@'))) {
20244       *host1++ = '\0';
20245    }
20246    if ((host2 = strchr(uri2, '@'))) {
20247       *host2++ = '\0';
20248    }
20249 
20250    /* Check for mismatched username and passwords. This is the
20251     * only case-sensitive comparison of a SIP URI
20252     */
20253    if ((host1 && !host2) ||
20254          (host2 && !host1) ||
20255          (host1 && host2 && strcmp(uri1, uri2))) {
20256       return 1;
20257    }
20258 
20259    if (!host1)
20260       host1 = uri1;
20261    if (!host2)
20262       host2 = uri2;
20263 
20264    /* Strip off the parameters and headers so we can compare
20265     * host and port
20266     */
20267 
20268    if ((params1 = strchr(host1, ';'))) {
20269       *params1++ = '\0';
20270    }
20271    if ((params2 = strchr(host2, ';'))) {
20272       *params2++ = '\0';
20273    }
20274 
20275    /* Headers come after parameters, but there may be headers without
20276     * parameters, thus the S_OR
20277     */
20278    if ((headers1 = strchr(S_OR(params1, host1), '?'))) {
20279       *headers1++ = '\0';
20280    }
20281    if ((headers2 = strchr(S_OR(params2, host2), '?'))) {
20282       *headers2++ = '\0';
20283    }
20284 
20285    /* Now the host/port are properly isolated. We can get by with a string comparison
20286     * because the SIP URI checking rules have some interesting exceptions that make
20287     * this possible. I will note 2 in particular
20288     * 1. hostnames which resolve to the same IP address as well as a hostname and its
20289     *    IP address are not considered a match with SIP URI's.
20290     * 2. If one URI specifies a port and the other does not, then the URIs do not match.
20291     *    This includes if one URI explicitly contains port 5060 and the other implies it
20292     *    by not having a port specified.
20293     */
20294 
20295    if (strcasecmp(host1, host2)) {
20296       return 1;
20297    }
20298 
20299    /* Headers have easier rules to follow, so do those first */
20300    if (sip_uri_headers_cmp(headers1, headers2)) {
20301       return 1;
20302    }
20303 
20304    /* And now the parameters. Ugh */
20305    return sip_uri_params_cmp(params1, params2);
20306 }
20307 
20308 /*! \note No channel or pvt locks should be held while calling this function. */
20309 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context)
20310 {
20311    struct ast_str *str = ast_str_alloca(AST_MAX_EXTENSION + AST_MAX_CONTEXT + 2);
20312    struct ast_app *pickup = pbx_findapp("Pickup");
20313 
20314    if (!pickup) {
20315       ast_log(LOG_ERROR, "Unable to perform pickup: Application 'Pickup' not loaded (app_directed_pickup.so).\n");
20316       return -1;
20317    }
20318 
20319    ast_str_set(&str, 0, "%s@%s", extension, sip_cfg.notifycid == IGNORE_CONTEXT ? "PICKUPMARK" : context);
20320 
20321    ast_debug(2, "About to call Pickup(%s)\n", str->str);
20322 
20323    /* There is no point in capturing the return value since pickup_exec
20324       doesn't return anything meaningful unless the passed data is an empty
20325       string (which in our case it will not be) */
20326    pbx_exec(channel, pickup, str->str);
20327 
20328    return 0;
20329 }
20330 
20331 /*! \brief Called to deny a T38 reinvite if the core does not respond to our request */
20332 static int sip_t38_abort(const void *data)
20333 {
20334    struct sip_pvt *p = (struct sip_pvt *) data;
20335 
20336    sip_pvt_lock(p);
20337    /* an application may have taken ownership of the T.38 negotiation on this
20338     * channel while we were waiting to grab the lock... if it did, the scheduler
20339     * id will have been reset to -1, which is our indication that we do *not*
20340     * want to abort the negotiation process
20341     */
20342    if (p->t38id != -1) {
20343       change_t38_state(p, T38_DISABLED);
20344       transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
20345       p->t38id = -1;
20346       dialog_unref(p, "unref the dialog ptr from sip_t38_abort, because it held a dialog ptr");
20347    }
20348    sip_pvt_unlock(p);
20349    return 0;
20350 }
20351 
20352 /*! \brief Handle incoming INVITE request
20353 \note    If the INVITE has a Replaces header, it is part of an
20354  * attended transfer. If so, we do not go through the dial
20355  * plan but tries to find the active call and masquerade
20356  * into it 
20357  */
20358 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)
20359 {
20360    int res = 1;
20361    int gotdest;
20362    const char *p_replaces;
20363    char *replace_id = NULL;
20364    int refer_locked = 0;
20365    const char *required;
20366    unsigned int required_profile = 0;
20367    struct ast_channel *c = NULL;    /* New channel */
20368    int reinvite = 0;
20369    int rtn;
20370 
20371    const char *p_uac_se_hdr;       /* UAC's Session-Expires header string                      */
20372    const char *p_uac_min_se;       /* UAC's requested Min-SE interval (char string)            */
20373    int uac_max_se = -1;            /* UAC's Session-Expires in integer format                  */
20374    int uac_min_se = -1;            /* UAC's Min-SE in integer format                           */
20375    int st_active = FALSE;          /* Session-Timer on/off boolean                             */
20376    int st_interval = 0;            /* Session-Timer negotiated refresh interval                */
20377    enum st_refresher st_ref;       /* Session-Timer session refresher                          */
20378    int dlg_min_se = -1;
20379    struct {
20380       char exten[AST_MAX_EXTENSION];
20381       char context[AST_MAX_CONTEXT];
20382    } pickup = {
20383       .exten = "",
20384    };
20385    st_ref = SESSION_TIMER_REFRESHER_AUTO;
20386 
20387    /* Find out what they support */
20388    if (!p->sipoptions) {
20389       const char *supported = get_header(req, "Supported");
20390       if (!ast_strlen_zero(supported))
20391          parse_sip_options(p, supported);
20392    }
20393 
20394    /* Find out what they require */
20395    required = get_header(req, "Require");
20396    if (!ast_strlen_zero(required)) {
20397       required_profile = parse_sip_options(NULL, required);
20398       if (required_profile && !(required_profile & (SIP_OPT_REPLACES | SIP_OPT_TIMER))) {
20399          /* At this point we only support REPLACES and Session-Timer */
20400          transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, required);
20401          ast_log(LOG_WARNING, "Received SIP INVITE with unsupported required extension: %s\n", required);
20402          p->invitestate = INV_COMPLETED;
20403          if (!p->lastinvite)
20404             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20405          res = -1;
20406          goto request_invite_cleanup;
20407       }
20408    }
20409 
20410    /* The option tags may be present in Supported: or Require: headers.
20411    Include the Require: option tags for further processing as well */
20412    p->sipoptions |= required_profile;
20413    p->reqsipoptions = required_profile;
20414 
20415    /* Check if this is a loop */
20416    if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && p->owner && (p->invitestate != INV_TERMINATED && p->invitestate != INV_CONFIRMED)) {
20417       /* This is a call to ourself.  Send ourselves an error code and stop
20418          processing immediately, as SIP really has no good mechanism for
20419          being able to call yourself */
20420       /* If pedantic is on, we need to check the tags. If they're different, this is
20421          in fact a forked call through a SIP proxy somewhere. */
20422       int different;
20423       char *initial_rlPart2 = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
20424       char *this_rlPart2 = REQ_OFFSET_TO_STR(req, rlPart2);
20425       if (sip_cfg.pedanticsipchecking)
20426          different = sip_uri_cmp(initial_rlPart2, this_rlPart2);
20427       else
20428          different = strcmp(initial_rlPart2, this_rlPart2);
20429       if (!different) {
20430          transmit_response(p, "482 Loop Detected", req);
20431          p->invitestate = INV_COMPLETED;
20432          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20433          res = 0;
20434          goto request_invite_cleanup;
20435       } else {
20436          /*! This is a spiral. What we need to do is to just change the outgoing INVITE
20437           * so that it now routes to the new Request URI. Since we created the INVITE ourselves
20438           * that should be all we need to do.
20439           * 
20440           * \todo XXX This needs to be reviewed.  YOu don't change the request URI really, you route the packet
20441           * correctly instead...
20442           */
20443          char *uri = ast_strdupa(this_rlPart2);
20444          char *at = strchr(uri, '@');
20445          char *peerorhost;
20446          ast_debug(2, "Potential spiral detected. Original RURI was %s, new RURI is %s\n", initial_rlPart2, this_rlPart2);
20447          transmit_response(p, "100 Trying", req);
20448          if (at) {
20449             *at = '\0';
20450          }
20451          /* Parse out "sip:" */
20452          if ((peerorhost = strchr(uri, ':'))) {
20453             *peerorhost++ = '\0';
20454          }
20455          ast_string_field_set(p, theirtag, NULL);
20456          /* Treat this as if there were a call forward instead...
20457           */
20458          ast_string_field_set(p->owner, call_forward, peerorhost);
20459          ast_queue_control(p->owner, AST_CONTROL_BUSY);
20460          res = 0;
20461          goto request_invite_cleanup;
20462       }
20463    }
20464 
20465    if (!req->ignore && p->pendinginvite) {
20466       if (!ast_test_flag(&p->flags[0], SIP_OUTGOING) && (p->invitestate == INV_COMPLETED || p->invitestate == INV_TERMINATED)) {
20467          /* What do these circumstances mean? We have received an INVITE for an "incoming" dialog for which we
20468           * have sent a final response. We have not yet received an ACK, though (which is why p->pendinginvite is non-zero).
20469           * We also know that the INVITE is not a retransmission, because otherwise the "ignore" flag would be set.
20470           * This means that either we are receiving a reinvite for a terminated dialog, or we are receiving an INVITE with
20471           * credentials based on one we challenged earlier.
20472           *
20473           * The action to take in either case is to treat the INVITE as though it contains an implicit ACK for the previous
20474           * transaction. Calling __sip_ack will take care of this by clearing the p->pendinginvite and removing the response
20475           * from the previous transaction from the list of outstanding packets.
20476           */
20477          __sip_ack(p, p->pendinginvite, 1, 0);
20478       } else {
20479          /* We already have a pending invite. Sorry. You are on hold. */
20480          p->glareinvite = seqno;     /* must hold on to this seqno to process ack and retransmit correctly */
20481          if (p->rtp && find_sdp(req)) {
20482             struct sockaddr_in sin;
20483             if (get_ip_and_port_from_sdp(req, SDP_AUDIO, &sin)) {
20484                ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Audio may not work properly on this call.\n");
20485             } else {
20486                ast_rtp_set_alt_peer(p->rtp, &sin);
20487             }
20488             if (p->vrtp) {
20489                if (get_ip_and_port_from_sdp(req, SDP_VIDEO, &sin)) {
20490                   ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Video may not work properly on this call.\n");
20491                } else {
20492                   ast_rtp_set_alt_peer(p->vrtp, &sin);
20493                }
20494             }
20495          }
20496          transmit_response_reliable(p, "491 Request Pending", req);
20497          ast_debug(1, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
20498          /* Don't destroy dialog here */
20499          res = 0;
20500          goto request_invite_cleanup;
20501       }
20502    }
20503 
20504    p_replaces = get_header(req, "Replaces");
20505    if (!ast_strlen_zero(p_replaces)) {
20506       /* We have a replaces header */
20507       char *ptr;
20508       char *fromtag = NULL;
20509       char *totag = NULL;
20510       char *start, *to;
20511       int error = 0;
20512 
20513       if (p->owner) {
20514          ast_debug(3, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
20515          transmit_response_reliable(p, "400 Bad request", req);   /* The best way to not not accept the transfer */
20516          /* Do not destroy existing call */
20517          res = -1;
20518          goto request_invite_cleanup;
20519       }
20520 
20521       if (sipdebug)
20522          ast_debug(3, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
20523       /* Create a buffer we can manipulate */
20524       replace_id = ast_strdupa(p_replaces);
20525       ast_uri_decode(replace_id);
20526 
20527       if (!p->refer && !sip_refer_allocate(p)) {
20528          transmit_response_reliable(p, "500 Server Internal Error", req);
20529          append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
20530          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20531          p->invitestate = INV_COMPLETED;
20532          res = -1;
20533          goto request_invite_cleanup;
20534       }
20535 
20536       /*  Todo: (When we find phones that support this)
20537          if the replaces header contains ";early-only"
20538          we can only replace the call in early
20539          stage, not after it's up.
20540 
20541          If it's not in early mode, 486 Busy.
20542       */
20543 
20544       /* Skip leading whitespace */
20545       replace_id = ast_skip_blanks(replace_id);
20546 
20547       start = replace_id;
20548       while ( (ptr = strsep(&start, ";")) ) {
20549          ptr = ast_skip_blanks(ptr); /* XXX maybe unnecessary ? */
20550          if ( (to = strcasestr(ptr, "to-tag=") ) )
20551             totag = to + 7;   /* skip the keyword */
20552          else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
20553             fromtag = to + 9; /* skip the keyword */
20554             fromtag = strsep(&fromtag, "&"); /* trim what ? */
20555          }
20556       }
20557 
20558       if (sipdebug)
20559          ast_debug(4, "Invite/replaces: Will use Replace-Call-ID : %s Fromtag: %s Totag: %s\n",
20560                  replace_id,
20561                  fromtag ? fromtag : "<no from tag>",
20562                  totag ? totag : "<no to tag>");
20563 
20564       /* Try to find call that we are replacing.
20565          If we have a Replaces header, we need to cancel that call if we succeed with this call.
20566          First we cheat a little and look for a magic call-id from phones that support
20567          dialog-info+xml so we can do technology independent pickup... */
20568       if (strncmp(replace_id, "pickup-", 7) == 0) {
20569          struct sip_pvt *subscription = NULL;
20570          replace_id += 7; /* Worst case we are looking at \0 */
20571 
20572          if ((subscription = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
20573             ast_log(LOG_NOTICE, "Unable to find subscription with call-id: %s\n", replace_id);
20574             transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
20575             error = 1;
20576          } else {
20577             ast_log(LOG_NOTICE, "Trying to pick up %s@%s\n", subscription->exten, subscription->context);
20578             ast_copy_string(pickup.exten, subscription->exten, sizeof(pickup.exten));
20579             ast_copy_string(pickup.context, subscription->context, sizeof(pickup.context));
20580             sip_pvt_unlock(subscription);
20581             if (subscription->owner) {
20582                ast_channel_unlock(subscription->owner);
20583             }
20584          }
20585       }
20586 
20587       /* This locks both refer_call pvt and refer_call pvt's owner!!!*/
20588       if (!error && ast_strlen_zero(pickup.exten) && (p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
20589          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
20590          transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
20591          error = 1;
20592       } else {
20593          refer_locked = 1;
20594       }
20595 
20596       /* The matched call is the call from the transferer to Asterisk .
20597          We want to bridge the bridged part of the call to the 
20598          incoming invite, thus taking over the refered call */
20599 
20600       if (p->refer->refer_call == p) {
20601          ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
20602          p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
20603          transmit_response_reliable(p, "400 Bad request", req);   /* The best way to not not accept the transfer */
20604          error = 1;
20605       }
20606 
20607       if (!error && ast_strlen_zero(pickup.exten) && !p->refer->refer_call->owner) {
20608          /* Oops, someting wrong anyway, no owner, no call */
20609          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
20610          /* Check for better return code */
20611          transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replace)", req);
20612          error = 1;
20613       }
20614 
20615       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) {
20616          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
20617          transmit_response_reliable(p, "603 Declined (Replaces)", req);
20618          error = 1;
20619       }
20620 
20621       if (error) {   /* Give up this dialog */
20622          append_history(p, "Xfer", "INVITE/Replace Failed.");
20623          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20624          sip_pvt_unlock(p);
20625          if (p->refer->refer_call) {
20626             sip_pvt_unlock(p->refer->refer_call);
20627             if (p->refer->refer_call->owner) {
20628                ast_channel_unlock(p->refer->refer_call->owner);
20629             }
20630          }
20631          refer_locked = 0;
20632          p->invitestate = INV_COMPLETED;
20633          res = -1;
20634          goto request_invite_cleanup;
20635       }
20636    }
20637 
20638    /* Check if this is an INVITE that sets up a new dialog or
20639       a re-invite in an existing dialog */
20640 
20641    if (!req->ignore) {
20642       int newcall = (p->initreq.headers ? TRUE : FALSE);
20643 
20644       if (sip_cancel_destroy(p))
20645          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
20646       /* This also counts as a pending invite */
20647       p->pendinginvite = seqno;
20648       check_via(p, req);
20649 
20650       copy_request(&p->initreq, req);     /* Save this INVITE as the transaction basis */
20651       if (sipdebug)
20652          ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
20653       if (!p->owner) {  /* Not a re-invite */
20654          if (debug)
20655             ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
20656          if (newcall)
20657             append_history(p, "Invite", "New call: %s", p->callid);
20658          parse_ok_contact(p, req);
20659       } else { /* Re-invite on existing call */
20660          ast_clear_flag(&p->flags[0], SIP_OUTGOING);  /* This is now an inbound dialog */
20661          /* Handle SDP here if we already have an owner */
20662          if (find_sdp(req)) {
20663             if (process_sdp(p, req, SDP_T38_INITIATE)) {
20664                transmit_response_reliable(p, "488 Not acceptable here", req);
20665                if (!p->lastinvite)
20666                   sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20667                res = -1;
20668                goto request_invite_cleanup;
20669             }
20670             ast_queue_control(p->owner, AST_CONTROL_SRCUPDATE);
20671          } else {
20672             p->jointcapability = p->capability;
20673             ast_debug(1, "Hm....  No sdp for the moment\n");
20674             /* Some devices signal they want to be put off hold by sending a re-invite
20675                *without* an SDP, which is supposed to mean "Go back to your state"
20676                and since they put os on remote hold, we go back to off hold */
20677             if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
20678                ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
20679                /* Activate a re-invite */
20680                ast_queue_frame(p->owner, &ast_null_frame);
20681                change_hold_state(p, req, FALSE, 0);
20682             }
20683          }
20684          if (p->do_history) /* This is a response, note what it was for */
20685             append_history(p, "ReInv", "Re-invite received");
20686       }
20687    } else if (debug)
20688       ast_verbose("Ignoring this INVITE request\n");
20689 
20690    if (!p->lastinvite && !req->ignore && !p->owner) {
20691       /* This is a new invite */
20692       /* Handle authentication if this is our first invite */
20693       res = check_user(p, req, SIP_INVITE, e, XMIT_RELIABLE, sin);
20694       if (res == AUTH_CHALLENGE_SENT) {
20695          p->invitestate = INV_COMPLETED;     /* Needs to restart in another INVITE transaction */
20696          res = 0;
20697          goto request_invite_cleanup;
20698       }
20699       if (res < 0) { /* Something failed in authentication */
20700          if (res == AUTH_FAKE_AUTH) {
20701             ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
20702             transmit_fake_auth_response(p, SIP_INVITE, req, XMIT_RELIABLE);
20703          } else {
20704             ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
20705             transmit_response_reliable(p, "403 Forbidden", req);
20706          }
20707          p->invitestate = INV_COMPLETED;
20708          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20709          ast_string_field_set(p, theirtag, NULL);
20710          res = 0;
20711          goto request_invite_cleanup;
20712       }
20713 
20714       /* If T38 is needed but not present, then make it magically appear */
20715       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && !p->udptl) {
20716          if ((p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr))) {
20717             p->t38_maxdatagram = global_t38_maxdatagram;
20718             set_t38_capabilities(p);
20719          } else {
20720             /* udptl creation failed, T38 can not be supported on this dialog */
20721             ast_debug(1, "UDPTL creation failed on dialog.\n");
20722             ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
20723          }
20724       }
20725 
20726       req->authenticated = 1;
20727 
20728       /* We have a succesful authentication, process the SDP portion if there is one */
20729       if (find_sdp(req)) {
20730          if (process_sdp(p, req, SDP_T38_INITIATE)) {
20731             /* Unacceptable codecs */
20732             transmit_response_reliable(p, "488 Not acceptable here", req);
20733             p->invitestate = INV_COMPLETED;
20734             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20735             ast_debug(1, "No compatible codecs for this SIP call.\n");
20736             res = -1;
20737             goto request_invite_cleanup;
20738          }
20739       } else { /* No SDP in invite, call control session */
20740          p->jointcapability = p->capability;
20741          ast_debug(2, "No SDP in Invite, third party call control\n");
20742       }
20743 
20744       /* Queue NULL frame to prod ast_rtp_bridge if appropriate */
20745       /* This seems redundant ... see !p-owner above */
20746       if (p->owner)
20747          ast_queue_frame(p->owner, &ast_null_frame);
20748 
20749 
20750       /* Initialize the context if it hasn't been already */
20751       if (ast_strlen_zero(p->context))
20752          ast_string_field_set(p, context, sip_cfg.default_context);
20753 
20754 
20755       /* Check number of concurrent calls -vs- incoming limit HERE */
20756       ast_debug(1, "Checking SIP call limits for device %s\n", p->username);
20757       if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
20758          if (res < 0) {
20759             ast_log(LOG_NOTICE, "Failed to place call for device %s, too many calls\n", p->username);
20760             transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
20761             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20762             p->invitestate = INV_COMPLETED;
20763          }
20764          res = 0;
20765          goto request_invite_cleanup;
20766       }
20767       gotdest = get_destination(p, NULL); /* Get destination right away */
20768       get_rdnis(p, NULL);        /* Get redirect information */
20769       extract_uri(p, req);       /* Get the Contact URI */
20770       build_contact(p);       /* Build our contact header */
20771 
20772       if (p->rtp) {
20773          ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
20774          ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
20775       }
20776 
20777       if (!replace_id && gotdest) { /* No matching extension found */
20778          if (gotdest == 1 && ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP))
20779             transmit_response_reliable(p, "484 Address Incomplete", req);
20780          else {
20781             char *decoded_exten = ast_strdupa(p->exten);
20782 
20783             transmit_response_reliable(p, "404 Not Found", req);
20784             ast_uri_decode(decoded_exten);
20785             ast_log(LOG_NOTICE, "Call from '%s' to extension"
20786                " '%s' rejected because extension not found in context '%s'.\n",
20787                S_OR(p->username, p->peername), decoded_exten, p->context);
20788          }
20789          p->invitestate = INV_COMPLETED;
20790          update_call_counter(p, DEC_CALL_LIMIT);
20791          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20792          res = 0;
20793          goto request_invite_cleanup;
20794       } else {
20795 
20796          /* If no extension was specified, use the s one */
20797          /* Basically for calling to IP/Host name only */
20798          if (ast_strlen_zero(p->exten))
20799             ast_string_field_set(p, exten, "s");
20800          /* Initialize our tag */
20801 
20802          make_our_tag(p->tag, sizeof(p->tag));
20803          /* First invitation - create the channel.  Allocation
20804           * failures are handled below. */
20805          c = sip_new(p, AST_STATE_DOWN, S_OR(p->peername, NULL));
20806          *recount = 1;
20807 
20808          /* Save Record-Route for any later requests we make on this dialogue */
20809          build_route(p, req, 0);
20810 
20811          if (c) {
20812             /* Pre-lock the call */
20813             ast_channel_lock(c);
20814          }
20815       }
20816    } else {
20817       if (sipdebug) {
20818          if (!req->ignore)
20819             ast_debug(2, "Got a SIP re-invite for call %s\n", p->callid);
20820          else
20821             ast_debug(2, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
20822       }
20823       if (!req->ignore)
20824          reinvite = 1;
20825       c = p->owner;
20826    }
20827 
20828    /* Session-Timers */
20829    if ((p->sipoptions & SIP_OPT_TIMER) && !ast_strlen_zero(get_header(req, "Session-Expires"))) {
20830       /* The UAC has requested session-timers for this session. Negotiate
20831       the session refresh interval and who will be the refresher */
20832       ast_debug(2, "Incoming INVITE with 'timer' option supported and \"Session-Expires\" header.\n");
20833 
20834       /* Allocate Session-Timers struct w/in the dialog */
20835       if (!p->stimer)
20836          sip_st_alloc(p);
20837 
20838       /* Parse the Session-Expires header */
20839       p_uac_se_hdr = get_header(req, "Session-Expires");
20840       rtn = parse_session_expires(p_uac_se_hdr, &uac_max_se, &st_ref);
20841       if (rtn != 0) {
20842          transmit_response_reliable(p, "400 Session-Expires Invalid Syntax", req);
20843          p->invitestate = INV_COMPLETED;
20844          if (!p->lastinvite) {
20845             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20846          }
20847          res = -1;
20848          goto request_invite_cleanup;
20849       }
20850 
20851       /* Parse the Min-SE header */
20852       p_uac_min_se = get_header(req, "Min-SE");
20853       if (!ast_strlen_zero(p_uac_min_se)) {
20854          rtn = parse_minse(p_uac_min_se, &uac_min_se); 
20855          if (rtn != 0) {
20856             transmit_response_reliable(p, "400 Min-SE Invalid Syntax", req);
20857             p->invitestate = INV_COMPLETED;
20858             if (!p->lastinvite) {
20859                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20860             }
20861             res = -1;
20862             goto request_invite_cleanup;
20863          }
20864       }
20865 
20866       dlg_min_se = st_get_se(p, FALSE);
20867       switch (st_get_mode(p, 1)) {
20868       case SESSION_TIMER_MODE_ACCEPT:
20869       case SESSION_TIMER_MODE_ORIGINATE:
20870          if (uac_max_se > 0 && uac_max_se < dlg_min_se) {
20871             transmit_response_with_minse(p, "422 Session Interval Too Small", req, dlg_min_se);
20872             p->invitestate = INV_COMPLETED;
20873             if (!p->lastinvite) {
20874                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20875             }
20876             res = -1;
20877             goto request_invite_cleanup;
20878          }
20879 
20880          p->stimer->st_active_peer_ua = TRUE;
20881          st_active = TRUE;
20882          if (st_ref == SESSION_TIMER_REFRESHER_AUTO) {
20883             st_ref = st_get_refresher(p);
20884          }
20885 
20886          if (uac_max_se > 0) {
20887             int dlg_max_se = st_get_se(p, TRUE);
20888             if (dlg_max_se >= uac_min_se) {
20889                st_interval = (uac_max_se < dlg_max_se) ? uac_max_se : dlg_max_se;
20890             } else {
20891                st_interval = uac_max_se;
20892             }
20893          } else {
20894             /* Set to default max value */
20895             st_interval = global_max_se;
20896          }
20897          break;
20898 
20899       case SESSION_TIMER_MODE_REFUSE:
20900          if (p->reqsipoptions & SIP_OPT_TIMER) {
20901             transmit_response_with_unsupported(p, "420 Option Disabled", req, required);
20902             ast_log(LOG_WARNING, "Received SIP INVITE with supported but disabled option: %s\n", required);
20903             p->invitestate = INV_COMPLETED;
20904             if (!p->lastinvite) {
20905                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20906             }
20907             res = -1;
20908             goto request_invite_cleanup;
20909          }
20910          break;
20911 
20912       default:
20913          ast_log(LOG_ERROR, "Internal Error %d at %s:%d\n", st_get_mode(p, 1), __FILE__, __LINE__);
20914          break;
20915       }
20916    } else {
20917       /* The UAC did not request session-timers.  Asterisk (UAS), will now decide
20918       (based on session-timer-mode in sip.conf) whether to run session-timers for
20919       this session or not. */
20920       switch (st_get_mode(p, 1)) {
20921       case SESSION_TIMER_MODE_ORIGINATE:
20922          st_active = TRUE;
20923          st_interval = st_get_se(p, TRUE);
20924          st_ref = SESSION_TIMER_REFRESHER_UAS;
20925          p->stimer->st_active_peer_ua = FALSE;
20926          break;
20927 
20928       default:
20929          break;
20930       }
20931    }
20932 
20933    if (reinvite == 0) {
20934       /* Session-Timers: Start session refresh timer based on negotiation/config */
20935       if (st_active == TRUE) {
20936          p->stimer->st_active   = TRUE;
20937          p->stimer->st_interval = st_interval;
20938          p->stimer->st_ref      = st_ref;
20939          start_session_timer(p);
20940       }
20941    } else {
20942       if (p->stimer->st_active == TRUE) {
20943          /* Session-Timers:  A re-invite request sent within a dialog will serve as 
20944          a refresh request, no matter whether the re-invite was sent for refreshing 
20945          the session or modifying it.*/
20946          ast_debug (2, "Restarting session-timers on a refresh - %s\n", p->callid);
20947 
20948          /* The UAC may be adjusting the session-timers mid-session */
20949          if (st_interval > 0) {
20950             p->stimer->st_interval = st_interval;
20951             p->stimer->st_ref      = st_ref;
20952          }
20953 
20954          restart_session_timer(p);
20955          if (p->stimer->st_expirys > 0) {
20956             p->stimer->st_expirys--;
20957          }
20958       }
20959    }
20960 
20961    if (!req->ignore && p)
20962       p->lastinvite = seqno;
20963 
20964    if (c && replace_id) {  /* Attended transfer or call pickup - we're the target */
20965       if (!ast_strlen_zero(pickup.exten)) {
20966          append_history(p, "Xfer", "INVITE/Replace received");
20967 
20968          /* Let the caller know we're giving it a shot */
20969          transmit_response(p, "100 Trying", req);
20970          p->invitestate = INV_PROCEEDING;
20971          ast_setstate(c, AST_STATE_RING);
20972 
20973          /* Do the pickup itself */
20974          ast_channel_unlock(c);
20975          *nounlock = 1;
20976 
20977          /* since p->owner (c) is unlocked, we need to go ahead and unlock pvt for both
20978           * magic pickup and ast_hangup.  Both of these functions will attempt to lock
20979           * p->owner again, which can cause a deadlock if we already hold a lock on p.
20980           * Locking order is, channel then pvt.  Dead lock avoidance must be used if
20981           * called the other way around. */
20982          sip_pvt_unlock(p);
20983          do_magic_pickup(c, pickup.exten, pickup.context);
20984          /* Now we're either masqueraded or we failed to pickup, in either case we... */
20985          ast_hangup(c);
20986          sip_pvt_lock(p); /* pvt is expected to remain locked on return, so re-lock it */
20987 
20988          res = 0;
20989          goto request_invite_cleanup;
20990       } else {
20991          /* Go and take over the target call */
20992          if (sipdebug)
20993             ast_debug(4, "Sending this call to the invite/replcaes handler %s\n", p->callid);
20994          res = handle_invite_replaces(p, req, debug, seqno, sin, nounlock);
20995          refer_locked = 0;
20996          goto request_invite_cleanup;
20997       }
20998    }
20999 
21000 
21001    if (c) { /* We have a call  -either a new call or an old one (RE-INVITE) */
21002       enum ast_channel_state c_state = c->_state;
21003 
21004       if (c_state != AST_STATE_UP && reinvite &&
21005          (p->invitestate == INV_TERMINATED || p->invitestate == INV_CONFIRMED)) {
21006          /* If these conditions are true, and the channel is still in the 'ringing'
21007           * state, then this likely means that we have a situation where the initial
21008           * INVITE transaction has completed *but* the channel's state has not yet been
21009           * changed to UP. The reason this could happen is if the reinvite is received
21010           * on the SIP socket prior to an application calling ast_read on this channel
21011           * to read the answer frame we earlier queued on it. In this case, the reinvite
21012           * is completely legitimate so we need to handle this the same as if the channel 
21013           * were already UP. Thus we are purposely falling through to the AST_STATE_UP case.
21014           */
21015          c_state = AST_STATE_UP;
21016       }
21017 
21018       switch(c_state) {
21019       case AST_STATE_DOWN:
21020          ast_debug(2, "%s: New call is still down.... Trying... \n", c->name);
21021          transmit_provisional_response(p, "100 Trying", req, 0);
21022          p->invitestate = INV_PROCEEDING;
21023          ast_setstate(c, AST_STATE_RING);
21024          if (strcmp(p->exten, ast_pickup_ext())) { /* Call to extension -start pbx on this call */
21025             enum ast_pbx_result result;
21026 
21027             result = ast_pbx_start(c);
21028 
21029             switch(result) {
21030             case AST_PBX_FAILED:
21031                ast_log(LOG_WARNING, "Failed to start PBX :(\n");
21032                p->invitestate = INV_COMPLETED;
21033                transmit_response_reliable(p, "503 Unavailable", req);
21034                break;
21035             case AST_PBX_CALL_LIMIT:
21036                ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
21037                p->invitestate = INV_COMPLETED;
21038                transmit_response_reliable(p, "480 Temporarily Unavailable", req);
21039                break;
21040             case AST_PBX_SUCCESS:
21041                /* nothing to do */
21042                break;
21043             }
21044 
21045             if (result) {
21046 
21047                /* Unlock locks so ast_hangup can do its magic */
21048                ast_channel_unlock(c);
21049                *nounlock = 1;
21050                sip_pvt_unlock(p);
21051                ast_hangup(c);
21052                sip_pvt_lock(p);
21053                c = NULL;
21054             }
21055          } else { /* Pickup call in call group */
21056             if (sip_pickup(c)) {
21057                ast_log(LOG_WARNING, "Failed to start Group pickup by %s\n", c->name);
21058                transmit_response_reliable(p, "480 Temporarily Unavailable", req);
21059                sip_alreadygone(p);
21060                c->hangupcause = AST_CAUSE_FAILURE;
21061 
21062                /* Unlock locks so ast_hangup can do its magic */
21063                ast_channel_unlock(c);
21064                *nounlock = 1;
21065 
21066                p->invitestate = INV_COMPLETED;
21067                sip_pvt_unlock(p);
21068                ast_hangup(c);
21069                sip_pvt_lock(p);
21070                c = NULL;
21071             }
21072          }
21073          break;
21074       case AST_STATE_RING:
21075          transmit_provisional_response(p, "100 Trying", req, 0);
21076          p->invitestate = INV_PROCEEDING;
21077          break;
21078       case AST_STATE_RINGING:
21079          transmit_provisional_response(p, "180 Ringing", req, 0);
21080          p->invitestate = INV_PROCEEDING;
21081          break;
21082       case AST_STATE_UP:
21083          ast_debug(2, "%s: This call is UP.... \n", c->name);
21084 
21085          transmit_response(p, "100 Trying", req);
21086 
21087          if (p->t38.state == T38_PEER_REINVITE) {
21088             if (p->t38id > -1) {
21089                /* reset t38 abort timer */
21090                AST_SCHED_DEL_UNREF(sched, p->t38id, dialog_unref(p, "remove ref for t38id"));
21091             }
21092             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."));
21093          } else if (p->t38.state == T38_ENABLED) {
21094             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21095             transmit_response_with_t38_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ?  XMIT_UNRELIABLE : XMIT_CRITICAL)));
21096          } else if (p->t38.state == T38_DISABLED) {
21097             /* If this is not a re-invite or something to ignore - it's critical */
21098             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21099             transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ?  XMIT_UNRELIABLE : XMIT_CRITICAL)), p->session_modify == TRUE ? FALSE:TRUE); 
21100          }
21101 
21102          p->invitestate = INV_TERMINATED;
21103          break;
21104       default:
21105          ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
21106          transmit_response(p, "100 Trying", req);
21107          break;
21108       }
21109    } else {
21110       if (p && (p->autokillid == -1)) {
21111          const char *msg;
21112 
21113          if (!p->jointcapability)
21114             msg = "488 Not Acceptable Here (codec error)";
21115          else {
21116             ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
21117             msg = "503 Unavailable";
21118          }
21119          transmit_response_reliable(p, msg, req);
21120          p->invitestate = INV_COMPLETED;
21121          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21122       }
21123    }
21124 
21125 request_invite_cleanup:
21126 
21127    if (refer_locked && p->refer && p->refer->refer_call) {
21128       sip_pvt_unlock(p->refer->refer_call);
21129       if (p->refer->refer_call->owner) {
21130          ast_channel_unlock(p->refer->refer_call->owner);
21131       }
21132    }
21133 
21134    return res;
21135 }
21136 
21137 /*! \brief  Find all call legs and bridge transferee with target 
21138  * called from handle_request_refer */
21139 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno)
21140 {
21141    struct sip_dual target;    /* Chan 1: Call from tranferer to Asterisk */
21142                /* Chan 2: Call from Asterisk to target */
21143    int res = 0;
21144    struct sip_pvt *targetcall_pvt;
21145 
21146    /* Check if the call ID of the replaces header does exist locally */
21147    if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag, 
21148       transferer->refer->replaces_callid_fromtag))) {
21149       if (transferer->refer->localtransfer) {
21150          /* We did not find the refered call. Sorry, can't accept then */
21151          /* Let's fake a response from someone else in order
21152             to follow the standard */
21153          transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
21154          append_history(transferer, "Xfer", "Refer failed");
21155          ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);  
21156          transferer->refer->status = REFER_FAILED;
21157          return -1;
21158       }
21159       /* Fall through for remote transfers that we did not find locally */
21160       ast_debug(3, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
21161       return 0;
21162    }
21163 
21164    /* Ok, we can accept this transfer */
21165    append_history(transferer, "Xfer", "Refer accepted");
21166    if (!targetcall_pvt->owner) { /* No active channel */
21167       ast_debug(4, "SIP attended transfer: Error: No owner of target call\n");
21168       /* Cancel transfer */
21169       transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
21170       append_history(transferer, "Xfer", "Refer failed");
21171       ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
21172       transferer->refer->status = REFER_FAILED;
21173       sip_pvt_unlock(targetcall_pvt);
21174       if (targetcall_pvt)
21175          ao2_t_ref(targetcall_pvt, -1, "Drop targetcall_pvt pointer");
21176       return -1;
21177    }
21178 
21179    /* We have a channel, find the bridge */
21180    target.chan1 = targetcall_pvt->owner;           /* Transferer to Asterisk */
21181    target.chan2 = ast_bridged_channel(targetcall_pvt->owner);  /* Asterisk to target */
21182 
21183    if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
21184       /* Wrong state of new channel */
21185       if (target.chan2) 
21186          ast_debug(4, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
21187       else if (target.chan1->_state != AST_STATE_RING)
21188          ast_debug(4, "SIP attended transfer: Error: No target channel\n");
21189       else
21190          ast_debug(4, "SIP attended transfer: Attempting transfer in ringing state\n");
21191    }
21192 
21193    /* Transfer */
21194    if (sipdebug) {
21195       if (current->chan2)  /* We have two bridges */
21196          ast_debug(4, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
21197       else        /* One bridge, propably transfer of IVR/voicemail etc */
21198          ast_debug(4, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
21199    }
21200 
21201    ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);   /* Delay hangup */
21202 
21203    /* Perform the transfer */
21204    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",
21205       transferer->owner->name,
21206       transferer->owner->uniqueid,
21207       transferer->callid,
21208       target.chan1->name,
21209       target.chan1->uniqueid);
21210    res = attempt_transfer(current, &target);
21211    sip_pvt_unlock(targetcall_pvt);
21212    if (res) {
21213       /* Failed transfer */
21214       transmit_notify_with_sipfrag(transferer, seqno, "486 Busy Here", TRUE);
21215       append_history(transferer, "Xfer", "Refer failed");
21216       if (targetcall_pvt->owner)
21217          ast_channel_unlock(targetcall_pvt->owner);
21218       ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
21219    } else {
21220       /* Transfer succeeded! */
21221       const char *xfersound = pbx_builtin_getvar_helper(target.chan1, "ATTENDED_TRANSFER_COMPLETE_SOUND");
21222 
21223       /* Tell transferer that we're done. */
21224       transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
21225       append_history(transferer, "Xfer", "Refer succeeded");
21226       transferer->refer->status = REFER_200OK;
21227       if (target.chan2 && !ast_strlen_zero(xfersound) && ast_streamfile(target.chan2, xfersound, target.chan2->language) >= 0) {
21228          ast_waitstream(target.chan2, "");
21229       }
21230       if (targetcall_pvt->owner) {
21231          ast_debug(1, "SIP attended transfer: Unlocking channel %s\n", targetcall_pvt->owner->name);
21232          ast_channel_unlock(targetcall_pvt->owner);
21233       }
21234       ast_indicate(target.chan1, AST_CONTROL_UNHOLD);
21235       if (target.chan2) {
21236          ast_indicate(target.chan2, AST_CONTROL_UNHOLD);
21237       }
21238    }
21239    if (targetcall_pvt)
21240       ao2_t_ref(targetcall_pvt, -1, "drop targetcall_pvt");
21241    return 1;
21242 }
21243 
21244 
21245 /*! \brief Handle incoming REFER request */
21246 /*! \page SIP_REFER SIP transfer Support (REFER)
21247 
21248    REFER is used for call transfer in SIP. We get a REFER
21249    to place a new call with an INVITE somwhere and then
21250    keep the transferor up-to-date of the transfer. If the
21251    transfer fails, get back on line with the orginal call. 
21252 
21253    - REFER can be sent outside or inside of a dialog.
21254      Asterisk only accepts REFER inside of a dialog.
21255 
21256    - If we get a replaces header, it is an attended transfer
21257 
21258    \par Blind transfers
21259    The transferor provides the transferee
21260    with the transfer targets contact. The signalling between
21261    transferer or transferee should not be cancelled, so the
21262    call is recoverable if the transfer target can not be reached 
21263    by the transferee.
21264 
21265    In this case, Asterisk receives a TRANSFER from
21266    the transferor, thus is the transferee. We should
21267    try to set up a call to the contact provided
21268    and if that fails, re-connect the current session.
21269    If the new call is set up, we issue a hangup.
21270    In this scenario, we are following section 5.2
21271    in the SIP CC Transfer draft. (Transfer without
21272    a GRUU)
21273 
21274    \par Transfer with consultation hold
21275    In this case, the transferor
21276    talks to the transfer target before the transfer takes place.
21277    This is implemented with SIP hold and transfer.
21278    Note: The invite From: string could indicate a transfer.
21279    (Section 6. Transfer with consultation hold)
21280    The transferor places the transferee on hold, starts a call
21281    with the transfer target to alert them to the impending
21282    transfer, terminates the connection with the target, then
21283    proceeds with the transfer (as in Blind transfer above)
21284 
21285    \par Attended transfer
21286    The transferor places the transferee
21287    on hold, calls the transfer target to alert them,
21288    places the target on hold, then proceeds with the transfer
21289    using a Replaces header field in the Refer-to header. This
21290    will force the transfee to send an Invite to the target,
21291    with a replaces header that instructs the target to
21292    hangup the call between the transferor and the target.
21293    In this case, the Refer/to: uses the AOR address. (The same
21294    URI that the transferee used to establish the session with
21295    the transfer target (To: ). The Require: replaces header should
21296    be in the INVITE to avoid the wrong UA in a forked SIP proxy
21297    scenario to answer and have no call to replace with.
21298 
21299    The referred-by header is *NOT* required, but if we get it,
21300    can be copied into the INVITE to the transfer target to 
21301    inform the target about the transferor
21302 
21303    "Any REFER request has to be appropriately authenticated.".
21304    
21305    We can't destroy dialogs, since we want the call to continue.
21306    
21307    */
21308 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock)
21309 {
21310    struct sip_dual current;   /* Chan1: Call between asterisk and transferer */
21311                /* Chan2: Call between asterisk and transferee */
21312 
21313    int res = 0;
21314    current.req.data = NULL;
21315 
21316    if (req->debug)
21317       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");
21318 
21319    if (!p->owner) {
21320       /* This is a REFER outside of an existing SIP dialog */
21321       /* We can't handle that, so decline it */
21322       ast_debug(3, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
21323       transmit_response(p, "603 Declined (No dialog)", req);
21324       if (!req->ignore) {
21325          append_history(p, "Xfer", "Refer failed. Outside of dialog.");
21326          sip_alreadygone(p);
21327          pvt_set_needdestroy(p, "outside of dialog");
21328       }
21329       return 0;
21330    }
21331 
21332 
21333    /* Check if transfer is allowed from this device */
21334    if (p->allowtransfer == TRANSFER_CLOSED ) {
21335       /* Transfer not allowed, decline */
21336       transmit_response(p, "603 Declined (policy)", req);
21337       append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
21338       /* Do not destroy SIP session */
21339       return 0;
21340    }
21341 
21342    if (!req->ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
21343       /* Already have a pending REFER */
21344       transmit_response(p, "491 Request pending", req);
21345       append_history(p, "Xfer", "Refer failed. Request pending.");
21346       return 0;
21347    }
21348 
21349    /* Allocate memory for call transfer data */
21350    if (!p->refer && !sip_refer_allocate(p)) {
21351       transmit_response(p, "500 Internal Server Error", req);
21352       append_history(p, "Xfer", "Refer failed. Memory allocation error.");
21353       return -3;
21354    }
21355 
21356    res = get_refer_info(p, req); /* Extract headers */
21357 
21358    p->refer->status = REFER_SENT;
21359 
21360    if (res != 0) {
21361       switch (res) {
21362       case -2: /* Syntax error */
21363          transmit_response(p, "400 Bad Request (Refer-to missing)", req);
21364          append_history(p, "Xfer", "Refer failed. Refer-to missing.");
21365          if (req->debug)
21366             ast_debug(1, "SIP transfer to black hole can't be handled (no refer-to: )\n");
21367          break;
21368       case -3:
21369          transmit_response(p, "603 Declined (Non sip: uri)", req);
21370          append_history(p, "Xfer", "Refer failed. Non SIP uri");
21371          if (req->debug)
21372             ast_debug(1, "SIP transfer to non-SIP uri denied\n");
21373          break;
21374       default:
21375          /* Refer-to extension not found, fake a failed transfer */
21376          transmit_response(p, "202 Accepted", req);
21377          append_history(p, "Xfer", "Refer failed. Bad extension.");
21378          transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
21379          ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
21380          if (req->debug)
21381             ast_debug(1, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
21382          break;
21383       } 
21384       return 0;
21385    }
21386    if (ast_strlen_zero(p->context))
21387       ast_string_field_set(p, context, sip_cfg.default_context);
21388 
21389    /* If we do not support SIP domains, all transfers are local */
21390    if (sip_cfg.allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
21391       p->refer->localtransfer = 1;
21392       if (sipdebug)
21393          ast_debug(3, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
21394    } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
21395       /* This PBX doesn't bother with SIP domains or domain is local, so this transfer is local */
21396       p->refer->localtransfer = 1;
21397    } else if (sipdebug)
21398          ast_debug(3, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
21399 
21400    /* Is this a repeat of a current request? Ignore it */
21401    /* Don't know what else to do right now. */
21402    if (req->ignore) 
21403       return res;
21404 
21405    /* If this is a blind transfer, we have the following
21406    channels to work with:
21407    - chan1, chan2: The current call between transferer and transferee (2 channels)
21408    - target_channel: A new call from the transferee to the target (1 channel)
21409    We need to stay tuned to what happens in order to be able
21410    to bring back the call to the transferer */
21411 
21412    /* If this is a attended transfer, we should have all call legs within reach:
21413    - chan1, chan2: The call between the transferer and transferee (2 channels)
21414    - target_channel, targetcall_pvt: The call between the transferer and the target (2 channels)
21415    We want to bridge chan2 with targetcall_pvt!
21416    
21417    The replaces call id in the refer message points
21418    to the call leg between Asterisk and the transferer.
21419    So we need to connect the target and the transferee channel
21420    and hangup the two other channels silently 
21421    
21422    If the target is non-local, the call ID could be on a remote
21423    machine and we need to send an INVITE with replaces to the
21424    target. We basically handle this as a blind transfer
21425    and let the sip_call function catch that we need replaces
21426    header in the INVITE.
21427    */
21428 
21429 
21430    /* Get the transferer's channel */
21431    current.chan1 = p->owner;
21432 
21433    /* Find the other part of the bridge (2) - transferee */
21434    current.chan2 = ast_bridged_channel(current.chan1);
21435    
21436    if (sipdebug)
21437       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>");
21438 
21439    if (!current.chan2 && !p->refer->attendedtransfer) {
21440       /* No bridged channel, propably IVR or echo or similar... */
21441       /* Guess we should masquerade or something here */
21442       /* Until we figure it out, refuse transfer of such calls */
21443       if (sipdebug)
21444          ast_debug(3, "Refused SIP transfer on non-bridged channel.\n");
21445       p->refer->status = REFER_FAILED;
21446       append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
21447       transmit_response(p, "603 Declined", req);
21448       return -1;
21449    }
21450 
21451    if (current.chan2) {
21452       if (sipdebug)
21453          ast_debug(4, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);
21454 
21455       ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
21456    }
21457 
21458    ast_set_flag(&p->flags[0], SIP_GOTREFER);
21459 
21460    /* From here on failures will be indicated with NOTIFY requests */
21461    transmit_response(p, "202 Accepted", req);
21462 
21463    /* Attended transfer: Find all call legs and bridge transferee with target*/
21464    if (p->refer->attendedtransfer) {
21465       if ((res = local_attended_transfer(p, &current, req, seqno)))
21466          return res; /* We're done with the transfer */
21467       /* Fall through for remote transfers that we did not find locally */
21468       if (sipdebug)
21469          ast_debug(4, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
21470       /* Fallthrough if we can't find the call leg internally */
21471    }
21472 
21473 
21474    /* Parking a call */
21475    if (p->refer->localtransfer && !strcmp(p->refer->refer_to, ast_parking_ext())) {
21476       /* Must release c's lock now, because it will not longer be accessible after the transfer! */
21477       *nounlock = 1;
21478       ast_channel_unlock(current.chan1);
21479       copy_request(&current.req, req);
21480       ast_clear_flag(&p->flags[0], SIP_GOTREFER);
21481       p->refer->status = REFER_200OK;
21482       append_history(p, "Xfer", "REFER to call parking.");
21483       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",
21484          current.chan1->name,
21485          current.chan1->uniqueid,
21486          p->callid,
21487          current.chan2->name,
21488          current.chan2->uniqueid,
21489          p->refer->refer_to);
21490       if (sipdebug)
21491          ast_debug(4, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
21492       if ((res = sip_park(current.chan2, current.chan1, req, seqno))) {
21493          transmit_notify_with_sipfrag(p, seqno, "500 Internal Server Error", TRUE);
21494       }
21495       return res;
21496    } 
21497 
21498    /* Blind transfers and remote attended xfers */
21499    if (current.chan1 && current.chan2) {
21500       ast_debug(3, "chan1->name: %s\n", current.chan1->name);
21501       pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
21502    }
21503    if (current.chan2) {
21504       pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
21505       pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", p->refer->refer_to_domain);
21506       pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
21507       /* One for the new channel */
21508       pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
21509       /* Attended transfer to remote host, prepare headers for the INVITE */
21510       if (p->refer->referred_by) 
21511          pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", p->refer->referred_by);
21512    }
21513    /* Generate a Replaces string to be used in the INVITE during attended transfer */
21514    if (!ast_strlen_zero(p->refer->replaces_callid)) {
21515       char tempheader[SIPBUFSIZE];
21516       snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid, 
21517             p->refer->replaces_callid_totag ? ";to-tag=" : "", 
21518             p->refer->replaces_callid_totag, 
21519             p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
21520             p->refer->replaces_callid_fromtag);
21521       if (current.chan2)
21522          pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
21523    }
21524    /* Must release lock now, because it will not longer
21525       be accessible after the transfer! */
21526    *nounlock = 1;
21527    ast_channel_unlock(current.chan1);
21528 
21529    /* Connect the call */
21530 
21531    /* FAKE ringing if not attended transfer */
21532    if (!p->refer->attendedtransfer)
21533       transmit_notify_with_sipfrag(p, seqno, "183 Ringing", FALSE); 
21534 
21535    /* For blind transfer, this will lead to a new call */
21536    /* For attended transfer to remote host, this will lead to
21537       a new SIP call with a replaces header, if the dial plan allows it 
21538    */
21539    if (!current.chan2) {
21540       /* We have no bridge, so we're talking with Asterisk somehow */
21541       /* We need to masquerade this call */
21542       /* What to do to fix this situation:
21543          * Set up the new call in a new channel 
21544          * Let the new channel masq into this channel
21545          Please add that code here :-)
21546       */
21547       p->refer->status = REFER_FAILED;
21548       transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
21549       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
21550       append_history(p, "Xfer", "Refer failed (only bridged calls).");
21551       return -1;
21552    }
21553    ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);   /* Delay hangup */
21554 
21555 
21556    /* For blind transfers, move the call to the new extensions. For attended transfers on multiple
21557       servers - generate an INVITE with Replaces. Either way, let the dial plan decided  */
21558    /* indicate before masquerade so the indication actually makes it to the real channel
21559       when using local channels with MOH passthru */
21560    ast_indicate(current.chan2, AST_CONTROL_UNHOLD);
21561    res = ast_async_goto(current.chan2, p->refer->refer_to_context, p->refer->refer_to, 1);
21562 
21563    if (!res) {
21564       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",
21565          current.chan1->name,
21566          current.chan1->uniqueid,
21567          p->callid,
21568          current.chan2->name,
21569          current.chan2->uniqueid,
21570          p->refer->refer_to, p->refer->refer_to_context);
21571       /* Success  - we have a new channel */
21572       ast_debug(3, "%s transfer succeeded. Telling transferer.\n", p->refer->attendedtransfer? "Attended" : "Blind");
21573       transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
21574       if (p->refer->localtransfer)
21575          p->refer->status = REFER_200OK;
21576       if (p->owner)
21577          p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
21578       append_history(p, "Xfer", "Refer succeeded.");
21579       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
21580       /* Do not hangup call, the other side do that when we say 200 OK */
21581       /* We could possibly implement a timer here, auto congestion */
21582       res = 0;
21583    } else {
21584       ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Don't delay hangup */
21585       ast_debug(3, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
21586       append_history(p, "Xfer", "Refer failed.");
21587       /* Failure of some kind */
21588       p->refer->status = REFER_FAILED;
21589       transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
21590       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
21591       res = -1;
21592    }
21593    return res;
21594 }
21595 
21596 /*! \brief Handle incoming CANCEL request */
21597 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
21598 {
21599       
21600    check_via(p, req);
21601    sip_alreadygone(p);
21602 
21603    /* At this point, we could have cancelled the invite at the same time
21604       as the other side sends a CANCEL. Our final reply with error code
21605       might not have been received by the other side before the CANCEL
21606       was sent, so let's just give up retransmissions and waiting for
21607       ACK on our error code. The call is hanging up any way. */
21608    if (p->invitestate == INV_TERMINATED)
21609       __sip_pretend_ack(p);
21610    else
21611       p->invitestate = INV_CANCELLED;
21612    
21613    if (p->owner && p->owner->_state == AST_STATE_UP) {
21614       /* This call is up, cancel is ignored, we need a bye */
21615       transmit_response(p, "200 OK", req);
21616       ast_debug(1, "Got CANCEL on an answered call. Ignoring... \n");
21617       return 0;
21618    }
21619 
21620    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) 
21621       update_call_counter(p, DEC_CALL_LIMIT);
21622 
21623    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
21624    if (p->owner)
21625       ast_queue_hangup(p->owner);
21626    else
21627       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21628    if (p->initreq.len > 0) {
21629       struct sip_pkt *pkt, *prev_pkt;
21630       /* If the CANCEL we are receiving is a retransmission, and we already have scheduled
21631        * a reliable 487, then we don't want to schedule another one on top of the previous
21632        * one.
21633        *
21634        * As odd as this may sound, we can't rely on the previously-transmitted "reliable" 
21635        * response in this situation. What if we've sent all of our reliable responses 
21636        * already and now all of a sudden, we get this second CANCEL?
21637        *
21638        * The only way to do this correctly is to cancel our previously-scheduled reliably-
21639        * transmitted response and send a new one in its place.
21640        */
21641       for (pkt = p->packets, prev_pkt = NULL; pkt; prev_pkt = pkt, pkt = pkt->next) {
21642          if (pkt->seqno == p->lastinvite && pkt->response_code == 487) {
21643             AST_SCHED_DEL(sched, pkt->retransid);
21644             UNLINK(pkt, p->packets, prev_pkt);
21645             dialog_unref(pkt->owner, "unref packet->owner from dialog");
21646             if (pkt->data) {
21647                ast_free(pkt->data);
21648             }
21649             ast_free(pkt);
21650             break;
21651          }
21652       }
21653       transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
21654       transmit_response(p, "200 OK", req);
21655       return 1;
21656    } else {
21657       transmit_response(p, "481 Call Leg Does Not Exist", req);
21658       return 0;
21659    }
21660 }
21661 
21662 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen)
21663 {
21664    struct sip_pvt *p = chan->tech_pvt;
21665    char *all = "", *parse = ast_strdupa(preparse);
21666    int res = 0;
21667    AST_DECLARE_APP_ARGS(args,
21668       AST_APP_ARG(param);
21669       AST_APP_ARG(type);
21670       AST_APP_ARG(field);
21671    );
21672    AST_STANDARD_APP_ARGS(args, parse);
21673 
21674    /* Sanity check */
21675    if (!IS_SIP_TECH(chan->tech)) {
21676       ast_log(LOG_ERROR, "Cannot call %s on a non-SIP channel\n", funcname);
21677       return 0;
21678    }
21679 
21680    memset(buf, 0, buflen);
21681 
21682    if (p == NULL) {
21683       return -1;
21684    }
21685 
21686    if (!strcasecmp(args.param, "peerip")) {
21687       ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", buflen);
21688    } else if (!strcasecmp(args.param, "recvip")) {
21689       ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", buflen);
21690    } else if (!strcasecmp(args.param, "from")) {
21691       ast_copy_string(buf, p->from, buflen);
21692    } else if (!strcasecmp(args.param, "uri")) {
21693       ast_copy_string(buf, p->uri, buflen);
21694    } else if (!strcasecmp(args.param, "useragent")) {
21695       ast_copy_string(buf, p->useragent, buflen);
21696    } else if (!strcasecmp(args.param, "peername")) {
21697       ast_copy_string(buf, p->peername, buflen);
21698    } else if (!strcasecmp(args.param, "t38passthrough")) {
21699       ast_copy_string(buf, (p->t38.state == T38_DISABLED) ? "0" : "1", buflen);
21700    } else if (!strcasecmp(args.param, "rtpdest")) {
21701       struct sockaddr_in sin;
21702       struct ast_rtp *stream = NULL;
21703 
21704       if (ast_strlen_zero(args.type))
21705          args.type = "audio";
21706 
21707       if (!strcasecmp(args.type, "audio")) {
21708          stream = p->rtp;
21709       } else if (!strcasecmp(args.type, "video")) {
21710          stream = p->vrtp;
21711       } else if (!strcasecmp(args.type, "text")) {
21712          stream = p->trtp;
21713       } else {
21714          return -1;
21715       }
21716 
21717       if (!stream) {
21718          return -1;
21719       }
21720 
21721       ast_rtp_get_peer(stream, &sin);
21722       snprintf(buf, buflen, "%s:%d", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
21723    } else if (!strcasecmp(args.param, "rtpqos")) {
21724       struct ast_rtp_quality qos;
21725       struct ast_rtp *rtp = p->rtp;
21726       
21727       memset(&qos, 0, sizeof(qos));
21728 
21729       if (ast_strlen_zero(args.type))
21730          args.type = "audio";
21731       if (ast_strlen_zero(args.field))
21732          args.field = "all";
21733       
21734       if (!strcasecmp(args.type, "AUDIO")) {
21735          all = ast_rtp_get_quality(rtp = p->rtp, &qos, RTPQOS_SUMMARY);
21736       } else if (!strcasecmp(args.type, "VIDEO")) {
21737          all = ast_rtp_get_quality(rtp = p->vrtp, &qos, RTPQOS_SUMMARY);
21738       } else if (!strcasecmp(args.type, "TEXT")) {
21739          all = ast_rtp_get_quality(rtp = p->trtp, &qos, RTPQOS_SUMMARY);
21740       } else {
21741          return -1;
21742       }
21743       
21744       if (!strcasecmp(args.field, "local_ssrc"))
21745          snprintf(buf, buflen, "%u", qos.local_ssrc);
21746       else if (!strcasecmp(args.field, "local_lostpackets"))
21747          snprintf(buf, buflen, "%u", qos.local_lostpackets);
21748       else if (!strcasecmp(args.field, "local_jitter"))
21749          snprintf(buf, buflen, "%.0f", qos.local_jitter * 1000.0);
21750       else if (!strcasecmp(args.field, "local_count"))
21751          snprintf(buf, buflen, "%u", qos.local_count);
21752       else if (!strcasecmp(args.field, "remote_ssrc"))
21753          snprintf(buf, buflen, "%u", qos.remote_ssrc);
21754       else if (!strcasecmp(args.field, "remote_lostpackets"))
21755          snprintf(buf, buflen, "%u", qos.remote_lostpackets);
21756       else if (!strcasecmp(args.field, "remote_jitter"))
21757          snprintf(buf, buflen, "%.0f", qos.remote_jitter * 1000.0);
21758       else if (!strcasecmp(args.field, "remote_count"))
21759          snprintf(buf, buflen, "%u", qos.remote_count);
21760       else if (!strcasecmp(args.field, "rtt"))
21761          snprintf(buf, buflen, "%.0f", qos.rtt * 1000.0);
21762       else if (!strcasecmp(args.field, "all"))
21763          ast_copy_string(buf, all, buflen);
21764       else if (!ast_rtp_get_qos(rtp, args.field, buf, buflen))
21765           ;
21766       else {
21767          ast_log(LOG_WARNING, "Unrecognized argument '%s' to %s\n", preparse, funcname);
21768          return -1;
21769       }
21770    } else {
21771       res = -1;
21772    }
21773    return res;
21774 }
21775 
21776 /*! \brief Handle incoming BYE request */
21777 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
21778 {
21779    struct ast_channel *c=NULL;
21780    int res;
21781    struct ast_channel *bridged_to;
21782    
21783    /* If we have an INCOMING invite that we haven't answered, terminate that transaction */
21784    if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !req->ignore) {
21785       transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
21786    }
21787 
21788    __sip_pretend_ack(p);
21789 
21790    p->invitestate = INV_TERMINATED;
21791 
21792    copy_request(&p->initreq, req);
21793    if (sipdebug)
21794       ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
21795    check_via(p, req);
21796    sip_alreadygone(p);
21797 
21798    /* Get RTCP quality before end of call */
21799    if (p->do_history || p->owner) {
21800       struct ast_channel *bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
21801       char *videoqos, *textqos;
21802 
21803       /* We need to get the lock on bridge because ast_rtp_set_vars will attempt
21804        * to lock the bridge. This may get hairy...
21805        */
21806       while (bridge && ast_channel_trylock(bridge)) {
21807          ast_channel_unlock(p->owner);
21808          do {
21809             /* Can't use DEADLOCK_AVOIDANCE since p is an ao2 object */
21810             sip_pvt_unlock(p);
21811             usleep(1);
21812             sip_pvt_lock(p);
21813          } while (p->owner && ast_channel_trylock(p->owner));
21814          bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
21815       }
21816 
21817       if (p->rtp) {  
21818          if (p->do_history) {
21819             char *audioqos,
21820                  *audioqos_jitter,
21821                  *audioqos_loss,
21822                  *audioqos_rtt;
21823 
21824             audioqos        = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_SUMMARY);
21825             audioqos_jitter = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_JITTER);
21826             audioqos_loss   = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_LOSS);
21827             audioqos_rtt    = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_RTT);
21828 
21829             append_history(p, "RTCPaudio", "Quality:%s", audioqos);
21830             append_history(p, "RTCPaudioJitter", "Quality:%s", audioqos_jitter);
21831             append_history(p, "RTCPaudioLoss", "Quality:%s", audioqos_loss);
21832             append_history(p, "RTCPaudioRTT", "Quality:%s", audioqos_rtt);
21833          }
21834          
21835          if (p->owner) {
21836             ast_rtp_set_vars(p->owner, p->rtp);
21837          }
21838       }
21839 
21840       if (bridge) {
21841          struct sip_pvt *q = bridge->tech_pvt;
21842 
21843          if (IS_SIP_TECH(bridge->tech) && q && q->rtp)
21844             ast_rtp_set_vars(bridge, q->rtp);
21845          ast_channel_unlock(bridge);
21846       }
21847 
21848       if (p->vrtp) {
21849          videoqos = ast_rtp_get_quality(p->vrtp, NULL, RTPQOS_SUMMARY);
21850          if (p->do_history)
21851             append_history(p, "RTCPvideo", "Quality:%s", videoqos);
21852          if (p->owner)
21853             pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", videoqos);
21854       }
21855 
21856       if (p->trtp) {
21857          textqos = ast_rtp_get_quality(p->trtp, NULL, RTPQOS_SUMMARY);
21858          if (p->do_history)
21859             append_history(p, "RTCPtext", "Quality:%s", textqos);
21860          if (p->owner)
21861             pbx_builtin_setvar_helper(p->owner, "RTPTEXTQOS", textqos);
21862       }
21863    }
21864 
21865    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
21866    stop_session_timer(p); /* Stop Session-Timer */
21867 
21868    if (!ast_strlen_zero(get_header(req, "Also"))) {
21869       ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method.  Ask vendor to support REFER instead\n",
21870          ast_inet_ntoa(p->recv.sin_addr));
21871       if (ast_strlen_zero(p->context))
21872          ast_string_field_set(p, context, sip_cfg.default_context);
21873       res = get_also_info(p, req);
21874       if (!res) {
21875          c = p->owner;
21876          if (c) {
21877             bridged_to = ast_bridged_channel(c);
21878             if (bridged_to) {
21879                /* Don't actually hangup here... */
21880                ast_queue_control(c, AST_CONTROL_UNHOLD);
21881                ast_async_goto(bridged_to, p->context, p->refer->refer_to, 1);
21882             } else
21883                ast_queue_hangup(p->owner);
21884          }
21885       } else {
21886          ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_inet_ntoa(p->recv.sin_addr));
21887          if (p->owner)
21888             ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
21889       }
21890    } else if (p->owner) {
21891       ast_queue_hangup(p->owner);
21892       ast_debug(3, "Received bye, issuing owner hangup\n");
21893    } else {
21894       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21895       ast_debug(3, "Received bye, no owner, selfdestruct soon.\n");
21896    }
21897    ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21898    transmit_response(p, "200 OK", req);
21899 
21900    return 1;
21901 }
21902 
21903 /*! \brief Handle incoming MESSAGE request */
21904 static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
21905 {
21906    if (!req->ignore) {
21907       if (req->debug)
21908          ast_verbose("Receiving message!\n");
21909       receive_message(p, req);
21910    } else
21911       transmit_response(p, "202 Accepted", req);
21912    return 1;
21913 }
21914 
21915 static void add_peer_mwi_subs(struct sip_peer *peer)
21916 {
21917    struct sip_mailbox *mailbox;
21918 
21919    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
21920       mailbox->event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, peer,
21921          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
21922          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
21923          AST_EVENT_IE_END);
21924    }
21925 }
21926 
21927 /*! \brief  Handle incoming SUBSCRIBE request */
21928 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
21929 {
21930    int gotdest = 0;
21931    int res = 0;
21932    int firststate = AST_EXTENSION_REMOVED;
21933    struct sip_peer *authpeer = NULL;
21934    const char *eventheader = get_header(req, "Event");   /* Get Event package name */
21935    int resubscribe = (p->subscribed != NONE) && !req->ignore;
21936    char *temp, *event;
21937 
21938    if (p->initreq.headers) {  
21939       /* We already have a dialog */
21940       if (p->initreq.method != SIP_SUBSCRIBE) {
21941          /* This is a SUBSCRIBE within another SIP dialog, which we do not support */
21942          /* For transfers, this could happen, but since we haven't seen it happening, let us just refuse this */
21943          transmit_response(p, "403 Forbidden (within dialog)", req);
21944          /* Do not destroy session, since we will break the call if we do */
21945          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);
21946          return 0;
21947       } else if (req->debug) {
21948          if (resubscribe)
21949             ast_debug(1, "Got a re-subscribe on existing subscription %s\n", p->callid);
21950          else
21951             ast_debug(1, "Got a new subscription %s (possibly with auth) or retransmission\n", p->callid);
21952       }
21953    }
21954 
21955    /* Check if we have a global disallow setting on subscriptions. 
21956       if so, we don't have to check peer settings after auth, which saves a lot of processing
21957    */
21958    if (!sip_cfg.allowsubscribe) {
21959       transmit_response(p, "403 Forbidden (policy)", req);
21960       pvt_set_needdestroy(p, "forbidden");
21961       return 0;
21962    }
21963 
21964    if (!req->ignore && !resubscribe) { /* Set up dialog, new subscription */
21965       const char *to = get_header(req, "To");
21966       char totag[128];
21967 
21968       /* Check to see if a tag was provided, if so this is actually a resubscription of a dialog we no longer know about */
21969       if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
21970          if (req->debug)
21971             ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
21972          transmit_response(p, "481 Subscription does not exist", req);
21973          pvt_set_needdestroy(p, "subscription does not exist");
21974          return 0;
21975       }
21976 
21977       /* Use this as the basis */
21978       if (req->debug)
21979          ast_verbose("Creating new subscription\n");
21980 
21981       copy_request(&p->initreq, req);
21982       if (sipdebug)
21983          ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
21984       check_via(p, req);
21985       build_route(p, req, 0);
21986    } else if (req->debug && req->ignore)
21987       ast_verbose("Ignoring this SUBSCRIBE request\n");
21988 
21989    /* Find parameters to Event: header value and remove them for now */
21990    if (ast_strlen_zero(eventheader)) {
21991       transmit_response(p, "489 Bad Event", req);
21992       ast_debug(2, "Received SIP subscribe for unknown event package: <none>\n");
21993       pvt_set_needdestroy(p, "unknown event package in subscribe");
21994       return 0;
21995    }
21996 
21997    if ( (strchr(eventheader, ';'))) {
21998       event = ast_strdupa(eventheader);   /* Since eventheader is a const, we can't change it */
21999       temp = strchr(event, ';');       
22000       *temp = '\0';           /* Remove any options for now */
22001                      /* We might need to use them later :-) */
22002    } else
22003       event = (char *) eventheader;    /* XXX is this legal ? */
22004 
22005    /* Handle authentication if we're new and not a retransmission. We can't just
22006     * use if !req->ignore, because then we'll end up sending
22007     * a 200 OK if someone retransmits without sending auth */
22008    if (p->subscribed == NONE || resubscribe) {
22009       res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, sin, &authpeer);
22010 
22011       /* if an authentication response was sent, we are done here */
22012       if (res == AUTH_CHALLENGE_SENT)  /* authpeer = NULL here */
22013          return 0;
22014       if (res < 0) {
22015          if (res == AUTH_FAKE_AUTH) {
22016             ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
22017             transmit_fake_auth_response(p, SIP_SUBSCRIBE, req, XMIT_UNRELIABLE);
22018          } else {
22019             ast_log(LOG_NOTICE, "Failed to authenticate device %s for SUBSCRIBE\n", get_header(req, "From"));
22020             transmit_response_reliable(p, "403 Forbidden", req);
22021          }
22022 
22023          pvt_set_needdestroy(p, "authentication failed");
22024          return 0;
22025       }
22026    }
22027 
22028    /* At this point, authpeer cannot be NULL. Remember we hold a reference,
22029     * so we must release it when done.
22030     * XXX must remove all the checks for authpeer == NULL.
22031     */
22032 
22033    /* Check if this device  is allowed to subscribe at all */
22034    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
22035       transmit_response(p, "403 Forbidden (policy)", req);
22036       pvt_set_needdestroy(p, "subscription not allowed");
22037       if (authpeer)
22038          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 1)");
22039       return 0;
22040    }
22041 
22042    if (strcmp(event, "message-summary")) {
22043       /* Get destination right away */
22044       gotdest = get_destination(p, NULL);
22045    }
22046 
22047    /* Get full contact header - this needs to be used as a request URI in NOTIFY's */
22048    parse_ok_contact(p, req);
22049 
22050    build_contact(p);
22051    if (gotdest) {
22052       transmit_response(p, "404 Not Found", req);
22053       pvt_set_needdestroy(p, "subscription target not found");
22054       if (authpeer)
22055          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
22056       return 0;
22057    }
22058 
22059    /* Initialize tag for new subscriptions */   
22060    if (ast_strlen_zero(p->tag))
22061       make_our_tag(p->tag, sizeof(p->tag));
22062 
22063    if (!strcmp(event, "presence") || !strcmp(event, "dialog")) { /* Presence, RFC 3842 */
22064       unsigned int pidf_xml;
22065       const char *accept;
22066       int start = 0;
22067       enum subscriptiontype subscribed = NONE;
22068       const char *unknown_acceptheader = NULL;
22069 
22070       if (authpeer)  /* We do not need the authpeer any more */
22071          authpeer = unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
22072 
22073       /* Header from Xten Eye-beam Accept: multipart/related, application/rlmi+xml, application/pidf+xml, application/xpidf+xml */
22074 
22075       accept = __get_header(req, "Accept", &start);
22076       while ((subscribed == NONE) && !ast_strlen_zero(accept)) {
22077          pidf_xml = strstr(accept, "application/pidf+xml") ? 1 : 0;
22078 
22079          /* Older versions of Polycom firmware will claim pidf+xml, but really
22080           * they only support xpidf+xml. */
22081          if (pidf_xml && strstr(p->useragent, "Polycom")) {
22082             subscribed = XPIDF_XML;
22083          } else if (pidf_xml) {
22084             subscribed = PIDF_XML;         /* RFC 3863 format */
22085          } else if (strstr(accept, "application/dialog-info+xml")) {
22086             subscribed = DIALOG_INFO_XML;
22087             /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
22088          } else if (strstr(accept, "application/cpim-pidf+xml")) {
22089             subscribed = CPIM_PIDF_XML;    /* RFC 3863 format */
22090          } else if (strstr(accept, "application/xpidf+xml")) {
22091             subscribed = XPIDF_XML;        /* Early pre-RFC 3863 format with MSN additions (Microsoft Messenger) */
22092          } else {
22093             unknown_acceptheader = accept;
22094          }
22095          /* check to see if there is another Accept header present */
22096          accept = __get_header(req, "Accept", &start);
22097       }
22098 
22099       if (!start) {
22100          if (p->subscribed == NONE) { /* if the subscribed field is not already set, and there is no accept header... */
22101             transmit_response(p, "489 Bad Event", req);
22102             ast_log(LOG_WARNING,"SUBSCRIBE failure: no Accept header: pvt: "
22103                "stateid: %d, laststate: %d, dialogver: %d, subscribecont: "
22104                "'%s', subscribeuri: '%s'\n",
22105                p->stateid,
22106                p->laststate,
22107                p->dialogver,
22108                p->subscribecontext,
22109                p->subscribeuri);
22110             pvt_set_needdestroy(p, "no Accept header");
22111             return 0;
22112          }
22113          /* if p->subscribed is non-zero, then accept is not obligatory; according to rfc 3265 section 3.1.3, at least.
22114             so, we'll just let it ride, keeping the value from a previous subscription, and not abort the subscription */
22115       } else if (subscribed == NONE) {
22116          /* Can't find a format for events that we know about */
22117          char mybuf[200];
22118          if (!ast_strlen_zero(unknown_acceptheader)) {
22119             snprintf(mybuf, sizeof(mybuf), "489 Bad Event (format %s)", unknown_acceptheader);
22120          } else {
22121             snprintf(mybuf, sizeof(mybuf), "489 Bad Event");
22122          }
22123          transmit_response(p, mybuf, req);
22124          ast_log(LOG_WARNING,"SUBSCRIBE failure: unrecognized format:"
22125             "'%s' pvt: subscribed: %d, stateid: %d, laststate: %d,"
22126             "dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
22127             unknown_acceptheader,
22128             (int)p->subscribed,
22129             p->stateid,
22130             p->laststate,
22131             p->dialogver,
22132             p->subscribecontext,
22133             p->subscribeuri);
22134          pvt_set_needdestroy(p, "unrecognized format");
22135          return 0;
22136       } else {
22137          p->subscribed = subscribed;
22138       }
22139    } else if (!strcmp(event, "message-summary")) {
22140       int start = 0;
22141       int found_supported = 0;
22142       const char *acceptheader;
22143 
22144       acceptheader = __get_header(req, "Accept", &start);
22145       while (!found_supported && !ast_strlen_zero(acceptheader)) {
22146          found_supported = strcmp(acceptheader, "application/simple-message-summary") ? 0 : 1;
22147          if (!found_supported && (option_debug > 2)) {
22148             ast_log(LOG_DEBUG, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
22149          }
22150          acceptheader = __get_header(req, "Accept", &start);
22151       }
22152       if (start && !found_supported) {
22153          /* Format requested that we do not support */
22154          transmit_response(p, "406 Not Acceptable", req);
22155          ast_debug(2, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
22156          pvt_set_needdestroy(p, "unknown format");
22157          if (authpeer)
22158             unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 3)");
22159          return 0;
22160       }
22161 
22162       /* Looks like they actually want a mailbox status 
22163         This version of Asterisk supports mailbox subscriptions
22164         The subscribed URI needs to exist in the dial plan
22165         In most devices, this is configurable to the voicemailmain extension you use
22166       */
22167       if (!authpeer || AST_LIST_EMPTY(&authpeer->mailboxes)) {
22168          transmit_response(p, "404 Not found (no mailbox)", req);
22169          pvt_set_needdestroy(p, "received 404 response");
22170          ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", authpeer->name);
22171          if (authpeer)
22172             unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 4)");
22173          return 0;
22174       }
22175 
22176       p->subscribed = MWI_NOTIFICATION;
22177       if (ast_test_flag(&authpeer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY)) {
22178          add_peer_mwi_subs(authpeer);
22179       }
22180       if (authpeer->mwipvt && authpeer->mwipvt != p) {   /* Destroy old PVT if this is a new one */
22181          /* We only allow one subscription per peer */
22182          dialog_unlink_all(authpeer->mwipvt, TRUE, TRUE);
22183          authpeer->mwipvt = dialog_unref(authpeer->mwipvt, "unref dialog authpeer->mwipvt");
22184          /* sip_destroy(authpeer->mwipvt); */
22185       }
22186       if (authpeer->mwipvt)
22187          dialog_unref(authpeer->mwipvt, "Unref previously stored mwipvt dialog pointer");
22188       authpeer->mwipvt = dialog_ref(p, "setting peers' mwipvt to p");      /* Link from peer to pvt UH- should this be dialog_ref()? */
22189       if (p->relatedpeer)
22190          unref_peer(p->relatedpeer, "Unref previously stored relatedpeer ptr");
22191       p->relatedpeer = ref_peer(authpeer, "setting dialog's relatedpeer pointer");  /* already refcounted...Link from pvt to peer UH- should this be dialog_ref()? */
22192       /* Do not release authpeer here */
22193    } else { /* At this point, Asterisk does not understand the specified event */
22194       transmit_response(p, "489 Bad Event", req);
22195       ast_debug(2, "Received SIP subscribe for unknown event package: %s\n", event);
22196       pvt_set_needdestroy(p, "unknown event package");
22197       if (authpeer)
22198          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 5)");
22199       return 0;
22200    }
22201 
22202    /* At this point, if we have an authpeer we should unref it. */
22203    if (authpeer) {
22204       authpeer = unref_peer(authpeer, "unref pointer into (*authpeer)");
22205    }
22206 
22207    /* Add subscription for extension state from the PBX core */
22208    if (p->subscribed != MWI_NOTIFICATION && !resubscribe) {
22209       if (p->stateid > -1) {
22210          ast_extension_state_del(p->stateid, cb_extensionstate);
22211          /* we need to dec the refcount, now that the extensionstate is removed */
22212          dialog_unref(p, "the extensionstate containing this dialog ptr was deleted");
22213       }
22214       p->stateid = ast_extension_state_add(p->context, p->exten, cb_extensionstate, dialog_ref(p,"copying dialog ptr into extension state struct"));
22215    }
22216 
22217    if (!req->ignore && p)
22218       p->lastinvite = seqno;
22219    if (p && !p->needdestroy) {
22220       p->expiry = atoi(get_header(req, "Expires"));
22221 
22222       /* check if the requested expiry-time is within the approved limits from sip.conf */
22223       if (p->expiry > max_expiry)
22224          p->expiry = max_expiry;
22225       if (p->expiry < min_expiry && p->expiry > 0)
22226          p->expiry = min_expiry;
22227 
22228       if (sipdebug) {
22229          if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
22230             ast_debug(2, "Adding subscription for mailbox notification - peer %s\n", p->relatedpeer->name);
22231          else
22232             ast_debug(2, "Adding subscription for extension %s context %s for peer %s\n", p->exten, p->context, p->username);
22233       }
22234       if (p->autokillid > -1 && sip_cancel_destroy(p))   /* Remove subscription expiry for renewals */
22235          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
22236       if (p->expiry > 0)
22237          sip_scheddestroy(p, (p->expiry + 10) * 1000);   /* Set timer for destruction of call at expiration */
22238 
22239       if (p->subscribed == MWI_NOTIFICATION) {
22240          ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
22241          transmit_response(p, "200 OK", req);
22242          if (p->relatedpeer) {   /* Send first notification */
22243             ao2_lock(p->relatedpeer); /* was WRLOCK */
22244             sip_send_mwi_to_peer(p->relatedpeer, NULL, 0);
22245             ao2_unlock(p->relatedpeer);
22246          }
22247       } else {
22248 
22249          if ((firststate = ast_extension_state(NULL, p->context, p->exten)) < 0) {
22250 
22251             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));
22252             transmit_response(p, "404 Not found", req);
22253             pvt_set_needdestroy(p, "no extension for SUBSCRIBE");
22254             return 0;
22255          }
22256          ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
22257          transmit_response(p, "200 OK", req);
22258          transmit_state_notify(p, firststate, 1, FALSE); /* Send first notification */
22259          append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
22260          /* hide the 'complete' exten/context in the refer_to field for later display */
22261          ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
22262          /* Deleted the slow iteration of all sip dialogs to find old subscribes from this peer for exten@context */
22263 
22264       }
22265       if (!p->expiry) {
22266          pvt_set_needdestroy(p, "forcing expiration");
22267       }
22268    }
22269    return 1;
22270 }
22271 
22272 /*! \brief Handle incoming REGISTER request */
22273 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e)
22274 {
22275    enum check_auth_result res;
22276 
22277    /* If this is not the intial request, and the initial request isn't
22278     * a register, something screwy happened, so bail */
22279    if (p->initreq.headers && p->initreq.method != SIP_REGISTER) {
22280       ast_log(LOG_WARNING, "Ignoring spurious REGISTER with Call-ID: %s\n", p->callid);
22281       return -1;
22282    }
22283 
22284    /* Use this as the basis */
22285    copy_request(&p->initreq, req);
22286    if (sipdebug)
22287       ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
22288    check_via(p, req);
22289    if ((res = register_verify(p, sin, req, e)) < 0) {
22290       const char *reason;
22291 
22292       switch (res) {
22293       case AUTH_SECRET_FAILED:
22294          reason = "Wrong password";
22295          break;
22296       case AUTH_USERNAME_MISMATCH:
22297          reason = "Username/auth name mismatch";
22298          break;
22299       case AUTH_NOT_FOUND:
22300          reason = "No matching peer found";
22301          break;
22302       case AUTH_UNKNOWN_DOMAIN:
22303          reason = "Not a local domain";
22304          break;
22305       case AUTH_PEER_NOT_DYNAMIC:
22306          reason = "Peer is not supposed to register";
22307          break;
22308       case AUTH_ACL_FAILED:
22309          reason = "Device does not match ACL";
22310          break;
22311       case AUTH_BAD_TRANSPORT:
22312          reason = "Device not configured to use this transport type";
22313          break;
22314       default:
22315          reason = "Unknown failure";
22316          break;
22317       }
22318       ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
22319          get_header(req, "To"), ast_inet_ntoa(sin->sin_addr),
22320          reason);
22321       append_history(p, "RegRequest", "Failed : Account %s : %s", get_header(req, "To"), reason);
22322    } else {
22323       req->authenticated = 1;
22324       append_history(p, "RegRequest", "Succeeded : Account %s", get_header(req, "To"));
22325    }
22326 
22327    if (res < 1) {
22328       /* Destroy the session, but keep us around for just a bit in case they don't
22329          get our 200 OK */
22330       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22331    }
22332    return res;
22333 }
22334 
22335 /*!
22336  * \brief Handle incoming SIP requests (methods)
22337  * \note
22338  * This is where all incoming requests go first.
22339  * \note
22340  * called with p and p->owner locked
22341  */
22342 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock)
22343 {
22344    /* Called with p->lock held, as well as p->owner->lock if appropriate, keeping things
22345       relatively static */
22346    const char *cmd;
22347    const char *cseq;
22348    const char *useragent;
22349    const char *via;
22350    const char *callid;
22351    int via_pos = 0;
22352    int seqno;
22353    int len;
22354    int respid;
22355    int res = 0;
22356    int debug = sip_debug_test_pvt(p);
22357    char *e;
22358    int error = 0;
22359    int oldmethod = p->method;
22360    int acked = 0;
22361 
22362    /* RFC 3261 - 8.1.1 A valid SIP request must contain To, From, CSeq, Call-ID and Via.
22363     * 8.2.6.2 Response must have To, From, Call-ID CSeq, and Via related to the request,
22364     * so we can check to make sure these fields exist for all requests and responses */
22365    cseq = get_header(req, "Cseq");
22366    cmd = REQ_OFFSET_TO_STR(req, header[0]);
22367    /* Save the via_pos so we can check later that responses only have 1 Via header */
22368    via = __get_header(req, "Via", &via_pos);
22369    /* This must exist already because we've called find_call by now */
22370    callid = get_header(req, "Call-ID");
22371 
22372    /* Must have Cseq */
22373    if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq) || ast_strlen_zero(via)) {
22374       ast_log(LOG_ERROR, "Dropping this SIP message with Call-ID '%s', it's incomplete.\n", callid);
22375       error = 1;
22376    }
22377    if (!error && sscanf(cseq, "%30d%n", &seqno, &len) != 1) {
22378       ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
22379       error = 1;
22380    }
22381    if (error) {
22382       if (!p->initreq.headers) { /* New call */
22383          pvt_set_needdestroy(p, "no headers");
22384       }
22385       return -1;
22386    }
22387    /* Get the command XXX */
22388 
22389    cmd = REQ_OFFSET_TO_STR(req, rlPart1);
22390    e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlPart2));
22391 
22392    /* Save useragent of the client */
22393    useragent = get_header(req, "User-Agent");
22394    if (!ast_strlen_zero(useragent))
22395       ast_string_field_set(p, useragent, useragent);
22396 
22397    /* Find out SIP method for incoming request */
22398    if (req->method == SIP_RESPONSE) {  /* Response to our request */
22399       /* ignore means "don't do anything with it" but still have to 
22400        * respond appropriately.
22401        * But in this case this is a response already, so we really
22402        * have nothing to do with this message, and even setting the
22403        * ignore flag is pointless.
22404        */
22405       if (ast_strlen_zero(e)) {
22406          return 0;
22407       }
22408       if (sscanf(e, "%30d %n", &respid, &len) != 1) {
22409          ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
22410          return 0;
22411       }
22412       if (respid <= 0) {
22413          ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
22414          return 0;
22415       }
22416       /* RFC 3261 - 8.1.3.3 If more than one Via header field value is present in a reponse
22417        * the UAC SHOULD discard the message. This is not perfect, as it will not catch multiple
22418        * headers joined with a comma. Fixing that would pretty much involve writing a new parser */
22419       if (!ast_strlen_zero(__get_header(req, "via", &via_pos))) {
22420          ast_log(LOG_WARNING, "Misrouted SIP response '%s' with Call-ID '%s', too many vias\n", e, callid);
22421          return 0;
22422       }
22423       if (p->ocseq && (p->ocseq < seqno)) {
22424          if (option_debug)
22425             ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
22426          return -1;
22427       } else {
22428          if ((respid == 200) || ((respid >= 300) && (respid <= 399))) {
22429             extract_uri(p, req);
22430          }
22431          handle_response(p, respid, e + len, req, seqno);
22432       }
22433       return 0;
22434    }
22435 
22436    /* New SIP request coming in 
22437       (could be new request in existing SIP dialog as well...) 
22438     */         
22439    
22440    p->method = req->method;   /* Find out which SIP method they are using */
22441    ast_debug(4, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd); 
22442 
22443    if (p->icseq && (p->icseq > seqno) ) {
22444       if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
22445          ast_debug(2, "Got CANCEL or ACK on INVITE with transactions in between.\n");
22446       }  else {
22447          ast_debug(1, "Ignoring too old SIP packet packet %d (expecting >= %d)\n", seqno, p->icseq);
22448          if (req->method != SIP_ACK)
22449             transmit_response(p, "500 Server error", req);  /* We must respond according to RFC 3261 sec 12.2 */
22450          return -1;
22451       }
22452    } else if (p->icseq &&
22453          p->icseq == seqno &&
22454          req->method != SIP_ACK &&
22455          (p->method != SIP_CANCEL || p->alreadygone)) {
22456       /* ignore means "don't do anything with it" but still have to 
22457          respond appropriately.  We do this if we receive a repeat of
22458          the last sequence number  */
22459       req->ignore = 1;
22460       ast_debug(3, "Ignoring SIP message because of retransmit (%s Seqno %d, ours %d)\n", sip_methods[p->method].text, p->icseq, seqno);
22461    }
22462       
22463    if (seqno >= p->icseq)
22464       /* Next should follow monotonically (but not necessarily 
22465          incrementally -- thanks again to the genius authors of SIP --
22466          increasing */
22467       p->icseq = seqno;
22468 
22469    /* Find their tag if we haven't got it */
22470    if (ast_strlen_zero(p->theirtag)) {
22471       char tag[128];
22472 
22473       gettag(req, "From", tag, sizeof(tag));
22474       ast_string_field_set(p, theirtag, tag);
22475    }
22476    snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
22477 
22478    if (sip_cfg.pedanticsipchecking) {
22479       /* If this is a request packet without a from tag, it's not
22480          correct according to RFC 3261  */
22481       /* Check if this a new request in a new dialog with a totag already attached to it,
22482          RFC 3261 - section 12.2 - and we don't want to mess with recovery  */
22483       if (!p->initreq.headers && req->has_to_tag) {
22484          /* If this is a first request and it got a to-tag, it is not for us */
22485          if (!req->ignore && req->method == SIP_INVITE) {
22486             transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
22487             /* Will cease to exist after ACK */
22488          } else if (req->method != SIP_ACK) {
22489             transmit_response(p, "481 Call/Transaction Does Not Exist", req);
22490             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22491          } else {
22492             ast_debug(1, "Got ACK for unknown dialog... strange.\n");
22493          }
22494          return res;
22495       }
22496    }
22497 
22498    if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY)) {
22499       transmit_response(p, "400 Bad request", req);
22500       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22501       return -1;
22502    }
22503 
22504    /* Handle various incoming SIP methods in requests */
22505    switch (p->method) {
22506    case SIP_OPTIONS:
22507       res = handle_request_options(p, req);
22508       break;
22509    case SIP_INVITE:
22510       res = handle_request_invite(p, req, debug, seqno, sin, recount, e, nounlock);
22511       break;
22512    case SIP_REFER:
22513       res = handle_request_refer(p, req, debug, seqno, nounlock);
22514       break;
22515    case SIP_CANCEL:
22516       res = handle_request_cancel(p, req);
22517       break;
22518    case SIP_BYE:
22519       res = handle_request_bye(p, req);
22520       break;
22521    case SIP_MESSAGE:
22522       res = handle_request_message(p, req);
22523       break;
22524    case SIP_SUBSCRIBE:
22525       res = handle_request_subscribe(p, req, sin, seqno, e);
22526       break;
22527    case SIP_REGISTER:
22528       res = handle_request_register(p, req, sin, e);
22529       break;
22530    case SIP_INFO:
22531       if (req->debug)
22532          ast_verbose("Receiving INFO!\n");
22533       if (!req->ignore) 
22534          handle_request_info(p, req);
22535       else  /* if ignoring, transmit response */
22536          transmit_response(p, "200 OK", req);
22537       break;
22538    case SIP_NOTIFY:
22539       res = handle_request_notify(p, req, sin, seqno, e);
22540       break;
22541    case SIP_ACK:
22542       /* Make sure we don't ignore this */
22543       if (seqno == p->pendinginvite) {
22544          p->invitestate = INV_TERMINATED;
22545          p->pendinginvite = 0;
22546          acked = __sip_ack(p, seqno, 1 /* response */, 0);
22547          if (find_sdp(req)) {
22548             if (process_sdp(p, req, SDP_T38_NONE))
22549                return -1;
22550          }
22551          check_pendings(p);
22552       } else if (p->glareinvite == seqno) {
22553          /* handle ack for the 491 pending sent for glareinvite */
22554          p->glareinvite = 0;
22555          acked = __sip_ack(p, seqno, 1, 0);
22556       }
22557       if (!acked) {
22558          /* Got an ACK that did not match anything. Ignore
22559           * silently and restore previous method */
22560          p->method = oldmethod;
22561       }
22562       if (!p->lastinvite && ast_strlen_zero(p->randdata)) {
22563          pvt_set_needdestroy(p, "unmatched ACK");
22564       }
22565       break;
22566    default:
22567       transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
22568       ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n", 
22569          cmd, ast_inet_ntoa(p->sa.sin_addr));
22570       /* If this is some new method, and we don't have a call, destroy it now */
22571       if (!p->initreq.headers) {
22572          pvt_set_needdestroy(p, "unimplemented method");
22573       }
22574       break;
22575    }
22576    return res;
22577 }
22578 
22579 static void process_request_queue(struct sip_pvt *p, int *recount, int *nounlock)
22580 {
22581    struct sip_request *req;
22582 
22583    while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
22584       if (handle_incoming(p, req, &p->recv, recount, nounlock) == -1) {
22585          /* Request failed */
22586          if (option_debug) {
22587             ast_log(LOG_DEBUG, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
22588          }
22589       }
22590       ast_free(req);
22591    }
22592 }
22593 
22594 static int scheduler_process_request_queue(const void *data)
22595 {
22596    struct sip_pvt *p = (struct sip_pvt *) data;
22597    int recount = 0;
22598    int nounlock = 0;
22599    int lockretry;
22600 
22601    for (lockretry = 10; lockretry > 0; lockretry--) {
22602       sip_pvt_lock(p);
22603 
22604       /* lock the owner if it has one -- we may need it */
22605       /* because this is deadlock-prone, we need to try and unlock if failed */
22606       if (!p->owner || !ast_channel_trylock(p->owner)) {
22607          break;   /* locking succeeded */
22608       }
22609 
22610       if (lockretry != 1) {
22611          sip_pvt_unlock(p);
22612          /* Sleep for a very short amount of time */
22613          usleep(1);
22614       }
22615    }
22616 
22617    if (!lockretry) {
22618       int retry = !AST_LIST_EMPTY(&p->request_queue);
22619 
22620       /* we couldn't get the owner lock, which is needed to process
22621          the queued requests, so return a non-zero value, which will
22622          cause the scheduler to run this request again later if there
22623          still requests to be processed
22624       */
22625       sip_pvt_unlock(p);
22626       if (!retry) {
22627          dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
22628       }
22629       return retry;
22630    };
22631 
22632    process_request_queue(p, &recount, &nounlock);
22633    p->request_queue_sched_id = -1;
22634 
22635    if (p->owner && !nounlock) {
22636       ast_channel_unlock(p->owner);
22637    }
22638    sip_pvt_unlock(p);
22639 
22640    if (recount) {
22641       ast_update_use_count();
22642    }
22643 
22644    dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
22645 
22646    return 0;
22647 }
22648 
22649 static int queue_request(struct sip_pvt *p, const struct sip_request *req)
22650 {
22651    struct sip_request *newreq;
22652 
22653    if (!(newreq = ast_calloc(1, sizeof(*newreq)))) {
22654       return -1;
22655    }
22656 
22657    copy_request(newreq, req);
22658    AST_LIST_INSERT_TAIL(&p->request_queue, newreq, next);
22659    if (p->request_queue_sched_id == -1) {
22660       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) {
22661          dialog_unref(p, "Decrement refcount due to sched_add failure");
22662       }
22663    }
22664 
22665    return 0;
22666 }
22667 
22668 /*! \brief Read data from SIP UDP socket
22669 \note sipsock_read locks the owner channel while we are processing the SIP message
22670 \return 1 on error, 0 on success
22671 \note Successful messages is connected to SIP call and forwarded to handle_incoming() 
22672 */
22673 static int sipsock_read(int *id, int fd, short events, void *ignore)
22674 {
22675    struct sip_request req;
22676    struct sockaddr_in sin = { 0, };
22677    int res;
22678    socklen_t len = sizeof(sin);
22679    static char readbuf[65535];
22680 
22681    memset(&req, 0, sizeof(req));
22682    res = recvfrom(fd, readbuf, sizeof(readbuf) - 1, 0, (struct sockaddr *)&sin, &len);
22683    if (res < 0) {
22684 #if !defined(__FreeBSD__)
22685       if (errno == EAGAIN)
22686          ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
22687       else 
22688 #endif
22689       if (errno != ECONNREFUSED)
22690          ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
22691       return 1;
22692    }
22693 
22694    readbuf[res] = '\0';
22695 
22696    if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
22697       return 1;
22698    }
22699 
22700    if (ast_str_set(&req.data, 0, "%s", readbuf) == AST_DYNSTR_BUILD_FAILED) {
22701       return -1;
22702    }
22703 
22704    /* req.data will have the correct length in case of nulls */
22705    req.len = ast_str_strlen(req.data);
22706    req.socket.fd = sipsock;
22707    set_socket_transport(&req.socket, SIP_TRANSPORT_UDP);
22708    req.socket.tcptls_session  = NULL;
22709    req.socket.port = bindaddr.sin_port;
22710 
22711    handle_request_do(&req, &sin);
22712    deinit_req(&req);
22713 
22714    return 1;
22715 }
22716 
22717 /*! \brief Handle incoming SIP message - request or response 
22718 
22719    This is used for all transports (udp, tcp and tcp/tls)
22720 */
22721 static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin) 
22722 {
22723    struct sip_pvt *p;
22724    int recount = 0;
22725    int nounlock = 0;
22726    int lockretry;
22727 
22728    if (sip_debug_test_addr(sin)) /* Set the debug flag early on packet level */
22729       req->debug = 1;
22730    if (sip_cfg.pedanticsipchecking)
22731       req->len = lws2sws(req->data->str, req->len);   /* Fix multiline headers */
22732    if (req->debug) {
22733       ast_verbose("\n<--- SIP read from %s:%s:%d --->\n%s\n<------------->\n", 
22734          get_transport(req->socket.type), ast_inet_ntoa(sin->sin_addr), 
22735          ntohs(sin->sin_port), req->data->str);
22736    }
22737 
22738    if (parse_request(req) == -1) { /* Bad packet, can't parse */
22739       ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
22740       return 1;
22741    }
22742    req->method = find_sip_method(REQ_OFFSET_TO_STR(req, rlPart1));
22743 
22744    if (req->debug)
22745       ast_verbose("--- (%d headers %d lines)%s ---\n", req->headers, req->lines, (req->headers + req->lines == 0) ? " Nat keepalive" : "");
22746 
22747    if (req->headers < 2) { /* Must have at least two headers */
22748       ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
22749       return 1;
22750    }
22751 
22752    /* Process request, with netlock held, and with usual deadlock avoidance */
22753    for (lockretry = 10; lockretry > 0; lockretry--) {
22754       ast_mutex_lock(&netlock);
22755 
22756       /* Find the active SIP dialog or create a new one */
22757       p = find_call(req, sin, req->method);  /* returns p locked and ref'd */
22758       if (p == NULL) {
22759          ast_debug(1, "Invalid SIP message - rejected , no callid, len %d\n", req->len);
22760          ast_mutex_unlock(&netlock);
22761          return 1;
22762       }
22763 
22764       copy_socket_data(&p->socket, &req->socket);
22765 
22766       /* Go ahead and lock the owner if it has one -- we may need it */
22767       /* becaues this is deadlock-prone, we need to try and unlock if failed */
22768       if (!p->owner || !ast_channel_trylock(p->owner))
22769          break;   /* locking succeeded */
22770 
22771       if (lockretry != 1) {
22772          sip_pvt_unlock(p);
22773          ao2_t_ref(p, -1, "release p (from find_call) inside lockretry loop"); /* we'll look for it again, but p is dead now */
22774          ast_mutex_unlock(&netlock);
22775          /* Sleep for a very short amount of time */
22776          usleep(1);
22777       }
22778    }
22779    p->recv = *sin;
22780 
22781    /* if we have an owner, then this request has been authenticated */
22782    if (p->owner) {
22783       req->authenticated = 1;
22784    }
22785 
22786    if (p->do_history) /* This is a request or response, note what it was for */
22787       append_history(p, "Rx", "%s / %s / %s", req->data->str, get_header(req, "CSeq"), REQ_OFFSET_TO_STR(req, rlPart2));
22788 
22789    if (!lockretry) {
22790       if (!queue_request(p, req)) {
22791          /* the request has been queued for later handling */
22792          sip_pvt_unlock(p);
22793          ao2_t_ref(p, -1, "release p (from find_call) after queueing request");
22794          ast_mutex_unlock(&netlock);
22795          return 1;
22796       }
22797 
22798       if (p->owner)
22799          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 ??? - "));
22800       ast_log(LOG_ERROR, "SIP transaction failed: %s \n", p->callid);
22801       if (req->method != SIP_ACK)
22802          transmit_response(p, "503 Server error", req);  /* We must respond according to RFC 3261 sec 12.2 */
22803       /* XXX We could add retry-after to make sure they come back */
22804       append_history(p, "LockFail", "Owner lock failed, transaction failed.");
22805       sip_pvt_unlock(p);
22806       ao2_t_ref(p, -1, "release p (from find_call) at end of lockretry"); /* p is gone after the return */
22807       ast_mutex_unlock(&netlock);
22808       return 1;
22809    }
22810 
22811    /* if there are queued requests on this sip_pvt, process them first, so that everything is
22812       handled in order
22813    */
22814    if (!AST_LIST_EMPTY(&p->request_queue)) {
22815       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"));
22816       process_request_queue(p, &recount, &nounlock);
22817    }
22818 
22819    if (handle_incoming(p, req, sin, &recount, &nounlock) == -1) {
22820       /* Request failed */
22821       ast_debug(1, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
22822    }
22823       
22824    if (recount)
22825       ast_update_use_count();
22826 
22827    if (p->owner && !nounlock)
22828       ast_channel_unlock(p->owner);
22829    sip_pvt_unlock(p);
22830    ao2_t_ref(p, -1, "throw away dialog ptr from find_call at end of routine"); /* p is gone after the return */
22831    ast_mutex_unlock(&netlock);
22832    return 1;
22833 }
22834 
22835 /*! \brief Returns the port to use for this socket
22836  *
22837  * \param type The type of transport used
22838  * \param port Port we are checking to see if it's the standard port.
22839  * \note port is expected in host byte order
22840  */
22841 static int sip_standard_port(enum sip_transport type, int port)
22842 {
22843    if (type & SIP_TRANSPORT_TLS)
22844       return port == STANDARD_TLS_PORT;
22845    else
22846       return port == STANDARD_SIP_PORT;
22847 }
22848 
22849 static int threadinfo_locate_cb(void *obj, void *arg, int flags)
22850 {
22851    struct sip_threadinfo *th = obj;
22852    struct sockaddr_in *s = arg;
22853 
22854    if (!inaddrcmp(&th->tcptls_session->remote_address, s)) {
22855       return CMP_MATCH | CMP_STOP;
22856    }
22857 
22858    return 0;
22859 }
22860 
22861 /*! 
22862  * \brief Find thread for TCP/TLS session (based on IP/Port 
22863  *
22864  * \note This function returns an astobj2 reference
22865  */
22866 static struct ast_tcptls_session_instance *sip_tcp_locate(struct sockaddr_in *s)
22867 {
22868    struct sip_threadinfo *th;
22869    struct ast_tcptls_session_instance *tcptls_instance = NULL;
22870 
22871    if ((th = ao2_callback(threadt, 0, threadinfo_locate_cb, s))) {
22872       tcptls_instance = (ao2_ref(th->tcptls_session, +1), th->tcptls_session);
22873       ao2_t_ref(th, -1, "decrement ref from callback");
22874    }
22875    return tcptls_instance;
22876 }
22877 
22878 /*! \todo Get socket for dialog, prepare if needed, and return file handle  */
22879 static int sip_prepare_socket(struct sip_pvt *p) 
22880 {
22881    struct sip_socket *s = &p->socket;
22882    static const char name[] = "SIP socket";
22883    struct sip_threadinfo *th = NULL;
22884    struct ast_tcptls_session_instance *tcptls_session;
22885    struct ast_tcptls_session_args tmp_ca = {
22886       .name = name,
22887       .accept_fd = -1,
22888    };
22889    struct ast_tcptls_session_args *ca;
22890 
22891    /* check to see if a socket is already active */
22892    if ((s->fd != -1) && (s->type == SIP_TRANSPORT_UDP)) {
22893       return s->fd;
22894    }
22895    if ((s->type & (SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS)) &&
22896          (s->tcptls_session) &&
22897          (s->tcptls_session->fd != -1)) {
22898       return s->tcptls_session->fd;
22899    }
22900 
22901    /*! \todo Check this... This might be wrong, depending on the proxy configuration
22902       If proxy is in "force" mode its correct.
22903     */
22904    if (p->outboundproxy && p->outboundproxy->transport) {
22905       s->type = p->outboundproxy->transport;
22906    }
22907 
22908    if (s->type == SIP_TRANSPORT_UDP) {
22909       s->fd = sipsock;
22910       return s->fd;
22911    }
22912 
22913    /* At this point we are dealing with a TCP/TLS connection
22914     * 1. We need to check to see if a connectin thread exists
22915     *    for this address, if so use that.
22916     * 2. If a thread does not exist for this address, but the tcptls_session
22917     *    exists on the socket, the connection was closed.
22918     * 3. If no tcptls_session thread exists for the address, and no tcptls_session
22919     *    already exists on the socket, create a new one and launch a new thread.
22920     */
22921 
22922    /* 1.  check for existing threads */
22923    tmp_ca.remote_address = *(sip_real_dst(p));
22924    if ((tcptls_session = sip_tcp_locate(&tmp_ca.remote_address))) {
22925       s->fd = tcptls_session->fd;
22926       if (s->tcptls_session) {
22927          ao2_ref(s->tcptls_session, -1);
22928          s->tcptls_session = NULL;
22929       }
22930       s->tcptls_session = tcptls_session;
22931       return s->fd;
22932    /* 2.  Thread not found, if tcptls_session already exists, it once had a thread and is now terminated */
22933    } else if (s->tcptls_session) {
22934       return s->fd; /* XXX whether reconnection is ever necessary here needs to be investigated further */
22935    }
22936 
22937    /* 3.  Create a new TCP/TLS client connection */
22938    /* create new session arguments for the client connection */
22939    if (!(ca = ao2_alloc(sizeof(*ca), sip_tcptls_client_args_destructor)) ||
22940       !(ca->name = ast_strdup(name))) {
22941       goto create_tcptls_session_fail;
22942    }
22943    ca->accept_fd = -1;
22944    ca->remote_address = *(sip_real_dst(p));
22945    /* if type is TLS, we need to create a tls cfg for this session arg */
22946    if (s->type == SIP_TRANSPORT_TLS) {
22947       if (!(ca->tls_cfg = ast_calloc(1, sizeof(*ca->tls_cfg)))) {
22948          goto create_tcptls_session_fail;
22949       }
22950       memcpy(ca->tls_cfg, &default_tls_cfg, sizeof(*ca->tls_cfg));
22951 
22952       if (!(ca->tls_cfg->certfile = ast_strdup(default_tls_cfg.certfile)) ||
22953          !(ca->tls_cfg->cipher = ast_strdup(default_tls_cfg.cipher)) ||
22954          !(ca->tls_cfg->cafile = ast_strdup(default_tls_cfg.cafile)) ||
22955          !(ca->tls_cfg->capath = ast_strdup(default_tls_cfg.capath))) {
22956 
22957          goto create_tcptls_session_fail;
22958       }
22959 
22960       /* this host is used as the common name in ssl/tls */
22961       if (!ast_strlen_zero(p->tohost)) {
22962          ast_copy_string(ca->hostname, p->tohost, sizeof(ca->hostname));
22963       }
22964    }
22965    /* Create a client connection for address, this does not start the connection, just sets it up. */
22966    if (!(s->tcptls_session = ast_tcptls_client_create(ca))) {
22967       goto create_tcptls_session_fail;
22968    }
22969 
22970    s->fd = s->tcptls_session->fd;
22971 
22972    /* client connections need to have the sip_threadinfo object created before
22973     * the thread is detached.  This ensures the alert_pipe is up before it will
22974     * be used.  Note that this function links the new threadinfo object into the
22975     * threadt container. */
22976    if (!(th = sip_threadinfo_create(s->tcptls_session, s->type))) {
22977       goto create_tcptls_session_fail;
22978 
22979    }
22980 
22981    /* Give the new thread a reference to the tcptls_session */
22982    ao2_ref(s->tcptls_session, +1);
22983 
22984    if (ast_pthread_create_background(&ca->master, NULL, sip_tcp_worker_fn, s->tcptls_session)) {
22985       ast_debug(1, "Unable to launch '%s'.", ca->name);
22986       ao2_ref(s->tcptls_session, -1); /* take away the thread ref we just gave it */
22987       goto create_tcptls_session_fail;
22988    }
22989 
22990    return s->fd;
22991 
22992 create_tcptls_session_fail:
22993    if (ca) {
22994       ao2_t_ref(ca, -1, "failed to create client, getting rid of client tcptls_session arguments");
22995    }
22996    if (s->tcptls_session) {
22997       close(tcptls_session->fd);
22998       s->fd = tcptls_session->fd = -1;
22999       ao2_ref(s->tcptls_session, -1);
23000       s->tcptls_session = NULL;
23001    }
23002    if (th) {
23003       ao2_t_unlink(threadt, th, "Removing tcptls thread info object, thread failed to open");
23004    }
23005 
23006    return -1;
23007 }
23008 
23009 /*!
23010  * \brief Small function to parse a config line for a host with a transport
23011  *        i.e. tls://www.google.com:8056
23012  */
23013 static int sip_parse_host(char *line, int lineno, char **hostname, int *portnum, enum sip_transport *transport)
23014 {
23015    char *port;
23016 
23017    if ((*hostname = strstr(line, "://"))) {
23018       *hostname += 3;
23019 
23020       if (!strncasecmp(line, "tcp", 3))
23021          *transport = SIP_TRANSPORT_TCP;
23022       else if (!strncasecmp(line, "tls", 3))
23023          *transport = SIP_TRANSPORT_TLS;
23024       else if (!strncasecmp(line, "udp", 3))
23025          *transport = SIP_TRANSPORT_UDP;
23026       else
23027          ast_log(LOG_NOTICE, "'%.3s' is not a valid transport type on line %d of sip.conf. defaulting to udp.\n", line, lineno);
23028    } else {
23029       *hostname = line;
23030       *transport = SIP_TRANSPORT_UDP;
23031    }
23032 
23033    if ((line = strrchr(*hostname, '@')))
23034       line++;
23035    else
23036       line = *hostname;
23037 
23038    if ((port = strrchr(line, ':'))) {
23039       *port++ = '\0';
23040 
23041       if (!sscanf(port, "%5u", portnum)) {
23042          ast_log(LOG_NOTICE, "'%s' is not a valid port number on line %d of sip.conf. using default.\n", port, lineno);
23043          port = NULL;
23044       }
23045    }
23046 
23047    if (!port) {
23048       if (*transport & SIP_TRANSPORT_TLS) {
23049          *portnum = STANDARD_TLS_PORT;
23050       } else {
23051          *portnum = STANDARD_SIP_PORT;
23052       }
23053    }
23054 
23055    return 0;
23056 }
23057 
23058 /*!
23059  * \brief Get cached MWI info
23060  * \retval 0 At least one message is waiting
23061  * \retval 1 no messages waiting
23062  */
23063 static int get_cached_mwi(struct sip_peer *peer, int *new, int *old)
23064 {
23065    struct sip_mailbox *mailbox;
23066 
23067    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
23068       struct ast_event *event;
23069       event = ast_event_get_cached(AST_EVENT_MWI,
23070          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
23071          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
23072          AST_EVENT_IE_END);
23073       if (!event)
23074          continue;
23075       *new += ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
23076       *old += ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
23077       ast_event_destroy(event);
23078    }
23079 
23080    return (*new || *old) ? 0 : 1;
23081 }
23082 
23083 /*! \brief Send message waiting indication to alert peer that they've got voicemail */
23084 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only)
23085 {
23086    /* Called with peerl lock, but releases it */
23087    struct sip_pvt *p;
23088    int newmsgs = 0, oldmsgs = 0;
23089 
23090    if (ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY) && !peer->mwipvt)
23091       return 0;
23092 
23093    /* Do we have an IP address? If not, skip this peer */
23094    if (!peer->addr.sin_addr.s_addr && !peer->defaddr.sin_addr.s_addr) 
23095       return 0;
23096 
23097    if (event) {
23098       newmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
23099       oldmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
23100    } else if (!cache_only) { /* Fall back to manually checking the mailbox */
23101       struct ast_str *mailbox_str = ast_str_alloca(512);
23102       peer_mailboxes_to_str(&mailbox_str, peer);
23103       ast_app_inboxcount(mailbox_str->str, &newmsgs, &oldmsgs);
23104    } else {
23105       get_cached_mwi(peer, &newmsgs, &oldmsgs);
23106    }
23107    
23108    if (peer->mwipvt) {
23109       /* Base message on subscription */
23110       p = dialog_ref(peer->mwipvt, "sip_send_mwi_to_peer: Setting dialog ptr p from peer->mwipvt-- should this be done?");
23111    } else {
23112       /* Build temporary dialog for this message */
23113       if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) 
23114          return -1;
23115       /* If we don't set the socket type to 0, then create_addr_from_peer will fail immediately if the peer
23116        * uses any transport other than UDP. We set the type to 0 here and then let create_addr_from_peer copy 
23117        * the peer's socket information to the sip_pvt we just allocated
23118        */
23119       set_socket_transport(&p->socket, 0);
23120       if (create_addr_from_peer(p, peer)) {
23121          /* Maybe they're not registered, etc. */
23122          dialog_unlink_all(p, TRUE, TRUE);
23123          dialog_unref(p, "unref dialog p just created via sip_alloc");
23124          /* sip_destroy(p); */
23125          return 0;
23126       }
23127       /* Recalculate our side, and recalculate Call ID */
23128       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
23129       build_via(p);
23130       ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
23131       build_callid_pvt(p);
23132       ao2_t_link(dialogs, p, "Linking in under new name");
23133       /* Destroy this session after 32 secs */
23134       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23135    }
23136 
23137    /* Send MWI */
23138    ast_set_flag(&p->flags[0], SIP_OUTGOING);
23139    /* the following will decrement the refcount on p as it finishes */
23140    transmit_notify_with_mwi(p, newmsgs, oldmsgs, peer->vmexten);
23141    dialog_unref(p, "unref dialog ptr p just before it goes out of scope at the end of sip_send_mwi_to_peer.");
23142    return 0;
23143 }
23144 
23145 /*! \brief helper function for the monitoring thread -- seems to be called with the assumption that the dialog is locked */
23146 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t)
23147 {
23148    /* If we have no RTP or no active owner, no need to check timers */
23149    if (!dialog->rtp || !dialog->owner)
23150       return;
23151    /* If the call is not in UP state or redirected outside Asterisk, no need to check timers */
23152 
23153    if (dialog->owner->_state != AST_STATE_UP || dialog->redirip.sin_addr.s_addr)
23154       return;
23155 
23156    /* If the call is involved in a T38 fax session do not check RTP timeout */
23157    if (dialog->t38.state == T38_ENABLED)
23158       return;
23159 
23160    /* If we have no timers set, return now */
23161    if ((ast_rtp_get_rtpkeepalive(dialog->rtp) == 0) && (ast_rtp_get_rtptimeout(dialog->rtp) == 0) && (ast_rtp_get_rtpholdtimeout(dialog->rtp) == 0))
23162       return;
23163 
23164    /* Check AUDIO RTP keepalives */
23165    if (dialog->lastrtptx && ast_rtp_get_rtpkeepalive(dialog->rtp) &&
23166           (t > dialog->lastrtptx + ast_rtp_get_rtpkeepalive(dialog->rtp))) {
23167       /* Need to send an empty RTP packet */
23168       dialog->lastrtptx = time(NULL);
23169       ast_rtp_sendcng(dialog->rtp, 0);
23170    }
23171 
23172    /*! \todo Check video RTP keepalives
23173 
23174       Do we need to move the lastrtptx to the RTP structure to have one for audio and one
23175       for video? It really does belong to the RTP structure.
23176    */
23177 
23178    /* Check AUDIO RTP timers */
23179    if (dialog->lastrtprx && (ast_rtp_get_rtptimeout(dialog->rtp) || ast_rtp_get_rtpholdtimeout(dialog->rtp)) &&
23180           (t > dialog->lastrtprx + ast_rtp_get_rtptimeout(dialog->rtp))) {
23181 
23182       /* Might be a timeout now -- see if we're on hold */
23183       struct sockaddr_in sin;
23184       ast_rtp_get_peer(dialog->rtp, &sin);
23185       if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD) || (ast_rtp_get_rtpholdtimeout(dialog->rtp) &&
23186            (t > dialog->lastrtprx + ast_rtp_get_rtpholdtimeout(dialog->rtp)))) {
23187          /* Needs a hangup */
23188          if (ast_rtp_get_rtptimeout(dialog->rtp)) {
23189             while (dialog->owner && ast_channel_trylock(dialog->owner)) {
23190                sip_pvt_unlock(dialog);
23191                usleep(1);
23192                sip_pvt_lock(dialog);
23193             }
23194             if (!dialog->owner) {
23195                return; /* channel hangup can occur during deadlock avoidance. */
23196             }
23197             ast_log(LOG_NOTICE, "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
23198                dialog->owner->name, (long) (t - dialog->lastrtprx));
23199             /* Issue a softhangup */
23200             ast_softhangup_nolock(dialog->owner, AST_SOFTHANGUP_DEV);
23201             ast_channel_unlock(dialog->owner);
23202             /* forget the timeouts for this call, since a hangup
23203                has already been requested and we don't want to
23204                repeatedly request hangups
23205             */
23206             ast_rtp_set_rtptimeout(dialog->rtp, 0);
23207             ast_rtp_set_rtpholdtimeout(dialog->rtp, 0);
23208             if (dialog->vrtp) {
23209                ast_rtp_set_rtptimeout(dialog->vrtp, 0);
23210                ast_rtp_set_rtpholdtimeout(dialog->vrtp, 0);
23211             }
23212          }
23213       }
23214    }
23215 }
23216 
23217 /*! \brief The SIP monitoring thread 
23218 \note This thread monitors all the SIP sessions and peers that needs notification of mwi
23219    (and thus do not have a separate thread) indefinitely 
23220 */
23221 static void *do_monitor(void *data)
23222 {
23223    int res;
23224    time_t t;
23225    int reloading;
23226 
23227    /* Add an I/O event to our SIP UDP socket */
23228    if (sipsock > -1) 
23229       sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
23230 
23231    /* From here on out, we die whenever asked */
23232    for(;;) {
23233       /* Check for a reload request */
23234       ast_mutex_lock(&sip_reload_lock);
23235       reloading = sip_reloading;
23236       sip_reloading = FALSE;
23237       ast_mutex_unlock(&sip_reload_lock);
23238       if (reloading) {
23239          ast_verb(1, "Reloading SIP\n");
23240          sip_do_reload(sip_reloadreason);
23241 
23242          /* Change the I/O fd of our UDP socket */
23243          if (sipsock > -1) {
23244             if (sipsock_read_id)
23245                sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
23246             else
23247                sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
23248          } else if (sipsock_read_id) {
23249             ast_io_remove(io, sipsock_read_id);
23250             sipsock_read_id = NULL;
23251          }
23252       }
23253 
23254       /* Check for dialogs needing to be killed */
23255       t = time(NULL);
23256       /* don't scan the dialogs list if it hasn't been a reasonable period
23257          of time since the last time we did it (when MWI is being sent, we can
23258          get back to this point every millisecond or less)
23259       */
23260       ao2_t_callback(dialogs, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, dialog_needdestroy, &t,
23261             "callback to remove dialogs w/needdestroy");
23262 
23263       /* the old methodology would be to restart the search for dialogs to delete with every 
23264          dialog that was found and destroyed, probably because the list contents would change,
23265          so we'd need to restart. This isn't the best thing to do with callbacks. */
23266 
23267       /* XXX TODO The scheduler usage in this module does not have sufficient 
23268        * synchronization being done between running the scheduler and places 
23269        * scheduling tasks.  As it is written, any scheduled item may not run 
23270        * any sooner than about  1 second, regardless of whether a sooner time 
23271        * was asked for. */
23272 
23273       pthread_testcancel();
23274       /* Wait for sched or io */
23275       res = ast_sched_wait(sched);
23276       if ((res < 0) || (res > 1000))
23277          res = 1000;
23278       res = ast_io_wait(io, res);
23279       if (res > 20)
23280          ast_debug(1, "chan_sip: ast_io_wait ran %d all at once\n", res);
23281       ast_mutex_lock(&monlock);
23282       res = ast_sched_runq(sched);
23283       if (res >= 20)
23284          ast_debug(1, "chan_sip: ast_sched_runq ran %d all at once\n", res);
23285       ast_mutex_unlock(&monlock);
23286    }
23287 
23288    /* Never reached */
23289    return NULL;
23290 }
23291 
23292 /*! \brief Start the channel monitor thread */
23293 static int restart_monitor(void)
23294 {
23295    /* If we're supposed to be stopped -- stay stopped */
23296    if (monitor_thread == AST_PTHREADT_STOP)
23297       return 0;
23298    ast_mutex_lock(&monlock);
23299    if (monitor_thread == pthread_self()) {
23300       ast_mutex_unlock(&monlock);
23301       ast_log(LOG_WARNING, "Cannot kill myself\n");
23302       return -1;
23303    }
23304    if (monitor_thread != AST_PTHREADT_NULL) {
23305       /* Wake up the thread */
23306       pthread_kill(monitor_thread, SIGURG);
23307    } else {
23308       /* Start a new monitor */
23309       if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
23310          ast_mutex_unlock(&monlock);
23311          ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
23312          return -1;
23313       }
23314    }
23315    ast_mutex_unlock(&monlock);
23316    return 0;
23317 }
23318 
23319 
23320 /*! \brief Session-Timers: Restart session timer */
23321 static void restart_session_timer(struct sip_pvt *p)
23322 {
23323    if (!p->stimer) {
23324       ast_log(LOG_WARNING, "Null stimer in restart_session_timer - %s\n", p->callid);
23325       return;
23326    }
23327 
23328    if (p->stimer->st_active == TRUE) {
23329       ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
23330       AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
23331             dialog_unref(p, "Removing session timer ref"));
23332       start_session_timer(p);
23333    }
23334 }
23335 
23336 
23337 /*! \brief Session-Timers: Stop session timer */
23338 static void stop_session_timer(struct sip_pvt *p)
23339 {
23340    if (!p->stimer) {
23341       ast_log(LOG_WARNING, "Null stimer in stop_session_timer - %s\n", p->callid);
23342       return;
23343    }
23344 
23345    if (p->stimer->st_active == TRUE) {
23346       p->stimer->st_active = FALSE;
23347       ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
23348       AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
23349             dialog_unref(p, "removing session timer ref"));
23350    }
23351 }
23352 
23353 
23354 /*! \brief Session-Timers: Start session timer */
23355 static void start_session_timer(struct sip_pvt *p)
23356 {
23357    if (!p->stimer) {
23358       ast_log(LOG_WARNING, "Null stimer in start_session_timer - %s\n", p->callid);
23359       return;
23360    }
23361 
23362    if (p->stimer->st_schedid > -1) {
23363       /* in the event a timer is already going, stop it */
23364       ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
23365       AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
23366          dialog_unref(p, "unref stimer->st_schedid from dialog"));
23367    }
23368 
23369    p->stimer->st_schedid  = ast_sched_add(sched, p->stimer->st_interval * 1000 / 2, proc_session_timer, 
23370          dialog_ref(p, "adding session timer ref"));
23371    if (p->stimer->st_schedid < 0) {
23372       dialog_unref(p, "removing session timer ref");
23373       ast_log(LOG_ERROR, "ast_sched_add failed - %s\n", p->callid);
23374    } else {
23375       p->stimer->st_active = TRUE;
23376       ast_debug(2, "Session timer started: %d - %s\n", p->stimer->st_schedid, p->callid);
23377    }
23378 }
23379 
23380 
23381 /*! \brief Session-Timers: Process session refresh timeout event */
23382 static int proc_session_timer(const void *vp)
23383 {
23384    struct sip_pvt *p = (struct sip_pvt *) vp;
23385    int sendreinv = FALSE;
23386    int res = 0;
23387 
23388    if (!p->stimer) {
23389       ast_log(LOG_WARNING, "Null stimer in proc_session_timer - %s\n", p->callid);
23390       goto return_unref;
23391    }
23392 
23393    ast_debug(2, "Session timer expired: %d - %s\n", p->stimer->st_schedid, p->callid);
23394 
23395    if (!p->owner) {
23396       goto return_unref;
23397    }
23398 
23399    if ((p->stimer->st_active != TRUE) || (p->owner->_state != AST_STATE_UP)) {
23400       goto return_unref;
23401    }
23402 
23403    switch (p->stimer->st_ref) {
23404    case SESSION_TIMER_REFRESHER_UAC:
23405       if (p->outgoing_call == TRUE) {
23406          sendreinv = TRUE;
23407       }
23408       break;
23409    case SESSION_TIMER_REFRESHER_UAS:
23410       if (p->outgoing_call != TRUE) {
23411          sendreinv = TRUE;
23412       }
23413       break;
23414    default:
23415       ast_log(LOG_ERROR, "Unknown session refresher %d\n", p->stimer->st_ref);
23416       goto return_unref;
23417    }
23418 
23419    if (sendreinv == TRUE) {
23420       res = 1;
23421       transmit_reinvite_with_sdp(p, FALSE, TRUE);
23422    } else {
23423       p->stimer->st_expirys++;
23424       if (p->stimer->st_expirys >= 2) {
23425          if (p->stimer->quit_flag) {
23426             goto return_unref;
23427          }
23428          ast_log(LOG_WARNING, "Session-Timer expired - %s\n", p->callid);
23429          sip_pvt_lock(p);
23430          while (p->owner && ast_channel_trylock(p->owner)) {
23431             sip_pvt_unlock(p);
23432             usleep(1);
23433             if (p->stimer && p->stimer->quit_flag) {
23434                goto return_unref;
23435             }
23436             sip_pvt_lock(p);
23437          }
23438 
23439          ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
23440          ast_channel_unlock(p->owner);
23441          sip_pvt_unlock(p);
23442       }
23443    }
23444 
23445 return_unref:
23446    if (!res) {
23447       /* An error occurred.  Stop session timer processing */
23448       if (p->stimer) {
23449          ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
23450          p->stimer->st_schedid = -1;
23451          stop_session_timer(p);
23452       }
23453 
23454       /* If we are not asking to be rescheduled, then we need to release our
23455        * reference to the dialog. */
23456       dialog_unref(p, "removing session timer ref");
23457    }
23458 
23459    return res;
23460 }
23461 
23462 
23463 /*! \brief Session-Timers: Function for parsing Min-SE header */
23464 int parse_minse (const char *p_hdrval, int *const p_interval)
23465 {
23466    if (ast_strlen_zero(p_hdrval)) {
23467       ast_log(LOG_WARNING, "Null Min-SE header\n");
23468       return -1;
23469    }
23470 
23471    *p_interval = 0;
23472    p_hdrval = ast_skip_blanks(p_hdrval);
23473    if (!sscanf(p_hdrval, "%30d", p_interval)) {
23474       ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
23475       return -1;
23476    }
23477 
23478    ast_debug(2, "Received Min-SE: %d\n", *p_interval);
23479    return 0;
23480 }
23481 
23482 
23483 /*! \brief Session-Timers: Function for parsing Session-Expires header */
23484 int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref)
23485 {
23486    char *p_token;
23487    int  ref_idx;
23488    char *p_se_hdr;
23489 
23490    if (ast_strlen_zero(p_hdrval)) {
23491       ast_log(LOG_WARNING, "Null Session-Expires header\n");
23492       return -1;
23493    }
23494 
23495    *p_ref = SESSION_TIMER_REFRESHER_AUTO;
23496    *p_interval = 0;
23497 
23498    p_se_hdr = ast_strdupa(p_hdrval);
23499    p_se_hdr = ast_skip_blanks(p_se_hdr);
23500 
23501    while ((p_token = strsep(&p_se_hdr, ";"))) {
23502       p_token = ast_skip_blanks(p_token);
23503       if (!sscanf(p_token, "%30d", p_interval)) {
23504          ast_log(LOG_WARNING, "Parsing of Session-Expires failed\n");
23505          return -1;
23506       }
23507 
23508       ast_debug(2, "Session-Expires: %d\n", *p_interval);
23509 
23510       if (!p_se_hdr)
23511          continue;
23512 
23513       p_se_hdr = ast_skip_blanks(p_se_hdr);
23514       ref_idx = strlen("refresher=");
23515       if (!strncasecmp(p_se_hdr, "refresher=", ref_idx)) {
23516          p_se_hdr += ref_idx;
23517          p_se_hdr = ast_skip_blanks(p_se_hdr);
23518 
23519          if (!strncasecmp(p_se_hdr, "uac", strlen("uac"))) {
23520             *p_ref = SESSION_TIMER_REFRESHER_UAC;
23521             ast_debug(2, "Refresher: UAC\n");
23522          } else if (!strncasecmp(p_se_hdr, "uas", strlen("uas"))) {
23523             *p_ref = SESSION_TIMER_REFRESHER_UAS;
23524             ast_debug(2, "Refresher: UAS\n");
23525          } else {
23526             ast_log(LOG_WARNING, "Invalid refresher value %s\n", p_se_hdr);
23527             return -1;
23528          }
23529          break;
23530       }
23531    }
23532    return 0;
23533 }
23534 
23535 
23536 /*! \brief Handle 422 response to INVITE with session-timer requested
23537 
23538    Session-Timers:   An INVITE originated by Asterisk that asks for session-timers support
23539    from the UAS can result into a 422 response. This is how a UAS or an intermediary proxy 
23540    server tells Asterisk that the session refresh interval offered by Asterisk is too low 
23541    for them.  The proc_422_rsp() function handles a 422 response.  It extracts the Min-SE 
23542    header that comes back in 422 and sends a new INVITE accordingly. */
23543 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp)
23544 {
23545    int rtn;
23546    const char *p_hdrval;
23547    int minse;
23548 
23549    p_hdrval = get_header(rsp, "Min-SE");
23550    if (ast_strlen_zero(p_hdrval)) {
23551       ast_log(LOG_WARNING, "422 response without a Min-SE header %s\n", p_hdrval);
23552       return;
23553    }
23554    rtn = parse_minse(p_hdrval, &minse);
23555    if (rtn != 0) {
23556       ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
23557       return;
23558    }
23559    p->stimer->st_interval = minse;
23560    transmit_invite(p, SIP_INVITE, 1, 2); 
23561 }
23562 
23563 
23564 /*! \brief Get Max or Min SE (session timer expiry)
23565  * \param p pointer to the SIP dialog 
23566  * \param max if true, get max se, otherwise min se
23567 */
23568 int st_get_se(struct sip_pvt *p, int max)
23569 {
23570    if (max == TRUE) {
23571       if (p->stimer->st_cached_max_se) {
23572          return p->stimer->st_cached_max_se;
23573       } else if (p->peername) {
23574          struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
23575          if (pp) {
23576             p->stimer->st_cached_max_se = pp->stimer.st_max_se;
23577             unref_peer(pp, "unref peer pointer from find_peer call in st_get_se");
23578             return (p->stimer->st_cached_max_se);
23579          }
23580       }
23581       p->stimer->st_cached_max_se = global_max_se;
23582       return (p->stimer->st_cached_max_se);
23583    } else {
23584       if (p->stimer->st_cached_min_se) {
23585          return p->stimer->st_cached_min_se;
23586       } else if (p->peername) {
23587          struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
23588          if (pp) {
23589             p->stimer->st_cached_min_se = pp->stimer.st_min_se;
23590             unref_peer(pp, "unref peer pointer from find_peer call in st_get_se (2)");
23591             return (p->stimer->st_cached_min_se);
23592          }
23593       }
23594       p->stimer->st_cached_min_se = global_min_se;
23595       return (p->stimer->st_cached_min_se);
23596    }
23597 }
23598 
23599 
23600 /*! \brief Get the entity (UAC or UAS) that's acting as the session-timer refresher 
23601  * \param p pointer to the SIP dialog 
23602 */
23603 enum st_refresher st_get_refresher(struct sip_pvt *p)
23604 {
23605    if (p->stimer->st_cached_ref != SESSION_TIMER_REFRESHER_AUTO) 
23606       return p->stimer->st_cached_ref;
23607 
23608    if (p->peername) {
23609       struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
23610       if (pp) {
23611          p->stimer->st_cached_ref = pp->stimer.st_ref;
23612          unref_peer(pp, "unref peer pointer from find_peer call in st_get_refresher");
23613          return pp->stimer.st_ref;
23614       }
23615    }
23616    
23617    p->stimer->st_cached_ref = global_st_refresher;
23618    return global_st_refresher;
23619 }
23620 
23621 
23622 /*!
23623  * \brief Get the session-timer mode 
23624  * \param p pointer to the SIP dialog 
23625  * \param no_cached, set this to true in order to force a peername lookup on
23626  *        the session timer mode.
23627 */
23628 enum st_mode st_get_mode(struct sip_pvt *p, int no_cached)
23629 {
23630    if (!p->stimer) 
23631       sip_st_alloc(p);
23632 
23633    if (!no_cached && p->stimer->st_cached_mode != SESSION_TIMER_MODE_INVALID)
23634       return p->stimer->st_cached_mode;
23635 
23636    if (p->peername) {
23637       struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
23638       if (pp) {
23639          p->stimer->st_cached_mode = pp->stimer.st_mode_oper;
23640          unref_peer(pp, "unref peer pointer from find_peer call in st_get_mode");
23641          return pp->stimer.st_mode_oper;
23642       }
23643    }
23644 
23645    p->stimer->st_cached_mode = global_st_mode;
23646    return global_st_mode;
23647 }
23648 
23649 
23650 /*! \brief React to lack of answer to Qualify poke */
23651 static int sip_poke_noanswer(const void *data)
23652 {
23653    struct sip_peer *peer = (struct sip_peer *)data;
23654 
23655    peer->pokeexpire = -1;
23656 
23657    if (peer->lastms > -1) {
23658       ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE!  Last qualify: %d\n", peer->name, peer->lastms);
23659       if (sip_cfg.peer_rtupdate) {
23660          ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", "-1", SENTINEL);
23661       }
23662       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
23663       if (sip_cfg.regextenonqualify) {
23664          register_peer_exten(peer, FALSE);
23665       }
23666    }
23667 
23668    if (peer->call) {
23669       dialog_unlink_all(peer->call, TRUE, TRUE);
23670       peer->call = dialog_unref(peer->call, "unref dialog peer->call");
23671       /* peer->call = sip_destroy(peer->call);*/
23672    }
23673 
23674    /* Don't send a devstate change if nothing changed. */
23675    if (peer->lastms > -1) {
23676       peer->lastms = -1;
23677       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
23678    }
23679 
23680    /* Try again quickly */
23681    AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
23682          DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer,
23683          unref_peer(_data, "removing poke peer ref"),
23684          unref_peer(peer, "removing poke peer ref"),
23685          ref_peer(peer, "adding poke peer ref"));
23686 
23687    /* Release the ref held by the running scheduler entry */
23688    unref_peer(peer, "release peer poke noanswer ref");
23689 
23690    return 0;
23691 }
23692 
23693 /*! \brief Check availability of peer, also keep NAT open
23694 \note This is done with 60 seconds between each ping,
23695    unless forced by cli or manager. If peer is unreachable,
23696    we check every 10th second by default. 
23697 */
23698 static int sip_poke_peer(struct sip_peer *peer, int force)
23699 {
23700    struct sip_pvt *p;
23701    int xmitres = 0;
23702    
23703    if ((!peer->maxms && !force) || !peer->addr.sin_addr.s_addr) {
23704       /* IF we have no IP, or this isn't to be monitored, return
23705         immediately after clearing things out */
23706       AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
23707             unref_peer(peer, "removing poke peer ref"));
23708       
23709       peer->lastms = 0;
23710       if (peer->call) {
23711          peer->call = dialog_unref(peer->call, "unref dialog peer->call");
23712       }
23713       return 0;
23714    }
23715    if (peer->call) {
23716       if (sipdebug) {
23717          ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
23718       }
23719       dialog_unlink_all(peer->call, TRUE, TRUE);
23720       peer->call = dialog_unref(peer->call, "unref dialog peer->call");
23721       /* peer->call = sip_destroy(peer->call); */
23722    }
23723    if (!(p = sip_alloc(NULL, NULL, 0, SIP_OPTIONS, NULL))) {
23724       return -1;
23725    }
23726    peer->call = dialog_ref(p, "copy sip alloc from p to peer->call");
23727    
23728    p->sa = peer->addr;
23729    p->recv = peer->addr;
23730    copy_socket_data(&p->socket, &peer->socket);
23731    ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
23732    ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
23733 
23734    /* Send OPTIONs to peer's fullcontact */
23735    if (!ast_strlen_zero(peer->fullcontact))
23736       ast_string_field_set(p, fullcontact, peer->fullcontact);
23737 
23738    if (!ast_strlen_zero(peer->tohost))
23739       ast_string_field_set(p, tohost, peer->tohost);
23740    else
23741       ast_string_field_set(p, tohost, ast_inet_ntoa(peer->addr.sin_addr));
23742 
23743    /* Recalculate our side, and recalculate Call ID */
23744    ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
23745    build_via(p);
23746    ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
23747    build_callid_pvt(p);
23748    ao2_t_link(dialogs, p, "Linking in under new name");
23749 
23750    AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
23751          unref_peer(peer, "removing poke peer ref"));
23752    
23753    if (p->relatedpeer)
23754       p->relatedpeer = unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
23755    p->relatedpeer = ref_peer(peer, "setting the relatedpeer field in the dialog");
23756    ast_set_flag(&p->flags[0], SIP_OUTGOING);
23757 #ifdef VOCAL_DATA_HACK
23758    ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
23759    xmitres = transmit_invite(p, SIP_INVITE, 0, 2); /* sinks the p refcount */
23760 #else
23761    xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2); /* sinks the p refcount */
23762 #endif
23763    peer->ps = ast_tvnow();
23764    if (xmitres == XMIT_ERROR) {
23765       /* Immediately unreachable, network problems */
23766       sip_poke_noanswer(ref_peer(peer, "add ref for peerexpire (fake, for sip_poke_noanswer to remove)"));
23767    } else if (!force) {
23768       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, peer->maxms * 2, sip_poke_noanswer, peer,
23769             unref_peer(_data, "removing poke peer ref"),
23770             unref_peer(peer, "removing poke peer ref"),
23771             ref_peer(peer, "adding poke peer ref"));
23772    }
23773    dialog_unref(p, "unref dialog at end of sip_poke_peer, obtained from sip_alloc, just before it goes out of scope");
23774    return 0;
23775 }
23776 
23777 /*! \brief Part of PBX channel interface
23778 \note
23779 \par  Return values:---
23780 
23781    If we have qualify on and the device is not reachable, regardless of registration
23782    state we return AST_DEVICE_UNAVAILABLE
23783 
23784    For peers with call limit:
23785       - not registered        AST_DEVICE_UNAVAILABLE
23786       - registered, no call         AST_DEVICE_NOT_INUSE
23787       - registered, active calls    AST_DEVICE_INUSE
23788       - registered, call limit reached AST_DEVICE_BUSY
23789       - registered, onhold       AST_DEVICE_ONHOLD
23790       - registered, ringing         AST_DEVICE_RINGING
23791 
23792    For peers without call limit:
23793       - not registered        AST_DEVICE_UNAVAILABLE
23794       - registered            AST_DEVICE_NOT_INUSE
23795       - fixed IP (!dynamic)         AST_DEVICE_NOT_INUSE
23796    
23797    Peers that does not have a known call and can't be reached by OPTIONS
23798       - unreachable           AST_DEVICE_UNAVAILABLE
23799 
23800    If we return AST_DEVICE_UNKNOWN, the device state engine will try to find
23801    out a state by walking the channel list.
23802 
23803    The queue system (\ref app_queue.c) treats a member as "active"
23804    if devicestate is != AST_DEVICE_UNAVAILBALE && != AST_DEVICE_INVALID
23805 
23806    When placing a call to the queue member, queue system sets a member to busy if
23807    != AST_DEVICE_NOT_INUSE and != AST_DEVICE_UNKNOWN
23808 
23809 */
23810 static int sip_devicestate(void *data)
23811 {
23812    char *host;
23813    char *tmp;
23814    struct sip_peer *p;
23815 
23816    int res = AST_DEVICE_INVALID;
23817 
23818    /* make sure data is not null. Maybe unnecessary, but better be safe */
23819    host = ast_strdupa(data ? data : "");
23820    if ((tmp = strchr(host, '@')))
23821       host = tmp + 1;
23822 
23823    ast_debug(3, "Checking device state for peer %s\n", host);
23824 
23825    /* If find_peer asks for a realtime peer, then this breaks rtautoclear.  This
23826     * is because when a peer tries to autoexpire, the last thing it does is to
23827     * queue up an event telling the system that the devicestate has changed
23828     * (presumably to unavailable).  If we ask for a realtime peer here, this would
23829     * load it BACK into memory, thus defeating the point of trying to clear dead
23830     * hosts out of memory.
23831     */
23832    if ((p = find_peer(host, NULL, FALSE, FINDALLDEVICES, TRUE, 0))) {
23833       if (p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) {
23834          /* we have an address for the peer */
23835       
23836          /* Check status in this order
23837             - Hold
23838             - Ringing
23839             - Busy (enforced only by call limit)
23840             - Inuse (we have a call)
23841             - Unreachable (qualify)
23842             If we don't find any of these state, report AST_DEVICE_NOT_INUSE
23843             for registered devices */
23844 
23845          if (p->onHold)
23846             /* First check for hold or ring states */
23847             res = AST_DEVICE_ONHOLD;
23848          else if (p->inRinging) {
23849             if (p->inRinging == p->inUse)
23850                res = AST_DEVICE_RINGING;
23851             else
23852                res = AST_DEVICE_RINGINUSE;
23853          } else if (p->call_limit && (p->inUse == p->call_limit))
23854             /* check call limit */
23855             res = AST_DEVICE_BUSY;
23856          else if (p->call_limit && p->busy_level && p->inUse >= p->busy_level)
23857             /* We're forcing busy before we've reached the call limit */
23858             res = AST_DEVICE_BUSY;
23859          else if (p->call_limit && p->inUse)
23860             /* Not busy, but we do have a call */
23861             res = AST_DEVICE_INUSE;
23862          else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0))) 
23863             /* We don't have a call. Are we reachable at all? Requires qualify= */
23864             res = AST_DEVICE_UNAVAILABLE;
23865          else  /* Default reply if we're registered and have no other data */
23866             res = AST_DEVICE_NOT_INUSE;
23867       } else {
23868          /* there is no address, it's unavailable */
23869          res = AST_DEVICE_UNAVAILABLE;
23870       }
23871       unref_peer(p, "unref_peer, from sip_devicestate, release ref from find_peer");
23872    } else {
23873       res = AST_DEVICE_UNKNOWN;
23874    }
23875 
23876    return res;
23877 }
23878 
23879 /*! \brief PBX interface function -build SIP pvt structure 
23880  * SIP calls initiated by the PBX arrive here. 
23881  *
23882  * \verbatim   
23883  *    SIP Dial string syntax
23884  *    SIP/exten@host!dnid
23885  * or SIP/host/exten!dnid
23886  * or SIP/host!dnid
23887  * \endverbatim
23888 */
23889 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause)
23890 {
23891    struct sip_pvt *p;
23892    struct ast_channel *tmpc = NULL;
23893    char *ext = NULL, *host;
23894    char tmp[256];
23895    char *dest = data;
23896    char *dnid;
23897    char *secret = NULL;
23898    char *md5secret = NULL;
23899    char *authname = NULL;
23900    char *trans = NULL;
23901    enum sip_transport transport = 0;
23902    int oldformat = format;
23903 
23904    /* mask request with some set of allowed formats.
23905     * XXX this needs to be fixed.
23906     * The original code uses AST_FORMAT_AUDIO_MASK, but it is
23907     * unclear what to use here. We have global_capabilities, which is
23908     * configured from sip.conf, and sip_tech.capabilities, which is
23909     * hardwired to all audio formats.
23910     */
23911    format &= AST_FORMAT_AUDIO_MASK;
23912    if (!format) {
23913       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));
23914       *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;   /* Can't find codec to connect to host */
23915       return NULL;
23916    }
23917    ast_debug(1, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));
23918 
23919    if (ast_strlen_zero(dest)) {
23920       ast_log(LOG_ERROR, "Unable to create channel with empty destination.\n");
23921       *cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
23922       return NULL;
23923    }
23924 
23925    if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE, NULL))) {
23926       ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", dest);
23927       *cause = AST_CAUSE_SWITCH_CONGESTION;
23928       return NULL;
23929    }
23930 
23931    p->outgoing_call = TRUE;
23932 
23933    if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
23934       dialog_unlink_all(p, TRUE, TRUE);
23935       dialog_unref(p, "unref dialog p from mem fail");
23936       /* sip_destroy(p); */
23937       ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
23938       *cause = AST_CAUSE_SWITCH_CONGESTION;
23939       return NULL;
23940    }
23941 
23942    /* Save the destination, the SIP dial string */
23943    ast_copy_string(tmp, dest, sizeof(tmp));
23944 
23945 
23946    /* Find DNID and take it away */
23947    dnid = strchr(tmp, '!');
23948    if (dnid != NULL) {
23949       *dnid++ = '\0';
23950       ast_string_field_set(p, todnid, dnid);
23951    }
23952 
23953    /* Find at sign - @ */
23954    host = strchr(tmp, '@');
23955    if (host) {
23956       *host++ = '\0';
23957       ext = tmp;
23958       secret = strchr(ext, ':');
23959    }
23960    if (secret) {
23961       *secret++ = '\0';
23962       md5secret = strchr(secret, ':');
23963    }
23964    if (md5secret) {
23965       *md5secret++ = '\0';
23966       authname = strchr(md5secret, ':');
23967    }
23968    if (authname) {
23969       *authname++ = '\0';
23970       trans = strchr(authname, ':');
23971    }
23972    if (trans) {
23973       *trans++ = '\0';
23974       if (!strcasecmp(trans, "tcp"))
23975          transport = SIP_TRANSPORT_TCP;
23976       else if (!strcasecmp(trans, "tls"))
23977          transport = SIP_TRANSPORT_TLS;
23978       else {
23979          if (strcasecmp(trans, "udp"))
23980             ast_log(LOG_WARNING, "'%s' is not a valid transport option to Dial() for SIP calls, using udp by default.\n", trans);
23981          transport = SIP_TRANSPORT_UDP;
23982       }
23983    } else { /* use default */
23984       transport = SIP_TRANSPORT_UDP;
23985    }
23986 
23987    if (!host) {
23988       ext = strchr(tmp, '/');
23989       if (ext) 
23990          *ext++ = '\0';
23991       host = tmp;
23992    }
23993 
23994    set_socket_transport(&p->socket, transport);
23995 
23996    /* We now have 
23997       host = peer name, DNS host name or DNS domain (for SRV) 
23998       ext = extension (user part of URI)
23999       dnid = destination of the call (applies to the To: header)
24000    */
24001    if (create_addr(p, host, NULL, 1)) {
24002       *cause = AST_CAUSE_UNREGISTERED;
24003       ast_debug(3, "Cant create SIP call - target device not registered\n");
24004       dialog_unlink_all(p, TRUE, TRUE);
24005       dialog_unref(p, "unref dialog p UNREGISTERED");
24006       /* sip_destroy(p); */
24007       return NULL;
24008    }
24009    if (ast_strlen_zero(p->peername) && ext)
24010       ast_string_field_set(p, peername, ext);
24011    /* Recalculate our side, and recalculate Call ID */
24012    ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
24013    build_via(p);
24014    ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
24015    build_callid_pvt(p);
24016    ao2_t_link(dialogs, p, "Linking in under new name");
24017    
24018    /* We have an extension to call, don't use the full contact here */
24019    /* This to enable dialing registered peers with extension dialling,
24020       like SIP/peername/extension   
24021       SIP/peername will still use the full contact 
24022     */
24023    if (ext) {
24024       ast_string_field_set(p, username, ext);
24025       ast_string_field_set(p, fullcontact, NULL);
24026    }
24027    if (secret && !ast_strlen_zero(secret))
24028       ast_string_field_set(p, peersecret, secret);
24029 
24030    if (md5secret && !ast_strlen_zero(md5secret))
24031       ast_string_field_set(p, peermd5secret, md5secret);
24032 
24033    if (authname && !ast_strlen_zero(authname))
24034       ast_string_field_set(p, authname, authname);
24035 #if 0
24036    printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
24037 #endif
24038    p->prefcodec = oldformat;           /* Format for this call */
24039    p->jointcapability = oldformat & p->capability;
24040    sip_pvt_lock(p);
24041    tmpc = sip_new(p, AST_STATE_DOWN, host);  /* Place the call */
24042    if (sip_cfg.callevents)
24043       manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
24044          "Channel: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
24045          p->owner? p->owner->name : "", "SIP", p->callid, p->fullcontact, p->peername);
24046    sip_pvt_unlock(p);
24047    if (!tmpc) {
24048       dialog_unlink_all(p, TRUE, TRUE);
24049       /* sip_destroy(p); */
24050    }
24051    dialog_unref(p, "toss pvt ptr at end of sip_request_call");
24052    ast_update_use_count();
24053    restart_monitor();
24054    return tmpc;
24055 }
24056 
24057 /*! \brief Parse insecure= setting in sip.conf and set flags according to setting */
24058 static void set_insecure_flags (struct ast_flags *flags, const char *value, int lineno)
24059 {
24060    if (ast_strlen_zero(value))
24061       return;
24062 
24063    if (!ast_false(value)) {
24064       char buf[64];
24065       char *word, *next;
24066 
24067       ast_copy_string(buf, value, sizeof(buf));
24068       next = buf;
24069       while ((word = strsep(&next, ","))) {
24070          if (!strcasecmp(word, "port"))
24071             ast_set_flag(&flags[0], SIP_INSECURE_PORT);
24072          else if (!strcasecmp(word, "invite"))
24073             ast_set_flag(&flags[0], SIP_INSECURE_INVITE);
24074          else
24075             ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
24076       }
24077    }
24078 }
24079 
24080 /*!
24081   \brief Handle T.38 configuration options common to users and peers
24082   \returns non-zero if any config options were handled, zero otherwise
24083 */
24084 static int handle_t38_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v,
24085                int *maxdatagram)
24086 {
24087    int res = 1;
24088 
24089    if (!strcasecmp(v->name, "t38pt_udptl")) {
24090       char *buf = ast_strdupa(v->value);
24091       char *word, *next = buf;
24092 
24093       ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT);
24094 
24095       while ((word = strsep(&next, ","))) {
24096          if (ast_true(word) || !strcasecmp(word, "fec")) {
24097             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
24098             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_FEC);
24099          } else if (!strcasecmp(word, "redundancy")) {
24100             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
24101             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY);
24102          } else if (!strcasecmp(word, "none")) {
24103             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
24104             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
24105          } else if (!strncasecmp(word, "maxdatagram=", 12)) {
24106             if (sscanf(&word[12], "%30u", maxdatagram) != 1) {
24107                ast_log(LOG_WARNING, "Invalid maxdatagram '%s' at line %d of %s\n", v->value, v->lineno, config);
24108                *maxdatagram = global_t38_maxdatagram;
24109             }
24110          }
24111       }
24112    } else if (!strcasecmp(v->name, "t38pt_usertpsource")) {
24113       ast_set_flag(&mask[1], SIP_PAGE2_UDPTL_DESTINATION);
24114       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_UDPTL_DESTINATION);
24115    } else if (!strcasecmp(v->name, "forwardloopdetected")) {
24116       ast_set_flag(&mask[1], SIP_PAGE2_FORWARD_LOOP_DETECTED);
24117       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_FORWARD_LOOP_DETECTED);
24118    } else {
24119       res = 0;
24120    }
24121 
24122    return res;
24123 }
24124 
24125 /*!
24126   \brief Handle flag-type options common to configuration of devices - peers
24127   \param flags array of two struct ast_flags
24128   \param mask array of two struct ast_flags
24129   \param v linked list of config variables to process
24130   \returns non-zero if any config options were handled, zero otherwise
24131 */
24132 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
24133 {
24134    int res = 1;
24135 
24136    if (!strcasecmp(v->name, "trustrpid")) {
24137       ast_set_flag(&mask[0], SIP_TRUSTRPID);
24138       ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
24139    } else if (!strcasecmp(v->name, "sendrpid")) {
24140       ast_set_flag(&mask[0], SIP_SENDRPID);
24141       ast_set2_flag(&flags[0], ast_true(v->value), SIP_SENDRPID);
24142    } else if (!strcasecmp(v->name, "g726nonstandard")) {
24143       ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
24144       ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
24145    } else if (!strcasecmp(v->name, "useclientcode")) {
24146       ast_set_flag(&mask[0], SIP_USECLIENTCODE);
24147       ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
24148    } else if (!strcasecmp(v->name, "dtmfmode")) {
24149       ast_set_flag(&mask[0], SIP_DTMF);
24150       ast_clear_flag(&flags[0], SIP_DTMF);
24151       if (!strcasecmp(v->value, "inband"))
24152          ast_set_flag(&flags[0], SIP_DTMF_INBAND);
24153       else if (!strcasecmp(v->value, "rfc2833"))
24154          ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
24155       else if (!strcasecmp(v->value, "info"))
24156          ast_set_flag(&flags[0], SIP_DTMF_INFO);
24157       else if (!strcasecmp(v->value, "shortinfo"))
24158          ast_set_flag(&flags[0], SIP_DTMF_SHORTINFO);
24159       else if (!strcasecmp(v->value, "auto"))
24160          ast_set_flag(&flags[0], SIP_DTMF_AUTO);
24161       else {
24162          ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
24163          ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
24164       }
24165    } else if (!strcasecmp(v->name, "nat")) {
24166       ast_set_flag(&mask[0], SIP_NAT);
24167       ast_clear_flag(&flags[0], SIP_NAT);
24168       if (!strcasecmp(v->value, "never"))
24169          ast_set_flag(&flags[0], SIP_NAT_NEVER);
24170       else if (!strcasecmp(v->value, "route"))
24171          ast_set_flag(&flags[0], SIP_NAT_ROUTE);
24172       else if (ast_true(v->value))
24173          ast_set_flag(&flags[0], SIP_NAT_ALWAYS);
24174       else
24175          ast_set_flag(&flags[0], SIP_NAT_RFC3581);
24176    } else if (!strcasecmp(v->name, "directmedia") || !strcasecmp(v->name, "canreinvite")) {
24177       ast_set_flag(&mask[0], SIP_REINVITE);
24178       ast_clear_flag(&flags[0], SIP_REINVITE);
24179       if (ast_true(v->value)) {
24180          ast_set_flag(&flags[0], SIP_DIRECT_MEDIA | SIP_DIRECT_MEDIA_NAT);
24181       } else if (!ast_false(v->value)) {
24182          char buf[64];
24183          char *word, *next = buf;
24184 
24185          ast_copy_string(buf, v->value, sizeof(buf));
24186          while ((word = strsep(&next, ","))) {
24187             if (!strcasecmp(word, "update")) {
24188                ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_DIRECT_MEDIA);
24189             } else if (!strcasecmp(word, "nonat")) {
24190                ast_set_flag(&flags[0], SIP_DIRECT_MEDIA);
24191                ast_clear_flag(&flags[0], SIP_DIRECT_MEDIA_NAT);
24192             } else {
24193                ast_log(LOG_WARNING, "Unknown directmedia mode '%s' on line %d\n", v->value, v->lineno);
24194             }
24195          }
24196       }
24197    } else if (!strcasecmp(v->name, "insecure")) {
24198       ast_set_flag(&mask[0], SIP_INSECURE);
24199       ast_clear_flag(&flags[0], SIP_INSECURE);
24200       set_insecure_flags(&flags[0], v->value, v->lineno);   
24201    } else if (!strcasecmp(v->name, "progressinband")) {
24202       ast_set_flag(&mask[0], SIP_PROG_INBAND);
24203       ast_clear_flag(&flags[0], SIP_PROG_INBAND);
24204       if (ast_true(v->value))
24205          ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
24206       else if (strcasecmp(v->value, "never"))
24207          ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
24208    } else if (!strcasecmp(v->name, "promiscredir")) {
24209       ast_set_flag(&mask[0], SIP_PROMISCREDIR);
24210       ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
24211    } else if (!strcasecmp(v->name, "videosupport")) {
24212       if (!strcasecmp(v->value, "always")) {
24213          ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
24214          ast_set_flag(&flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
24215       } else {
24216          ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
24217          ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
24218       }
24219    } else if (!strcasecmp(v->name, "textsupport")) {
24220       ast_set_flag(&mask[1], SIP_PAGE2_TEXTSUPPORT);
24221       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_TEXTSUPPORT);
24222       res = 1;
24223    } else if (!strcasecmp(v->name, "allowoverlap")) {
24224       ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
24225       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWOVERLAP);
24226    } else if (!strcasecmp(v->name, "allowsubscribe")) {
24227       ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
24228       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
24229    } else if (!strcasecmp(v->name, "ignoresdpversion")) {
24230       ast_set_flag(&mask[1], SIP_PAGE2_IGNORESDPVERSION);
24231       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_IGNORESDPVERSION);
24232    } else if (!strcasecmp(v->name, "faxdetect")) {
24233       ast_set_flag(&mask[1], SIP_PAGE2_FAX_DETECT);
24234       if (ast_true(v->value)) {
24235          ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
24236       } else if (ast_false(v->value)) {
24237          ast_clear_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
24238       } else {
24239          char *buf = ast_strdupa(v->value);
24240          char *word, *next = buf;
24241 
24242          while ((word = strsep(&next, ","))) {
24243             if (!strcasecmp(word, "cng")) {
24244                ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_CNG);
24245             } else if (!strcasecmp(word, "t38")) {
24246                ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_T38);
24247             } else {
24248                ast_log(LOG_WARNING, "Unknown faxdetect mode '%s' on line %d.\n", word, v->lineno);
24249             }
24250          }
24251       }
24252    } else if (!strcasecmp(v->name, "rfc2833compensate")) {
24253       ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
24254       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
24255    } else if (!strcasecmp(v->name, "buggymwi")) {
24256       ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
24257       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
24258    } else
24259       res = 0;
24260 
24261    return res;
24262 }
24263 
24264 /*! \brief Add SIP domain to list of domains we are responsible for */
24265 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
24266 {
24267    struct domain *d;
24268 
24269    if (ast_strlen_zero(domain)) {
24270       ast_log(LOG_WARNING, "Zero length domain.\n");
24271       return 1;
24272    }
24273 
24274    if (!(d = ast_calloc(1, sizeof(*d))))
24275       return 0;
24276 
24277    ast_copy_string(d->domain, domain, sizeof(d->domain));
24278 
24279    if (!ast_strlen_zero(context))
24280       ast_copy_string(d->context, context, sizeof(d->context));
24281 
24282    d->mode = mode;
24283 
24284    AST_LIST_LOCK(&domain_list);
24285    AST_LIST_INSERT_TAIL(&domain_list, d, list);
24286    AST_LIST_UNLOCK(&domain_list);
24287 
24288    if (sipdebug)  
24289       ast_debug(1, "Added local SIP domain '%s'\n", domain);
24290 
24291    return 1;
24292 }
24293 
24294 /*! \brief  check_sip_domain: Check if domain part of uri is local to our server */
24295 static int check_sip_domain(const char *domain, char *context, size_t len)
24296 {
24297    struct domain *d;
24298    int result = 0;
24299 
24300    AST_LIST_LOCK(&domain_list);
24301    AST_LIST_TRAVERSE(&domain_list, d, list) {
24302       if (strcasecmp(d->domain, domain))
24303          continue;
24304 
24305       if (len && !ast_strlen_zero(d->context))
24306          ast_copy_string(context, d->context, len);
24307       
24308       result = 1;
24309       break;
24310    }
24311    AST_LIST_UNLOCK(&domain_list);
24312 
24313    return result;
24314 }
24315 
24316 /*! \brief Clear our domain list (at reload) */
24317 static void clear_sip_domains(void)
24318 {
24319    struct domain *d;
24320 
24321    AST_LIST_LOCK(&domain_list);
24322    while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
24323       ast_free(d);
24324    AST_LIST_UNLOCK(&domain_list);
24325 }
24326 
24327 
24328 /*! \brief Add realm authentication in list */
24329 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno)
24330 {
24331    char authcopy[256];
24332    char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
24333    struct sip_auth *a, *b, *auth;
24334 
24335    if (ast_strlen_zero(configuration))
24336       return authlist;
24337 
24338    ast_debug(1, "Auth config ::  %s\n", configuration);
24339 
24340    ast_copy_string(authcopy, configuration, sizeof(authcopy));
24341    username = authcopy;
24342 
24343    /* split user[:secret] and relm */
24344    realm = strrchr(username, '@');
24345    if (realm)
24346       *realm++ = '\0';
24347    if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
24348       ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
24349       return authlist;
24350    }
24351 
24352    /* parse username at ':' for secret, or '#" for md5secret */
24353    if ((secret = strchr(username, ':'))) {
24354       *secret++ = '\0';
24355    } else if ((md5secret = strchr(username, '#'))) {
24356       *md5secret++ = '\0';
24357    }
24358 
24359    if (!(auth = ast_calloc(1, sizeof(*auth))))
24360       return authlist;
24361 
24362    ast_copy_string(auth->realm, realm, sizeof(auth->realm));
24363    ast_copy_string(auth->username, username, sizeof(auth->username));
24364    if (secret)
24365       ast_copy_string(auth->secret, secret, sizeof(auth->secret));
24366    if (md5secret)
24367       ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
24368 
24369    /* find the end of the list */
24370    for (b = NULL, a = authlist; a ; b = a, a = a->next)
24371       ;
24372    if (b)
24373       b->next = auth;   /* Add structure add end of list */
24374    else
24375       authlist = auth;
24376 
24377    ast_verb(3, "Added authentication for realm %s\n", realm);
24378 
24379    return authlist;
24380 
24381 }
24382 
24383 /*! \brief Clear realm authentication list (at reload) */
24384 static int clear_realm_authentication(struct sip_auth *authlist)
24385 {
24386    struct sip_auth *a = authlist;
24387    struct sip_auth *b;
24388 
24389    while (a) {
24390       b = a;
24391       a = a->next;
24392       ast_free(b);
24393    }
24394 
24395    return 1;
24396 }
24397 
24398 /*! \brief Find authentication for a specific realm */
24399 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm)
24400 {
24401    struct sip_auth *a;
24402 
24403    for (a = authlist; a; a = a->next) {
24404       if (!strcasecmp(a->realm, realm))
24405          break;
24406    }
24407 
24408    return a;
24409 }
24410 
24411 /*! \brief
24412  * implement the setvar config line
24413  */
24414 static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
24415 {
24416    struct ast_variable *tmpvar = NULL;
24417    char *varname = ast_strdupa(buf), *varval = NULL;
24418    
24419    if ((varval = strchr(varname, '='))) {
24420       *varval++ = '\0';
24421       if ((tmpvar = ast_variable_new(varname, varval, ""))) {
24422          tmpvar->next = list;
24423          list = tmpvar;
24424       }
24425    }
24426    return list;
24427 }
24428 
24429 /*! \brief Set peer defaults before configuring specific configurations */
24430 static void set_peer_defaults(struct sip_peer *peer)
24431 {
24432    if (peer->expire == 0) {
24433       /* Don't reset expire or port time during reload 
24434          if we have an active registration 
24435       */
24436       peer->expire = -1;
24437       peer->pokeexpire = -1;
24438       peer->addr.sin_port = htons(STANDARD_SIP_PORT);
24439       set_socket_transport(&peer->socket, SIP_TRANSPORT_UDP);
24440    }
24441    peer->type = SIP_TYPE_PEER;
24442    ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
24443    ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
24444    ast_string_field_set(peer, context, sip_cfg.default_context);
24445    ast_string_field_set(peer, subscribecontext, sip_cfg.default_subscribecontext);
24446    ast_string_field_set(peer, language, default_language);
24447    ast_string_field_set(peer, mohinterpret, default_mohinterpret);
24448    ast_string_field_set(peer, mohsuggest, default_mohsuggest);
24449    peer->addr.sin_family = AF_INET;
24450    peer->defaddr.sin_family = AF_INET;
24451    peer->capability = global_capability;
24452    peer->maxcallbitrate = default_maxcallbitrate;
24453    peer->rtptimeout = global_rtptimeout;
24454    peer->rtpholdtimeout = global_rtpholdtimeout;
24455    peer->rtpkeepalive = global_rtpkeepalive;
24456    peer->allowtransfer = sip_cfg.allowtransfer;
24457    peer->autoframing = global_autoframing;
24458    peer->t38_maxdatagram = global_t38_maxdatagram;
24459    peer->qualifyfreq = global_qualifyfreq;
24460    if (global_callcounter)
24461       peer->call_limit=INT_MAX;
24462    ast_string_field_set(peer, vmexten, default_vmexten);
24463    ast_string_field_set(peer, secret, "");
24464    ast_string_field_set(peer, remotesecret, "");
24465    ast_string_field_set(peer, md5secret, "");
24466    ast_string_field_set(peer, cid_num, "");
24467    ast_string_field_set(peer, cid_name, "");
24468    ast_string_field_set(peer, fromdomain, "");
24469    ast_string_field_set(peer, fromuser, "");
24470    ast_string_field_set(peer, regexten, "");
24471    peer->callgroup = 0;
24472    peer->pickupgroup = 0;
24473    peer->maxms = default_qualify;
24474    peer->prefs = default_prefs;
24475    peer->stimer.st_mode_oper = global_st_mode;  /* Session-Timers */
24476    peer->stimer.st_ref = global_st_refresher;
24477    peer->stimer.st_min_se = global_min_se;
24478    peer->stimer.st_max_se = global_max_se;
24479    peer->timer_t1 = global_t1;
24480    peer->timer_b = global_timer_b;
24481    clear_peer_mailboxes(peer);
24482    peer->transports = default_transports;
24483    peer->default_outbound_transport = default_primary_transport;
24484 }
24485 
24486 /*! \brief Create temporary peer (used in autocreatepeer mode) */
24487 static struct sip_peer *temp_peer(const char *name)
24488 {
24489    struct sip_peer *peer;
24490 
24491    if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
24492       return NULL;
24493 
24494    if (ast_string_field_init(peer, 512)) {
24495       ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
24496       return NULL;
24497    }
24498 
24499    ast_atomic_fetchadd_int(&apeerobjs, 1);
24500    set_peer_defaults(peer);
24501 
24502    ast_copy_string(peer->name, name, sizeof(peer->name));
24503 
24504    peer->selfdestruct = TRUE;
24505    peer->host_dynamic = TRUE;
24506    peer->prefs = default_prefs;
24507    reg_source_db(peer);
24508 
24509    return peer;
24510 }
24511 
24512 /*! \todo document this function */
24513 static void add_peer_mailboxes(struct sip_peer *peer, const char *value)
24514 {
24515    char *next, *mbox, *context;
24516 
24517    next = ast_strdupa(value);
24518 
24519    while ((mbox = context = strsep(&next, ","))) {
24520       struct sip_mailbox *mailbox;
24521       int duplicate = 0;
24522 
24523       strsep(&context, "@");
24524 
24525       if (ast_strlen_zero(mbox)) {
24526          continue;
24527       }
24528 
24529       /* Check whether the mailbox is already in the list */
24530       AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
24531          if (!strcmp(mailbox->mailbox, mbox) && !strcmp(S_OR(mailbox->context, ""), S_OR(context, ""))) {
24532             duplicate = 1;
24533             break;
24534          }
24535       }
24536       if (duplicate) {
24537          continue;
24538       }
24539 
24540       if (!(mailbox = ast_calloc(1, sizeof(*mailbox)))) {
24541          continue;
24542       }
24543 
24544       mailbox->mailbox = ast_strdup(mbox);
24545       mailbox->context = ast_strdup(context);
24546 
24547       AST_LIST_INSERT_TAIL(&peer->mailboxes, mailbox, entry);
24548    }
24549 }
24550 
24551 /*! \brief Build peer from configuration (file or realtime static/dynamic) */
24552 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only)
24553 {
24554    struct sip_peer *peer = NULL;
24555    struct ast_ha *oldha = NULL;
24556    int found = 0;
24557    int firstpass = 1;
24558    uint16_t port = 0;
24559    int format = 0;      /* Ama flags */
24560    time_t regseconds = 0;
24561    struct ast_flags peerflags[2] = {{(0)}};
24562    struct ast_flags mask[2] = {{(0)}};
24563    char callback[256] = "";
24564    struct sip_peer tmp_peer;
24565    const char *srvlookup = NULL;
24566    static int deprecation_warning = 1;
24567    int alt_fullcontact = alt ? 1 : 0;
24568    struct ast_str *fullcontact = ast_str_alloca(512);
24569 
24570    if (!realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
24571       /* Note we do NOT use find_peer here, to avoid realtime recursion */
24572       /* We also use a case-sensitive comparison (unlike find_peer) so
24573          that case changes made to the peer name will be properly handled
24574          during reload
24575       */
24576       ast_copy_string(tmp_peer.name, name, sizeof(tmp_peer.name));
24577       peer = ao2_t_find(peers, &tmp_peer, OBJ_POINTER | OBJ_UNLINK, "find and unlink peer from peers table");
24578    }
24579 
24580    if (peer) {
24581       /* Already in the list, remove it and it will be added back (or FREE'd)  */
24582       found++;
24583       if (!(peer->the_mark))
24584          firstpass = 0;
24585    } else {
24586       if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
24587          return NULL;
24588 
24589       if (ast_string_field_init(peer, 512)) {
24590          ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
24591          return NULL;
24592       }
24593 
24594       if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
24595          ast_atomic_fetchadd_int(&rpeerobjs, 1);
24596          ast_debug(3, "-REALTIME- peer built. Name: %s. Peer objects: %d\n", name, rpeerobjs);
24597       } else
24598          ast_atomic_fetchadd_int(&speerobjs, 1);
24599    }
24600 
24601    /* Note that our peer HAS had its reference count increased */
24602    if (firstpass) {
24603       peer->lastmsgssent = -1;
24604       oldha = peer->ha;
24605       peer->ha = NULL;
24606       set_peer_defaults(peer);   /* Set peer defaults */
24607       peer->type = 0;
24608    }
24609    if (!found && name)
24610       ast_copy_string(peer->name, name, sizeof(peer->name));
24611 
24612    /* If we have channel variables, remove them (reload) */
24613    if (peer->chanvars) {
24614       ast_variables_destroy(peer->chanvars);
24615       peer->chanvars = NULL;
24616       /* XXX should unregister ? */
24617    }
24618 
24619    if (found)
24620       peer->portinuri = 0;
24621 
24622    /* If we have realm authentication information, remove them (reload) */
24623    clear_realm_authentication(peer->auth);
24624    peer->auth = NULL;
24625    /* clear the transport information.  We will detect if a default value is required after parsing the config */
24626    peer->default_outbound_transport = 0;
24627    peer->transports = 0;
24628 
24629    if (!devstate_only) {
24630       struct sip_mailbox *mailbox;
24631       AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
24632          mailbox->delme = 1;
24633       }
24634    }
24635 
24636    for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
24637       if (!devstate_only) {
24638          if (handle_common_options(&peerflags[0], &mask[0], v)) {
24639             continue;
24640          }
24641          if (handle_t38_options(&peerflags[0], &mask[0], v, &peer->t38_maxdatagram)) {
24642             continue;
24643          }
24644          if (!strcasecmp(v->name, "transport") && !ast_strlen_zero(v->value)) {
24645             char *val = ast_strdupa(v->value);
24646             char *trans;
24647 
24648             while ((trans = strsep(&val, ","))) {
24649                trans = ast_skip_blanks(trans);
24650 
24651                if (!strncasecmp(trans, "udp", 3)) {
24652                   peer->transports |= SIP_TRANSPORT_UDP;
24653                } else if (!strncasecmp(trans, "tcp", 3)) {
24654                   peer->transports |= SIP_TRANSPORT_TCP;
24655                } else if (!strncasecmp(trans, "tls", 3)) {
24656                   peer->transports |= SIP_TRANSPORT_TLS;
24657                } else {
24658                   ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
24659                }
24660 
24661                if (!peer->default_outbound_transport) { /*!< The first transport listed should be default outbound */
24662                   peer->default_outbound_transport = peer->transports;
24663                }
24664             }
24665          } else if (realtime && !strcasecmp(v->name, "regseconds")) {
24666             ast_get_time_t(v->value, &regseconds, 0, NULL);
24667          } else if (realtime && !strcasecmp(v->name, "name")) {
24668             ast_copy_string(peer->name, v->value, sizeof(peer->name));
24669          } else if (realtime && !strcasecmp(v->name, "useragent")) {
24670             ast_string_field_set(peer, useragent, v->value);
24671          } else if (!strcasecmp(v->name, "type")) {
24672             if (!strcasecmp(v->value, "peer")) {
24673                peer->type |= SIP_TYPE_PEER;
24674             } else if (!strcasecmp(v->value, "user")) {
24675                peer->type |= SIP_TYPE_USER;
24676             } else if (!strcasecmp(v->value, "friend")) {
24677                peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
24678             }
24679          } else if (!strcasecmp(v->name, "remotesecret")) {
24680             ast_string_field_set(peer, remotesecret, v->value);
24681          } else if (!strcasecmp(v->name, "secret")) {
24682             ast_string_field_set(peer, secret, v->value);
24683          } else if (!strcasecmp(v->name, "md5secret")) {
24684             ast_string_field_set(peer, md5secret, v->value);
24685          } else if (!strcasecmp(v->name, "auth")) {
24686             peer->auth = add_realm_authentication(peer->auth, v->value, v->lineno);
24687          } else if (!strcasecmp(v->name, "callerid")) {
24688             char cid_name[80] = { '\0' }, cid_num[80] = { '\0' };
24689 
24690             ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
24691             ast_string_field_set(peer, cid_name, cid_name);
24692             ast_string_field_set(peer, cid_num, cid_num);
24693          } else if (!strcasecmp(v->name, "fullname")) {
24694             ast_string_field_set(peer, cid_name, v->value);
24695          } else if (!strcasecmp(v->name, "trunkname")) {
24696             /* This is actually for a trunk, so we don't want to override callerid */
24697             ast_string_field_set(peer, cid_name, "");
24698          } else if (!strcasecmp(v->name, "cid_number")) {
24699             ast_string_field_set(peer, cid_num, v->value);
24700          } else if (!strcasecmp(v->name, "context")) {
24701             ast_string_field_set(peer, context, v->value);
24702             ast_set_flag(&peer->flags[1], SIP_PAGE2_HAVEPEERCONTEXT);
24703          } else if (!strcasecmp(v->name, "subscribecontext")) {
24704             ast_string_field_set(peer, subscribecontext, v->value);
24705          } else if (!strcasecmp(v->name, "fromdomain")) {
24706             ast_string_field_set(peer, fromdomain, v->value);
24707          } else if (!strcasecmp(v->name, "usereqphone")) {
24708             ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
24709          } else if (!strcasecmp(v->name, "fromuser")) {
24710             ast_string_field_set(peer, fromuser, v->value);
24711          } else if (!strcasecmp(v->name, "outboundproxy")) {
24712             char *port, *next, *force, *proxyname;
24713             int forceopt = FALSE;
24714             /* Set peer channel variable */
24715             next = proxyname = ast_strdupa(v->value);
24716             if ((port = strchr(proxyname, ':'))) {
24717                *port++ = '\0';
24718                next = port;
24719             }
24720             if ((force = strchr(next, ','))) {
24721                *force++ = '\0';
24722                forceopt = strcmp(force, "force");
24723             }
24724             /* Allocate proxy object */
24725             peer->outboundproxy = proxy_allocate(proxyname, port, forceopt);
24726          } else if (!strcasecmp(v->name, "host")) {
24727             if (!strcasecmp(v->value, "dynamic")) {
24728                /* They'll register with us */
24729                if (!found || !peer->host_dynamic) {
24730                   /* Initialize stuff if this is a new peer, or if it used to
24731                    * not be dynamic before the reload. */
24732                   memset(&peer->addr.sin_addr, 0, 4);
24733                   peer->addr.sin_port = 0;
24734                }
24735                peer->host_dynamic = TRUE;
24736             } else {
24737                /* Non-dynamic.  Make sure we become that way if we're not */
24738                AST_SCHED_DEL_UNREF(sched, peer->expire,
24739                      unref_peer(peer, "removing register expire ref"));
24740                /* the port will either be set to a default value or a config specified value once all option parsing is complete */
24741                peer->addr.sin_port = 0;
24742                peer->host_dynamic = FALSE;
24743                srvlookup = v->value;
24744             }
24745          } else if (!strcasecmp(v->name, "defaultip")) {
24746             if (!ast_strlen_zero(v->value) && ast_get_ip(&peer->defaddr, v->value)) {
24747                unref_peer(peer, "unref_peer: from build_peer defaultip");
24748                return NULL;
24749             }
24750          } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
24751             int ha_error = 0;
24752             if (!ast_strlen_zero(v->value)) {
24753                peer->ha = ast_append_ha(v->name, v->value, peer->ha, &ha_error);
24754             }
24755             if (ha_error) {
24756                ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
24757             }
24758          } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
24759             int ha_error = 0;
24760             if (!ast_strlen_zero(v->value)) {
24761                peer->contactha = ast_append_ha(v->name + 7, v->value, peer->contactha, &ha_error);
24762             }
24763             if (ha_error) {
24764                ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
24765             }
24766          } else if (!strcasecmp(v->name, "port")) {
24767             peer->portinuri = 1;
24768             if (!(port = port_str2int(v->value, 0))) {
24769                if (realtime) {
24770                   /* If stored as integer, could be 0 for some DBs (notably MySQL) */
24771                   peer->portinuri = 0;
24772                } else {
24773                   ast_log(LOG_WARNING, "Invalid peer port configuration at line %d : %s\n", v->lineno, v->value);
24774                }
24775             }
24776          } else if (!strcasecmp(v->name, "callingpres")) {
24777             peer->callingpres = ast_parse_caller_presentation(v->value);
24778             if (peer->callingpres == -1) {
24779                peer->callingpres = atoi(v->value);
24780             }
24781          } else if (!strcasecmp(v->name, "username") || !strcmp(v->name, "defaultuser")) {   /* "username" is deprecated */
24782             ast_string_field_set(peer, username, v->value);
24783             if (!strcasecmp(v->name, "username")) {
24784                if (deprecation_warning) {
24785                   ast_log(LOG_NOTICE, "The 'username' field for sip peers has been deprecated in favor of the term 'defaultuser'\n");
24786                   deprecation_warning = 0;
24787                }
24788                peer->deprecated_username = 1;
24789             }
24790          } else if (!strcasecmp(v->name, "language")) {
24791             ast_string_field_set(peer, language, v->value);
24792          } else if (!strcasecmp(v->name, "regexten")) {
24793             ast_string_field_set(peer, regexten, v->value);
24794          } else if (!strcasecmp(v->name, "callbackextension")) {
24795             ast_copy_string(callback, v->value, sizeof(callback));
24796          } else if (!strcasecmp(v->name, "amaflags")) {
24797             format = ast_cdr_amaflags2int(v->value);
24798             if (format < 0) {
24799                ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
24800             } else {
24801                peer->amaflags = format;
24802             }
24803          } else if (!strcasecmp(v->name, "accountcode")) {
24804             ast_string_field_set(peer, accountcode, v->value);
24805          } else if (!strcasecmp(v->name, "mohinterpret")) {
24806             ast_string_field_set(peer, mohinterpret, v->value);
24807          } else if (!strcasecmp(v->name, "mohsuggest")) {
24808             ast_string_field_set(peer, mohsuggest, v->value);
24809          } else if (!strcasecmp(v->name, "parkinglot")) {
24810             ast_string_field_set(peer, parkinglot, v->value);
24811          } else if (!strcasecmp(v->name, "mailbox")) {
24812             add_peer_mailboxes(peer, v->value);
24813          } else if (!strcasecmp(v->name, "hasvoicemail")) {
24814             /* People expect that if 'hasvoicemail' is set, that the mailbox will
24815              * be also set, even if not explicitly specified. */
24816             if (ast_true(v->value) && AST_LIST_EMPTY(&peer->mailboxes)) {
24817                add_peer_mailboxes(peer, name);
24818             }
24819          } else if (!strcasecmp(v->name, "subscribemwi")) {
24820             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
24821          } else if (!strcasecmp(v->name, "vmexten")) {
24822             ast_string_field_set(peer, vmexten, v->value);
24823          } else if (!strcasecmp(v->name, "callgroup")) {
24824             peer->callgroup = ast_get_group(v->value);
24825          } else if (!strcasecmp(v->name, "allowtransfer")) {
24826             peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
24827          } else if (!strcasecmp(v->name, "pickupgroup")) {
24828             peer->pickupgroup = ast_get_group(v->value);
24829          } else if (!strcasecmp(v->name, "allow")) {
24830             int error =  ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, TRUE);
24831             if (error) {
24832                ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
24833             }
24834          } else if (!strcasecmp(v->name, "disallow")) {
24835             int error =  ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, FALSE);
24836             if (error) {
24837                ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
24838             }
24839          } else if (!strcasecmp(v->name, "registertrying")) {
24840             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_REGISTERTRYING);
24841          } else if (!strcasecmp(v->name, "autoframing")) {
24842             peer->autoframing = ast_true(v->value);
24843          } else if (!strcasecmp(v->name, "rtptimeout")) {
24844             if ((sscanf(v->value, "%30d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
24845                ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
24846                peer->rtptimeout = global_rtptimeout;
24847             }
24848          } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
24849             if ((sscanf(v->value, "%30d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
24850                ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
24851                peer->rtpholdtimeout = global_rtpholdtimeout;
24852             }
24853          } else if (!strcasecmp(v->name, "rtpkeepalive")) {
24854             if ((sscanf(v->value, "%30d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
24855                ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d.  Using default.\n", v->value, v->lineno);
24856                peer->rtpkeepalive = global_rtpkeepalive;
24857             }
24858          } else if (!strcasecmp(v->name, "timert1")) {
24859             if ((sscanf(v->value, "%30d", &peer->timer_t1) != 1) || (peer->timer_t1 < 0)) {
24860                ast_log(LOG_WARNING, "'%s' is not a valid T1 time at line %d.  Using default.\n", v->value, v->lineno);
24861                peer->timer_t1 = global_t1;
24862             }
24863             /* Note that Timer B is dependent upon T1 and MUST NOT be lower
24864              * than T1 * 64, according to RFC 3261, Section 17.1.1.2 */
24865             if (peer->timer_b < peer->timer_t1 * 64) {
24866                peer->timer_b = peer->timer_t1 * 64;
24867             }
24868          } else if (!strcasecmp(v->name, "timerb")) {
24869             if ((sscanf(v->value, "%30d", &peer->timer_b) != 1) || (peer->timer_b < 0)) {
24870                ast_log(LOG_WARNING, "'%s' is not a valid Timer B time at line %d.  Using default.\n", v->value, v->lineno);
24871                peer->timer_b = global_timer_b;
24872             }
24873             if (peer->timer_b < peer->timer_t1 * 64) {
24874                static int warning = 0;
24875                if (warning++ % 20 == 0) {
24876                   ast_log(LOG_WARNING, "Timer B has been set lower than recommended. (RFC 3261, 17.1.1.2)\n");
24877                }
24878             }
24879          } else if (!strcasecmp(v->name, "setvar")) {
24880             peer->chanvars = add_var(v->value, peer->chanvars);
24881          } else if (!strcasecmp(v->name, "qualifyfreq")) {
24882             int i;
24883             if (sscanf(v->value, "%30d", &i) == 1) {
24884                peer->qualifyfreq = i * 1000;
24885             } else {
24886                ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
24887                peer->qualifyfreq = global_qualifyfreq;
24888             }
24889          } else if (!strcasecmp(v->name, "maxcallbitrate")) {
24890             peer->maxcallbitrate = atoi(v->value);
24891             if (peer->maxcallbitrate < 0) {
24892                peer->maxcallbitrate = default_maxcallbitrate;
24893             }
24894          } else if (!strcasecmp(v->name, "session-timers")) {
24895             int i = (int) str2stmode(v->value);
24896             if (i < 0) {
24897                ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
24898                peer->stimer.st_mode_oper = global_st_mode;
24899             } else {
24900                peer->stimer.st_mode_oper = i;
24901             }
24902          } else if (!strcasecmp(v->name, "session-expires")) {
24903             if (sscanf(v->value, "%30d", &peer->stimer.st_max_se) != 1) {
24904                ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
24905                peer->stimer.st_max_se = global_max_se;
24906             }
24907          } else if (!strcasecmp(v->name, "session-minse")) {
24908             if (sscanf(v->value, "%30d", &peer->stimer.st_min_se) != 1) {
24909                ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
24910                peer->stimer.st_min_se = global_min_se;
24911             }
24912             if (peer->stimer.st_min_se < 90) {
24913                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);
24914                peer->stimer.st_min_se = global_min_se;
24915             }
24916          } else if (!strcasecmp(v->name, "session-refresher")) {
24917             int i = (int) str2strefresher(v->value);
24918             if (i < 0) {
24919                ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
24920                peer->stimer.st_ref = global_st_refresher;
24921             } else {
24922                peer->stimer.st_ref = i;
24923             }
24924          }
24925       }
24926 
24927       /* These apply to devstate lookups */
24928       if (realtime && !strcasecmp(v->name, "lastms")) {
24929          sscanf(v->value, "%30d", &peer->lastms);
24930       } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
24931          inet_aton(v->value, &(peer->addr.sin_addr));
24932       } else if (realtime && !strcasecmp(v->name, "fullcontact")) {
24933          if (alt_fullcontact && !alt) {
24934             /* Reset, because the alternate also has a fullcontact and we
24935              * do NOT want the field value to be doubled. It might be
24936              * tempting to skip this, but the first table might not have
24937              * fullcontact and since we're here, we know that the alternate
24938              * absolutely does. */
24939             alt_fullcontact = 0;
24940             ast_str_reset(fullcontact);
24941          }
24942          /* Reconstruct field, because realtime separates our value at the ';' */
24943          if (fullcontact->used > 0) {
24944             ast_str_append(&fullcontact, 0, ";%s", v->value);
24945          } else {
24946             ast_str_set(&fullcontact, 0, "%s", v->value);
24947          }
24948       } else if (!strcasecmp(v->name, "qualify")) {
24949          if (!strcasecmp(v->value, "no")) {
24950             peer->maxms = 0;
24951          } else if (!strcasecmp(v->value, "yes")) {
24952             peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
24953          } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
24954             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);
24955             peer->maxms = 0;
24956          }
24957          if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->maxms > 0) {
24958             /* This would otherwise cause a network storm, where the
24959              * qualify response refreshes the peer from the database,
24960              * which in turn causes another qualify to be sent, ad
24961              * infinitum. */
24962             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);
24963             peer->maxms = 0;
24964          }
24965       } else if (!strcasecmp(v->name, "callcounter")) {
24966          peer->call_limit = ast_true(v->value) ? INT_MAX : 0;
24967       } else if (!strcasecmp(v->name, "call-limit")) {
24968          peer->call_limit = atoi(v->value);
24969          if (peer->call_limit < 0) {
24970             peer->call_limit = 0;
24971          }
24972       } else if (!strcasecmp(v->name, "busylevel")) {
24973          peer->busy_level = atoi(v->value);
24974          if (peer->busy_level < 0) {
24975             peer->busy_level = 0;
24976          }
24977       }
24978    }
24979 
24980    if (!devstate_only) {
24981       struct sip_mailbox *mailbox;
24982       AST_LIST_TRAVERSE_SAFE_BEGIN(&peer->mailboxes, mailbox, entry) {
24983          if (mailbox->delme) {
24984             AST_LIST_REMOVE_CURRENT(entry);
24985             destroy_mailbox(mailbox);
24986          }
24987       }
24988       AST_LIST_TRAVERSE_SAFE_END;
24989    }
24990 
24991    if (!peer->default_outbound_transport) {
24992       /* Set default set of transports */
24993       peer->transports = default_transports;
24994       /* Set default primary transport */
24995       peer->default_outbound_transport = default_primary_transport;
24996    }
24997 
24998    /* The default transport type set during build_peer should only replace the socket.type when...
24999     * 1. Registration is not present and the socket.type and default transport types are different.
25000     * 2. The socket.type is not an acceptable transport type after rebuilding peer.
25001     * 3. The socket.type is not set yet. */
25002    if (((peer->socket.type != peer->default_outbound_transport) && (peer->expire == -1)) ||
25003       !(peer->socket.type & peer->transports) || !(peer->socket.type)) {
25004 
25005       set_socket_transport(&peer->socket, peer->default_outbound_transport);
25006    }
25007 
25008    if (port && !realtime && peer->host_dynamic) {
25009       peer->defaddr.sin_port = htons(port);
25010    } else if (port) {
25011       peer->addr.sin_port = htons(port);
25012    }
25013 
25014    if (ast_str_strlen(fullcontact)) {
25015       ast_string_field_set(peer, fullcontact, ast_str_buffer(fullcontact));
25016       peer->rt_fromcontact = TRUE;
25017       /* We have a hostname in the fullcontact, but if we don't have an
25018        * address listed on the entry (or if it's 'dynamic'), then we need to
25019        * parse the entry to obtain the IP address, so a dynamic host can be
25020        * contacted immediately after reload (as opposed to waiting for it to
25021        * register once again). But if we have an address for this peer and NAT was
25022        * specified, use that address instead. */
25023       /* XXX May need to revisit the final argument; does the realtime DB store whether
25024        * the original contact was over TLS or not? XXX */
25025       if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) || !peer->addr.sin_addr.s_addr) {
25026          __set_address_from_contact(fullcontact->str, &peer->addr, 0);
25027       }
25028    }
25029 
25030    if (srvlookup && peer->dnsmgr == NULL) {
25031       char transport[MAXHOSTNAMELEN];
25032       char _srvlookup[MAXHOSTNAMELEN];
25033       char *params;
25034 
25035       ast_copy_string(_srvlookup, srvlookup, sizeof(_srvlookup));
25036       if ((params = strchr(_srvlookup, ';'))) {
25037          *params++ = '\0';
25038       }
25039 
25040       snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(peer->socket.type), get_srv_protocol(peer->socket.type));
25041 
25042       if (ast_dnsmgr_lookup(_srvlookup, &peer->addr, &peer->dnsmgr, sip_cfg.srvlookup && !peer->portinuri ? transport : NULL)) {
25043          ast_log(LOG_ERROR, "srvlookup failed for host: %s, on peer %s, removing peer\n", _srvlookup, peer->name);
25044          unref_peer(peer, "getting rid of a peer pointer");
25045          return NULL;
25046       }
25047 
25048       ast_string_field_set(peer, tohost, srvlookup);
25049       if (global_dynamic_exclude_static) {
25050          int err = 0;
25051          global_contact_ha = ast_append_ha("deny", (char *)ast_inet_ntoa(peer->addr.sin_addr), global_contact_ha, &err);
25052          if (err) {
25053             ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
25054          }
25055       }
25056    }
25057 
25058    if (!peer->addr.sin_port) {
25059       peer->addr.sin_port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
25060    }
25061    if (!peer->defaddr.sin_port) {
25062       peer->defaddr.sin_port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
25063    }
25064    if (!peer->socket.port) {
25065       peer->socket.port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
25066    }
25067 
25068    if (!sip_cfg.ignore_regexpire && peer->host_dynamic && realtime) {
25069       time_t nowtime = time(NULL);
25070 
25071       if ((nowtime - regseconds) > 0) {
25072          destroy_association(peer);
25073          memset(&peer->addr, 0, sizeof(peer->addr));
25074          peer->lastms = -1;
25075          ast_debug(1, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
25076       }
25077    }
25078 
25079    /* Startup regular pokes */
25080    if (!devstate_only && realtime && peer->lastms > 0) {
25081       ref_peer(peer, "schedule qualify");
25082       sip_poke_peer(peer, 0);
25083    }
25084 
25085    ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
25086    ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
25087    if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
25088       sip_cfg.allowsubscribe = TRUE;   /* No global ban any more */
25089    }
25090    if (peer->host_dynamic && !peer->is_realtime) {
25091       reg_source_db(peer);
25092    }
25093 
25094    /* If they didn't request that MWI is sent *only* on subscribe, go ahead and
25095     * subscribe to it now. */
25096    if (!devstate_only && !ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
25097       !AST_LIST_EMPTY(&peer->mailboxes)) {
25098       add_peer_mwi_subs(peer);
25099       /* Send MWI from the event cache only.  This is so we can send initial
25100        * MWI if app_voicemail got loaded before chan_sip.  If it is the other
25101        * way, then we will get events when app_voicemail gets loaded. */
25102       sip_send_mwi_to_peer(peer, NULL, 1);
25103    }
25104 
25105    peer->the_mark = 0;
25106 
25107    ast_free_ha(oldha);
25108    if (!ast_strlen_zero(callback)) { /* build string from peer info */
25109       char *reg_string;
25110       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) {
25111          ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
25112       } else if (reg_string) {
25113          sip_register(reg_string, 0); /* XXX TODO: count in registry_count */
25114          ast_free(reg_string);
25115       }
25116    }
25117    return peer;
25118 }
25119 
25120 static int peer_markall_func(void *device, void *arg, int flags)
25121 {
25122    struct sip_peer *peer = device;
25123    peer->the_mark = 1;
25124    return 0;
25125 }
25126 
25127 /*! \brief Re-read SIP.conf config file
25128 \note This function reloads all config data, except for
25129    active peers (with registrations). They will only
25130    change configuration data at restart, not at reload.
25131    SIP debug and recordhistory state will not change
25132  */
25133 static int reload_config(enum channelreloadreason reason)
25134 {
25135    struct ast_config *cfg, *ucfg;
25136    struct ast_variable *v;
25137    struct sip_peer *peer;
25138    char *cat, *stringp, *context, *oldregcontext;
25139    char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
25140    struct ast_flags dummy[2];
25141    struct ast_flags config_flags = { reason == CHANNEL_MODULE_LOAD ? 0 : ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? 0 : CONFIG_FLAG_FILEUNCHANGED };
25142    int auto_sip_domains = FALSE;
25143    struct sockaddr_in old_bindaddr = bindaddr;
25144    int registry_count = 0, peer_count = 0;
25145    time_t run_start, run_end;
25146    
25147    run_start = time(0);
25148    ast_unload_realtime("sipregs");     
25149    ast_unload_realtime("sippeers");
25150    cfg = ast_config_load(config, config_flags);
25151 
25152    /* We *must* have a config file otherwise stop immediately */
25153    if (!cfg) {
25154       ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
25155       return -1;
25156    } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
25157       ucfg = ast_config_load("users.conf", config_flags);
25158       if (ucfg == CONFIG_STATUS_FILEUNCHANGED) {
25159          return 1;
25160       } else if (ucfg == CONFIG_STATUS_FILEINVALID) {
25161          ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
25162          return 1;
25163       }
25164       /* Must reread both files, because one changed */
25165       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
25166       if ((cfg = ast_config_load(config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
25167          ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
25168          ast_config_destroy(ucfg);
25169          return 1;
25170       }
25171    } else if (cfg == CONFIG_STATUS_FILEINVALID) {
25172       ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
25173       return 1;
25174    } else {
25175       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
25176       if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
25177          ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
25178          ast_config_destroy(cfg);
25179          return 1;
25180       }
25181    }
25182 
25183    /* Initialize tcp sockets */
25184    memset(&sip_tcp_desc.local_address, 0, sizeof(sip_tcp_desc.local_address));
25185    memset(&sip_tls_desc.local_address, 0, sizeof(sip_tls_desc.local_address));
25186 
25187    ast_free_ha(global_contact_ha);
25188    global_contact_ha = NULL;
25189 
25190    default_tls_cfg.enabled = FALSE;    /* Default: Disable TLS */
25191 
25192    sip_tcp_desc.local_address.sin_port = htons(STANDARD_SIP_PORT);
25193    sip_tls_desc.local_address.sin_port = htons(STANDARD_TLS_PORT);
25194 
25195    if (reason != CHANNEL_MODULE_LOAD) {
25196       ast_debug(4, "--------------- SIP reload started\n");
25197 
25198       clear_realm_authentication(authl);
25199       clear_sip_domains();
25200       authl = NULL;
25201 
25202       /* First, destroy all outstanding registry calls */
25203       /* This is needed, since otherwise active registry entries will not be destroyed */
25204       ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {  /* regl is locked */
25205 
25206             ASTOBJ_RDLOCK(iterator); /* now regl is locked, and the object is also locked */
25207             if (iterator->call) {
25208                ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
25209                /* This will also remove references to the registry */
25210                dialog_unlink_all(iterator->call, TRUE, TRUE);
25211                iterator->call = dialog_unref(iterator->call, "remove iterator->call from registry traversal");
25212             }
25213             if (iterator->expire > -1) {
25214                AST_SCHED_DEL_UNREF(sched, iterator->expire, registry_unref(iterator, "reg ptr unref from reload config"));
25215             }
25216             if (iterator->timeout > -1) {
25217                AST_SCHED_DEL_UNREF(sched, iterator->timeout, registry_unref(iterator, "reg ptr unref from reload config"));
25218             }
25219             ASTOBJ_UNLOCK(iterator);
25220             
25221       } while(0));
25222 
25223       /* Then, actually destroy users and registry */
25224       ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
25225       ast_debug(4, "--------------- Done destroying registry list\n");
25226       ao2_t_callback(peers, OBJ_NODATA, peer_markall_func, NULL, "callback to mark all peers");
25227    }
25228    
25229    /* Reset certificate handling for TLS sessions */
25230    if (reason != CHANNEL_MODULE_LOAD) {
25231       ast_free(default_tls_cfg.certfile);
25232       ast_free(default_tls_cfg.cipher);
25233       ast_free(default_tls_cfg.cafile);
25234       ast_free(default_tls_cfg.capath);
25235    }
25236    default_tls_cfg.certfile = ast_strdup(AST_CERTFILE); /*XXX Not sure if this is useful */
25237    default_tls_cfg.cipher = ast_strdup("");
25238    default_tls_cfg.cafile = ast_strdup("");
25239    default_tls_cfg.capath = ast_strdup("");
25240 
25241    
25242    /* Initialize copy of current global_regcontext for later use in removing stale contexts */
25243    ast_copy_string(oldcontexts, global_regcontext, sizeof(oldcontexts));
25244    oldregcontext = oldcontexts;
25245 
25246    /* Clear all flags before setting default values */
25247    /* Preserve debugging settings for console */
25248    sipdebug &= sip_debug_console;
25249    ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
25250    ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
25251 
25252    /* Reset IP addresses  */
25253    memset(&bindaddr, 0, sizeof(bindaddr));
25254    memset(&stunaddr, 0, sizeof(stunaddr));
25255    memset(&internip, 0, sizeof(internip));
25256 
25257    /* Free memory for local network address mask */
25258    ast_free_ha(localaddr);
25259    memset(&localaddr, 0, sizeof(localaddr));
25260    memset(&externip, 0, sizeof(externip));
25261    memset(&default_prefs, 0 , sizeof(default_prefs));
25262    memset(&sip_cfg.outboundproxy, 0, sizeof(struct sip_proxy));
25263    sip_cfg.outboundproxy.ip.sin_port = htons(STANDARD_SIP_PORT);
25264    sip_cfg.outboundproxy.ip.sin_family = AF_INET;  /*!< Type of address: IPv4 */
25265    sip_cfg.outboundproxy.force = FALSE;      /*!< Don't force proxy usage, use route: headers */
25266    default_transports = 0;          /*!< Reset default transport to zero here, default value later on */
25267    default_primary_transport = 0;         /*!< Reset default primary transport to zero here, default value later on */
25268    ourport_tcp = STANDARD_SIP_PORT;
25269    ourport_tls = STANDARD_TLS_PORT;
25270    bindaddr.sin_port = htons(STANDARD_SIP_PORT);
25271    sip_cfg.srvlookup = DEFAULT_SRVLOOKUP;
25272    global_tos_sip = DEFAULT_TOS_SIP;
25273    global_tos_audio = DEFAULT_TOS_AUDIO;
25274    global_tos_video = DEFAULT_TOS_VIDEO;
25275    global_tos_text = DEFAULT_TOS_TEXT;
25276    global_cos_sip = DEFAULT_COS_SIP;
25277    global_cos_audio = DEFAULT_COS_AUDIO;
25278    global_cos_video = DEFAULT_COS_VIDEO;
25279    global_cos_text = DEFAULT_COS_TEXT;
25280 
25281    externhost[0] = '\0';         /* External host name (for behind NAT DynDNS support) */
25282    externexpire = 0;       /* Expiration for DNS re-issuing */
25283    externrefresh = 10;
25284 
25285    /* Reset channel settings to default before re-configuring */
25286    sip_cfg.allow_external_domains = DEFAULT_ALLOW_EXT_DOM;           /* Allow external invites */
25287    global_regcontext[0] = '\0';
25288    sip_cfg.regextenonqualify = DEFAULT_REGEXTENONQUALIFY;
25289    sip_cfg.notifyringing = DEFAULT_NOTIFYRINGING;
25290    sip_cfg.notifycid = DEFAULT_NOTIFYCID;
25291    sip_cfg.notifyhold = FALSE;      /*!< Keep track of hold status for a peer */
25292    sip_cfg.directrtpsetup = FALSE;     /* Experimental feature, disabled by default */
25293    sip_cfg.alwaysauthreject = DEFAULT_ALWAYSAUTHREJECT;
25294    sip_cfg.allowsubscribe = FALSE;
25295    snprintf(global_useragent, sizeof(global_useragent), "%s %s", DEFAULT_USERAGENT, ast_get_version());
25296    snprintf(global_sdpsession, sizeof(global_sdpsession), "%s %s", DEFAULT_SDPSESSION, ast_get_version());
25297    snprintf(global_sdpowner, sizeof(global_sdpowner), "%s", DEFAULT_SDPOWNER);
25298    global_prematuremediafilter = TRUE;
25299    ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
25300    ast_copy_string(sip_cfg.realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM), sizeof(sip_cfg.realm));
25301    ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
25302    sip_cfg.compactheaders = DEFAULT_COMPACTHEADERS;
25303    global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
25304    global_regattempts_max = 0;
25305    sip_cfg.pedanticsipchecking = DEFAULT_PEDANTIC;
25306    sip_cfg.autocreatepeer = DEFAULT_AUTOCREATEPEER;
25307    global_autoframing = 0;
25308    sip_cfg.allowguest = DEFAULT_ALLOWGUEST;
25309    global_callcounter = DEFAULT_CALLCOUNTER;
25310    global_match_auth_username = FALSE;    /*!< Match auth username if available instead of From: Default off. */
25311    global_rtptimeout = 0;
25312    global_rtpholdtimeout = 0;
25313    global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
25314    sip_cfg.allowtransfer = TRANSFER_OPENFORALL; /* Merrily accept all transfers by default */
25315    sip_cfg.rtautoclear = 120;
25316    ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE);   /* Default for all devices: TRUE */
25317    ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP);     /* Default for all devices: TRUE */
25318    sip_cfg.peer_rtupdate = TRUE;
25319    global_dynamic_exclude_static = 0;  /* Exclude static peers */
25320 
25321    /* Session-Timers */
25322    global_st_mode = SESSION_TIMER_MODE_ACCEPT;    
25323    global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
25324    global_min_se  = DEFAULT_MIN_SE;
25325    global_max_se  = DEFAULT_MAX_SE;
25326 
25327    /* Peer poking settings */
25328    global_qualify_gap = DEFAULT_QUALIFY_GAP;
25329    global_qualify_peers = DEFAULT_QUALIFY_PEERS;
25330 
25331    /* Initialize some reasonable defaults at SIP reload (used both for channel and as default for devices */
25332    ast_copy_string(sip_cfg.default_context, DEFAULT_CONTEXT, sizeof(sip_cfg.default_context));
25333    sip_cfg.default_subscribecontext[0] = '\0';
25334    default_language[0] = '\0';
25335    default_fromdomain[0] = '\0';
25336    default_qualify = DEFAULT_QUALIFY;
25337    default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
25338    ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
25339    ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
25340    ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
25341    ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833);        /*!< Default DTMF setting: RFC2833 */
25342    ast_set_flag(&global_flags[0], SIP_NAT_RFC3581);         /*!< NAT support if requested by device with rport */
25343    ast_set_flag(&global_flags[0], SIP_DIRECT_MEDIA);        /*!< Allow re-invites */
25344    ast_set_flag(&global_flags[1], SIP_PAGE2_FORWARD_LOOP_DETECTED); /*!< Set up call forward on 482 Loop Detected */
25345 
25346    /* Debugging settings, always default to off */
25347    dumphistory = FALSE;
25348    recordhistory = FALSE;
25349    sipdebug &= ~sip_debug_config;
25350 
25351    /* Misc settings for the channel */
25352    global_relaxdtmf = FALSE;
25353    sip_cfg.callevents = DEFAULT_CALLEVENTS;
25354    global_authfailureevents = FALSE;
25355    global_t1 = DEFAULT_TIMER_T1;
25356    global_timer_b = 64 * DEFAULT_TIMER_T1;
25357    global_t1min = DEFAULT_T1MIN;
25358    global_qualifyfreq = DEFAULT_QUALIFYFREQ;
25359    global_t38_maxdatagram = -1;
25360    global_shrinkcallerid = 1;
25361    authlimit = DEFAULT_AUTHLIMIT;
25362    authtimeout = DEFAULT_AUTHTIMEOUT;
25363 
25364    sip_cfg.matchexterniplocally = DEFAULT_MATCHEXTERNIPLOCALLY;
25365 
25366    /* Copy the default jb config over global_jbconf */
25367    memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
25368 
25369    ast_clear_flag(&global_flags[1], SIP_PAGE2_FAX_DETECT);
25370    ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
25371    ast_clear_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT);
25372    ast_clear_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION);
25373 
25374 
25375    /* Read the [general] config section of sip.conf (or from realtime config) */
25376    for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
25377       if (handle_common_options(&global_flags[0], &dummy[0], v))
25378          continue;
25379       if (handle_t38_options(&global_flags[0], &dummy[0], v, &global_t38_maxdatagram)) {
25380          continue;
25381       }
25382       /* handle jb conf */
25383       if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
25384          continue;
25385 
25386       if (!strcasecmp(v->name, "context")) {
25387          ast_copy_string(sip_cfg.default_context, v->value, sizeof(sip_cfg.default_context));
25388       } else if (!strcasecmp(v->name, "subscribecontext")) {
25389          ast_copy_string(sip_cfg.default_subscribecontext, v->value, sizeof(sip_cfg.default_subscribecontext));
25390       } else if (!strcasecmp(v->name, "callcounter")) {
25391          global_callcounter = ast_true(v->value) ? 1 : 0;
25392       } else if (!strcasecmp(v->name, "allowguest")) {
25393          sip_cfg.allowguest = ast_true(v->value) ? 1 : 0;
25394       } else if (!strcasecmp(v->name, "realm")) {
25395          ast_copy_string(sip_cfg.realm, v->value, sizeof(sip_cfg.realm));
25396       } else if (!strcasecmp(v->name, "useragent")) {
25397          ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
25398          ast_debug(1, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
25399       } else if (!strcasecmp(v->name, "sdpsession")) {
25400          ast_copy_string(global_sdpsession, v->value, sizeof(global_sdpsession));
25401       } else if (!strcasecmp(v->name, "sdpowner")) {
25402          /* Field cannot contain spaces */
25403          if (!strstr(v->value, " "))
25404             ast_copy_string(global_sdpowner, v->value, sizeof(global_sdpowner));
25405          else
25406             ast_log(LOG_WARNING, "'%s' must not contain spaces at line %d.  Using default.\n", v->value, v->lineno);
25407       } else if (!strcasecmp(v->name, "allowtransfer")) {
25408          sip_cfg.allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
25409       } else if (!strcasecmp(v->name, "rtcachefriends")) {
25410          ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);   
25411       } else if (!strcasecmp(v->name, "rtsavesysname")) {
25412          sip_cfg.rtsave_sysname = ast_true(v->value);
25413       } else if (!strcasecmp(v->name, "rtupdate")) {
25414          sip_cfg.peer_rtupdate = ast_true(v->value);
25415       } else if (!strcasecmp(v->name, "ignoreregexpire")) {
25416          sip_cfg.ignore_regexpire = ast_true(v->value);
25417       } else if (!strcasecmp(v->name, "timert1")) {
25418          /* Defaults to 500ms, but RFC 3261 states that it is recommended
25419           * for the value to be set higher, though a lower value is only
25420           * allowed on private networks unconnected to the Internet. */
25421          global_t1 = atoi(v->value);
25422          /* Note that timer B is dependent on the value of T1 */
25423          global_timer_b = global_t1 * 64;
25424       } else if (!strcasecmp(v->name, "t1min")) {
25425          global_t1min = atoi(v->value);
25426       } else if (!strcasecmp(v->name, "transport") && !ast_strlen_zero(v->value)) {
25427          char *val = ast_strdupa(v->value);
25428          char *trans;
25429 
25430          while ((trans = strsep(&val, ","))) {
25431             trans = ast_skip_blanks(trans);
25432 
25433             if (!strncasecmp(trans, "udp", 3)) 
25434                default_transports |= SIP_TRANSPORT_UDP;
25435             else if (!strncasecmp(trans, "tcp", 3))
25436                default_transports |= SIP_TRANSPORT_TCP;
25437             else if (!strncasecmp(trans, "tls", 3))
25438                default_transports |= SIP_TRANSPORT_TLS;
25439             else
25440                ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
25441             if (default_primary_transport == 0) {
25442                default_primary_transport = default_transports;
25443             }
25444          }
25445       } else if (!strcasecmp(v->name, "tcpenable")) {
25446          sip_tcp_desc.local_address.sin_family = ast_false(v->value) ? 0 : AF_INET;
25447          ast_debug(2, "Enabling TCP socket for listening\n");
25448       } else if (!strcasecmp(v->name, "tcpbindaddr")) {
25449          int family = sip_tcp_desc.local_address.sin_family;
25450          if (ast_parse_arg(v->value, PARSE_INADDR, &sip_tcp_desc.local_address))
25451             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n", v->name, v->value, v->lineno, config);
25452          sip_tcp_desc.local_address.sin_family = family;
25453          ast_debug(2, "Setting TCP socket address to %s\n", v->value);
25454       } else if (!strcasecmp(v->name, "tlsenable")) {
25455          default_tls_cfg.enabled = ast_true(v->value) ? TRUE : FALSE;
25456          sip_tls_desc.local_address.sin_family = AF_INET;
25457       } else if (!strcasecmp(v->name, "tlscertfile")) {
25458          ast_free(default_tls_cfg.certfile);
25459          default_tls_cfg.certfile = ast_strdup(v->value);
25460       } else if (!strcasecmp(v->name, "tlscipher")) {
25461          ast_free(default_tls_cfg.cipher);
25462          default_tls_cfg.cipher = ast_strdup(v->value);
25463       } else if (!strcasecmp(v->name, "tlscafile")) {
25464          ast_free(default_tls_cfg.cafile);
25465          default_tls_cfg.cafile = ast_strdup(v->value);
25466       } else if (!strcasecmp(v->name, "tlscapath")) {
25467          ast_free(default_tls_cfg.capath);
25468          default_tls_cfg.capath = ast_strdup(v->value);
25469       } else if (!strcasecmp(v->name, "tlsverifyclient")) {
25470          ast_set2_flag(&default_tls_cfg.flags, ast_true(v->value), AST_SSL_VERIFY_CLIENT);   
25471       } else if (!strcasecmp(v->name, "tlsdontverifyserver")) {
25472          ast_set2_flag(&default_tls_cfg.flags, ast_true(v->value), AST_SSL_DONT_VERIFY_SERVER); 
25473       } else if (!strcasecmp(v->name, "tlsbindaddr")) {
25474          if (ast_parse_arg(v->value, PARSE_INADDR, &sip_tls_desc.local_address))
25475             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n", v->name, v->value, v->lineno, config);
25476       } else if (!strcasecmp(v->name, "dynamic_exclude_static") || !strcasecmp(v->name, "dynamic_excludes_static")) {
25477          global_dynamic_exclude_static = ast_true(v->value);
25478       } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
25479          int ha_error = 0;
25480          global_contact_ha = ast_append_ha(v->name + 7, v->value, global_contact_ha, &ha_error);
25481          if (ha_error) {
25482             ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
25483          }
25484       } else if (!strcasecmp(v->name, "rtautoclear")) {
25485          int i = atoi(v->value);
25486          if (i > 0)
25487             sip_cfg.rtautoclear = i;
25488          else
25489             i = 0;
25490          ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
25491       } else if (!strcasecmp(v->name, "usereqphone")) {
25492          ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);   
25493       } else if (!strcasecmp(v->name, "prematuremedia")) {
25494          global_prematuremediafilter = ast_true(v->value);
25495       } else if (!strcasecmp(v->name, "relaxdtmf")) {
25496          global_relaxdtmf = ast_true(v->value);
25497       } else if (!strcasecmp(v->name, "vmexten")) {
25498          ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
25499       } else if (!strcasecmp(v->name, "rtptimeout")) {
25500          if ((sscanf(v->value, "%30d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
25501             ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
25502             global_rtptimeout = 0;
25503          }
25504       } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
25505          if ((sscanf(v->value, "%30d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
25506             ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
25507             global_rtpholdtimeout = 0;
25508          }
25509       } else if (!strcasecmp(v->name, "rtpkeepalive")) {
25510          if ((sscanf(v->value, "%30d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
25511             ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d.  Using default.\n", v->value, v->lineno);
25512             global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
25513          }
25514       } else if (!strcasecmp(v->name, "compactheaders")) {
25515          sip_cfg.compactheaders = ast_true(v->value);
25516       } else if (!strcasecmp(v->name, "notifymimetype")) {
25517          ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
25518       } else if (!strcasecmp(v->name, "directrtpsetup")) {
25519          sip_cfg.directrtpsetup = ast_true(v->value);
25520       } else if (!strcasecmp(v->name, "notifyringing")) {
25521          sip_cfg.notifyringing = ast_true(v->value);
25522       } else if (!strcasecmp(v->name, "notifyhold")) {
25523          sip_cfg.notifyhold = ast_true(v->value);
25524       } else if (!strcasecmp(v->name, "notifycid")) {
25525          if (!strcasecmp(v->value, "ignore-context")) {
25526             sip_cfg.notifycid = IGNORE_CONTEXT;
25527          } else {
25528             sip_cfg.notifycid = ast_true(v->value);
25529          }
25530       } else if (!strcasecmp(v->name, "alwaysauthreject")) {
25531          sip_cfg.alwaysauthreject = ast_true(v->value);
25532       } else if (!strcasecmp(v->name, "mohinterpret")) {
25533          ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
25534       } else if (!strcasecmp(v->name, "mohsuggest")) {
25535          ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
25536       } else if (!strcasecmp(v->name, "language")) {
25537          ast_copy_string(default_language, v->value, sizeof(default_language));
25538       } else if (!strcasecmp(v->name, "regcontext")) {
25539          ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
25540          stringp = newcontexts;
25541          /* Let's remove any contexts that are no longer defined in regcontext */
25542          cleanup_stale_contexts(stringp, oldregcontext);
25543          /* Create contexts if they don't exist already */
25544          while ((context = strsep(&stringp, "&"))) {
25545             ast_copy_string(used_context, context, sizeof(used_context));
25546             ast_context_find_or_create(NULL, NULL, context, "SIP");
25547          }
25548          ast_copy_string(global_regcontext, v->value, sizeof(global_regcontext));
25549       } else if (!strcasecmp(v->name, "regextenonqualify")) {
25550          sip_cfg.regextenonqualify = ast_true(v->value);
25551       } else if (!strcasecmp(v->name, "callerid")) {
25552          ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
25553       } else if (!strcasecmp(v->name, "fromdomain")) {
25554          ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
25555       } else if (!strcasecmp(v->name, "outboundproxy")) {
25556          int portnum;
25557          char *tok, *proxyname;
25558 
25559          if (ast_strlen_zero(v->value)) {
25560             ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf.", v->lineno);
25561             continue;
25562          }
25563 
25564          tok = ast_skip_blanks(strtok(ast_strdupa(v->value), ","));
25565 
25566          sip_parse_host(tok, v->lineno, &proxyname, &portnum, &sip_cfg.outboundproxy.transport);
25567 
25568          sip_cfg.outboundproxy.ip.sin_port = htons(portnum);
25569    
25570          if ((tok = strtok(NULL, ","))) {
25571             sip_cfg.outboundproxy.force = !strncasecmp(ast_skip_blanks(tok), "force", 5);
25572          } else {
25573             sip_cfg.outboundproxy.force = FALSE;
25574          }
25575 
25576          if (ast_strlen_zero(proxyname)) {
25577             ast_log(LOG_WARNING, "you must specify a name for the outboundproxy on line %d of sip.conf.", v->lineno);
25578             sip_cfg.outboundproxy.name[0] = '\0';
25579             continue;
25580          }
25581 
25582          ast_copy_string(sip_cfg.outboundproxy.name, proxyname, sizeof(sip_cfg.outboundproxy.name));
25583 
25584          proxy_update(&sip_cfg.outboundproxy);
25585       } else if (!strcasecmp(v->name, "autocreatepeer")) {
25586          sip_cfg.autocreatepeer = ast_true(v->value);
25587       } else if (!strcasecmp(v->name, "match_auth_username")) {
25588          global_match_auth_username = ast_true(v->value);
25589       } else if (!strcasecmp(v->name, "srvlookup")) {
25590          sip_cfg.srvlookup = ast_true(v->value);
25591       } else if (!strcasecmp(v->name, "pedantic")) {
25592          sip_cfg.pedanticsipchecking = ast_true(v->value);
25593       } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
25594          max_expiry = atoi(v->value);
25595          if (max_expiry < 1)
25596             max_expiry = DEFAULT_MAX_EXPIRY;
25597       } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
25598          min_expiry = atoi(v->value);
25599          if (min_expiry < 1)
25600             min_expiry = DEFAULT_MIN_EXPIRY;
25601       } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
25602          default_expiry = atoi(v->value);
25603          if (default_expiry < 1)
25604             default_expiry = DEFAULT_DEFAULT_EXPIRY;
25605       } else if (!strcasecmp(v->name, "mwiexpiry") || !strcasecmp(v->name, "mwiexpirey")) {
25606          mwi_expiry = atoi(v->value);
25607          if (mwi_expiry < 1)
25608             mwi_expiry = DEFAULT_MWI_EXPIRY;
25609       } else if (!strcasecmp(v->name, "tcpauthtimeout")) {
25610          if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
25611                  &authtimeout, DEFAULT_AUTHTIMEOUT, 1, INT_MAX)) {
25612             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
25613                v->name, v->value, v->lineno, config);
25614          }
25615       } else if (!strcasecmp(v->name, "tcpauthlimit")) {
25616          if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
25617                  &authlimit, DEFAULT_AUTHLIMIT, 1, INT_MAX)) {
25618             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
25619                v->name, v->value, v->lineno, config);
25620          }
25621       } else if (!strcasecmp(v->name, "sipdebug")) {
25622          if (ast_true(v->value))
25623             sipdebug |= sip_debug_config;
25624       } else if (!strcasecmp(v->name, "dumphistory")) {
25625          dumphistory = ast_true(v->value);
25626       } else if (!strcasecmp(v->name, "recordhistory")) {
25627          recordhistory = ast_true(v->value);
25628       } else if (!strcasecmp(v->name, "registertimeout")) {
25629          global_reg_timeout = atoi(v->value);
25630          if (global_reg_timeout < 1)
25631             global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
25632       } else if (!strcasecmp(v->name, "registerattempts")) {
25633          global_regattempts_max = atoi(v->value);
25634       } else if (!strcasecmp(v->name, "stunaddr")) {
25635          stunaddr.sin_port = htons(3478);
25636          if (ast_parse_arg(v->value, PARSE_INADDR, &stunaddr))
25637             ast_log(LOG_WARNING, "Invalid STUN server address: %s\n", v->value);
25638          externexpire = time(NULL);
25639       } else if (!strcasecmp(v->name, "bindaddr") || !strcasecmp(v->name, "udpbindaddr")) {
25640          if (ast_parse_arg(v->value, PARSE_INADDR, &bindaddr))
25641             ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
25642       } else if (!strcasecmp(v->name, "localnet")) {
25643          struct ast_ha *na;
25644          int ha_error = 0;
25645 
25646          if (!(na = ast_append_ha("d", v->value, localaddr, &ha_error)))
25647             ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
25648          else
25649             localaddr = na;
25650          if (ha_error)
25651             ast_log(LOG_ERROR, "Bad localnet configuration value line %d : %s\n", v->lineno, v->value);
25652       } else if (!strcasecmp(v->name, "externip")) {
25653          if (ast_parse_arg(v->value, PARSE_INADDR, &externip))
25654             ast_log(LOG_WARNING, "Invalid address for externip keyword: %s\n", v->value);
25655          externexpire = 0;
25656          /* If no port was specified use the value of bindport */
25657          if (!externip.sin_port)
25658             externip.sin_port = bindaddr.sin_port;
25659       } else if (!strcasecmp(v->name, "externhost")) {
25660          ast_copy_string(externhost, v->value, sizeof(externhost));
25661          if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
25662             ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
25663          externexpire = time(NULL);
25664          /* If no port was specified use the value of bindport */
25665          if (!externip.sin_port)
25666             externip.sin_port = bindaddr.sin_port;
25667       } else if (!strcasecmp(v->name, "externrefresh")) {
25668          if (sscanf(v->value, "%30d", &externrefresh) != 1) {
25669             ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
25670             externrefresh = 10;
25671          }
25672       } else if (!strcasecmp(v->name, "allow")) {
25673          int error =  ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, TRUE);
25674          if (error)
25675             ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
25676       } else if (!strcasecmp(v->name, "disallow")) {
25677          int error =  ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, FALSE);
25678          if (error)
25679             ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
25680       } else if (!strcasecmp(v->name, "autoframing")) {
25681          global_autoframing = ast_true(v->value);
25682       } else if (!strcasecmp(v->name, "allowexternaldomains")) {
25683          sip_cfg.allow_external_domains = ast_true(v->value);
25684       } else if (!strcasecmp(v->name, "autodomain")) {
25685          auto_sip_domains = ast_true(v->value);
25686       } else if (!strcasecmp(v->name, "domain")) {
25687          char *domain = ast_strdupa(v->value);
25688          char *cntx = strchr(domain, ',');
25689 
25690          if (cntx)
25691             *cntx++ = '\0';
25692 
25693          if (ast_strlen_zero(cntx))
25694             ast_debug(1, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
25695          if (ast_strlen_zero(domain))
25696             ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
25697          else
25698             add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, cntx ? ast_strip(cntx) : "");
25699       } else if (!strcasecmp(v->name, "register")) {
25700          if (sip_register(v->value, v->lineno) == 0)
25701             registry_count++;
25702       } else if (!strcasecmp(v->name, "mwi")) {
25703          sip_subscribe_mwi(v->value, v->lineno);
25704       } else if (!strcasecmp(v->name, "tos_sip")) {
25705          if (ast_str2tos(v->value, &global_tos_sip))
25706             ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, refer to QoS documentation\n", v->lineno);
25707       } else if (!strcasecmp(v->name, "tos_audio")) {
25708          if (ast_str2tos(v->value, &global_tos_audio))
25709             ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, refer to QoS documentation\n", v->lineno);
25710       } else if (!strcasecmp(v->name, "tos_video")) {
25711          if (ast_str2tos(v->value, &global_tos_video))
25712             ast_log(LOG_WARNING, "Invalid tos_video value at line %d, refer to QoS documentation\n", v->lineno);
25713       } else if (!strcasecmp(v->name, "tos_text")) {
25714          if (ast_str2tos(v->value, &global_tos_text))
25715             ast_log(LOG_WARNING, "Invalid tos_text value at line %d, refer to QoS documentation\n", v->lineno);
25716       } else if (!strcasecmp(v->name, "cos_sip")) {
25717          if (ast_str2cos(v->value, &global_cos_sip))
25718             ast_log(LOG_WARNING, "Invalid cos_sip value at line %d, refer to QoS documentation\n", v->lineno);
25719       } else if (!strcasecmp(v->name, "cos_audio")) {
25720          if (ast_str2cos(v->value, &global_cos_audio))
25721             ast_log(LOG_WARNING, "Invalid cos_audio value at line %d, refer to QoS documentation\n", v->lineno);
25722       } else if (!strcasecmp(v->name, "cos_video")) {
25723          if (ast_str2cos(v->value, &global_cos_video))
25724             ast_log(LOG_WARNING, "Invalid cos_video value at line %d, refer to QoS documentation\n", v->lineno);
25725       } else if (!strcasecmp(v->name, "cos_text")) {
25726          if (ast_str2cos(v->value, &global_cos_text))
25727             ast_log(LOG_WARNING, "Invalid cos_text value at line %d, refer to QoS documentation\n", v->lineno);
25728       } else if (!strcasecmp(v->name, "bindport")) {
25729          int i;
25730          if (sscanf(v->value, "%5d", &i) == 1) {
25731             bindaddr.sin_port = htons(i);
25732          } else {
25733             ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
25734          }
25735       } else if (!strcasecmp(v->name, "qualify")) {
25736          if (!strcasecmp(v->value, "no")) {
25737             default_qualify = 0;
25738          } else if (!strcasecmp(v->value, "yes")) {
25739             default_qualify = DEFAULT_MAXMS;
25740          } else if (sscanf(v->value, "%30d", &default_qualify) != 1) {
25741             ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
25742             default_qualify = 0;
25743          }
25744       } else if (!strcasecmp(v->name, "qualifyfreq")) {
25745          int i;
25746          if (sscanf(v->value, "%30d", &i) == 1)
25747             global_qualifyfreq = i * 1000;
25748          else {
25749             ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
25750             global_qualifyfreq = DEFAULT_QUALIFYFREQ;
25751          }
25752       } else if (!strcasecmp(v->name, "callevents")) {
25753          sip_cfg.callevents = ast_true(v->value);
25754       } else if (!strcasecmp(v->name, "authfailureevents")) {
25755          global_authfailureevents = ast_true(v->value);
25756       } else if (!strcasecmp(v->name, "maxcallbitrate")) {
25757          default_maxcallbitrate = atoi(v->value);
25758          if (default_maxcallbitrate < 0)
25759             default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
25760       } else if (!strcasecmp(v->name, "matchexterniplocally")) {
25761          sip_cfg.matchexterniplocally = ast_true(v->value);
25762       } else if (!strcasecmp(v->name, "session-timers")) {
25763          int i = (int) str2stmode(v->value); 
25764          if (i < 0) {
25765             ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
25766             global_st_mode = SESSION_TIMER_MODE_ACCEPT;
25767          } else {
25768             global_st_mode = i;
25769          }
25770       } else if (!strcasecmp(v->name, "session-expires")) {
25771          if (sscanf(v->value, "%30d", &global_max_se) != 1) {
25772             ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
25773             global_max_se = DEFAULT_MAX_SE;
25774          } 
25775       } else if (!strcasecmp(v->name, "session-minse")) {
25776          if (sscanf(v->value, "%30d", &global_min_se) != 1) {
25777             ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
25778             global_min_se = DEFAULT_MIN_SE;
25779          } 
25780          if (global_min_se < 90) {
25781             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);
25782             global_min_se = DEFAULT_MIN_SE;
25783          } 
25784       } else if (!strcasecmp(v->name, "session-refresher")) {
25785          int i = (int) str2strefresher(v->value); 
25786          if (i < 0) {
25787             ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
25788             global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
25789          } else {
25790             global_st_refresher = i;
25791          }
25792       } else if (!strcasecmp(v->name, "qualifygap")) {
25793          if (sscanf(v->value, "%30d", &global_qualify_gap) != 1) {
25794             ast_log(LOG_WARNING, "Invalid qualifygap '%s' at line %d of %s\n", v->value, v->lineno, config);
25795             global_qualify_gap = DEFAULT_QUALIFY_GAP;
25796          }
25797       } else if (!strcasecmp(v->name, "qualifypeers")) {
25798          if (sscanf(v->value, "%30d", &global_qualify_peers) != 1) {
25799             ast_log(LOG_WARNING, "Invalid pokepeers '%s' at line %d of %s\n", v->value, v->lineno, config);
25800             global_qualify_peers = DEFAULT_QUALIFY_PEERS;
25801          }
25802       } else if (!strcasecmp(v->name, "shrinkcallerid")) {
25803          if (ast_true(v->value)) {
25804             global_shrinkcallerid = 1;
25805          } else if (ast_false(v->value)) {
25806             global_shrinkcallerid = 0;
25807          } else {
25808             ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
25809          }
25810       }
25811    }
25812 
25813    if (!sip_cfg.allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
25814       ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
25815       sip_cfg.allow_external_domains = 1;
25816    }
25817    /* If not configured, set default transports */
25818    if (default_transports == 0) {
25819       default_transports = default_primary_transport = SIP_TRANSPORT_UDP;
25820    }
25821    
25822    /* Build list of authentication to various SIP realms, i.e. service providers */
25823    for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
25824       /* Format for authentication is auth = username:password@realm */
25825       if (!strcasecmp(v->name, "auth"))
25826          authl = add_realm_authentication(authl, v->value, v->lineno);
25827    }
25828 
25829    /* Set UDP address and open socket */
25830    bindaddr.sin_family = AF_INET;
25831    internip = bindaddr;
25832    if (ast_find_ourip(&internip.sin_addr, bindaddr)) {
25833       ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
25834       ast_config_destroy(cfg);
25835       return 0;
25836    }
25837 
25838    ast_mutex_lock(&netlock);
25839    if ((sipsock > -1) && (memcmp(&old_bindaddr, &bindaddr, sizeof(struct sockaddr_in)))) {
25840       close(sipsock);
25841       sipsock = -1;
25842    }
25843    if (sipsock < 0) {
25844       sipsock = socket(AF_INET, SOCK_DGRAM, 0);
25845       if (sipsock < 0) {
25846          ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
25847          ast_config_destroy(cfg);
25848          ast_mutex_unlock(&netlock);
25849          return -1;
25850       } else {
25851          /* Allow SIP clients on the same host to access us: */
25852          const int reuseFlag = 1;
25853 
25854          setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
25855                (const char*)&reuseFlag,
25856                sizeof reuseFlag);
25857 
25858          ast_enable_packet_fragmentation(sipsock);
25859 
25860          if (bind(sipsock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
25861             ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
25862             ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
25863             strerror(errno));
25864             close(sipsock);
25865             sipsock = -1;
25866          } else {
25867             ast_verb(2, "SIP Listening on %s:%d\n",
25868                   ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
25869             ast_netsock_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
25870          }
25871       }
25872    } else {
25873       ast_netsock_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
25874    }
25875    if (stunaddr.sin_addr.s_addr != 0) {
25876       ast_debug(1, "stun to %s:%d\n",
25877          ast_inet_ntoa(stunaddr.sin_addr) , ntohs(stunaddr.sin_port));
25878       ast_stun_request(sipsock, &stunaddr,
25879          NULL, &externip);
25880       ast_debug(1, "STUN sees us at %s:%d\n", 
25881          ast_inet_ntoa(externip.sin_addr) , ntohs(externip.sin_port));
25882    }
25883    ast_mutex_unlock(&netlock);
25884 
25885    /* Start TCP server */
25886    ast_tcptls_server_start(&sip_tcp_desc);
25887    if (sip_tcp_desc.accept_fd == -1 &&  sip_tcp_desc.local_address.sin_family == AF_INET) {
25888       /* TCP server start failed. Tell the admin */
25889       ast_log(LOG_ERROR, "SIP TCP Server start failed. Not listening on TCP socket.\n");
25890       sip_tcp_desc.local_address.sin_family = 0;
25891    } else {
25892       ast_debug(2, "SIP TCP server started\n");
25893    }
25894 
25895    /* Start TLS server if needed */
25896    memcpy(sip_tls_desc.tls_cfg, &default_tls_cfg, sizeof(default_tls_cfg));
25897 
25898    if (ast_ssl_setup(sip_tls_desc.tls_cfg)) {
25899       ast_tcptls_server_start(&sip_tls_desc);
25900       if (default_tls_cfg.enabled && sip_tls_desc.accept_fd == -1) {
25901          ast_log(LOG_ERROR, "TLS Server start failed. Not listening on TLS socket.\n");
25902          sip_tls_desc.tls_cfg = NULL;
25903       }
25904    } else if (sip_tls_desc.tls_cfg->enabled) {
25905       sip_tls_desc.tls_cfg = NULL;
25906       ast_log(LOG_WARNING, "SIP TLS server did not load because of errors.\n");
25907    }
25908 
25909    if (ucfg) {
25910       struct ast_variable *gen;
25911       int genhassip, genregistersip;
25912       const char *hassip, *registersip;
25913       
25914       genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
25915       genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
25916       gen = ast_variable_browse(ucfg, "general");
25917       cat = ast_category_browse(ucfg, NULL);
25918       while (cat) {
25919          if (strcasecmp(cat, "general")) {
25920             hassip = ast_variable_retrieve(ucfg, cat, "hassip");
25921             registersip = ast_variable_retrieve(ucfg, cat, "registersip");
25922             if (ast_true(hassip) || (!hassip && genhassip)) {
25923                peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0, 0);
25924                if (peer) {
25925                   /* user.conf entries are always of type friend */
25926                   peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
25927                   ao2_t_link(peers, peer, "link peer into peer table");
25928                   if ((peer->type & SIP_TYPE_PEER) && peer->addr.sin_addr.s_addr) {
25929                      ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
25930                   }
25931                   
25932                   unref_peer(peer, "unref_peer: from reload_config");
25933                   peer_count++;
25934                }
25935             }
25936             if (ast_true(registersip) || (!registersip && genregistersip)) {
25937                char tmp[256];
25938                const char *host = ast_variable_retrieve(ucfg, cat, "host");
25939                const char *username = ast_variable_retrieve(ucfg, cat, "username");
25940                const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
25941                const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
25942                const char *authuser = ast_variable_retrieve(ucfg, cat, "authuser");
25943                if (!host)
25944                   host = ast_variable_retrieve(ucfg, "general", "host");
25945                if (!username)
25946                   username = ast_variable_retrieve(ucfg, "general", "username");
25947                if (!secret)
25948                   secret = ast_variable_retrieve(ucfg, "general", "secret");
25949                if (!contact)
25950                   contact = "s";
25951                if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
25952                   if (!ast_strlen_zero(secret)) {
25953                      if (!ast_strlen_zero(authuser)) {
25954                         snprintf(tmp, sizeof(tmp), "%s?%s:%s:%s@%s/%s", cat, username, secret, authuser, host, contact);
25955                      } else {
25956                         snprintf(tmp, sizeof(tmp), "%s?%s:%s@%s/%s", cat, username, secret, host, contact);
25957                      }
25958                   } else if (!ast_strlen_zero(authuser)) {
25959                      snprintf(tmp, sizeof(tmp), "%s?%s::%s@%s/%s", cat, username, authuser, host, contact);
25960                   } else {
25961                      snprintf(tmp, sizeof(tmp), "%s?%s@%s/%s", cat, username, host, contact);
25962                   }
25963                   if (sip_register(tmp, 0) == 0)
25964                      registry_count++;
25965                }
25966             }
25967          }
25968          cat = ast_category_browse(ucfg, cat);
25969       }
25970       ast_config_destroy(ucfg);
25971    }
25972 
25973    /* Load peers, users and friends */
25974    cat = NULL;
25975    while ( (cat = ast_category_browse(cfg, cat)) ) {
25976       const char *utype;
25977       if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
25978          continue;
25979       utype = ast_variable_retrieve(cfg, cat, "type");
25980       if (!utype) {
25981          ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
25982          continue;
25983       } else {
25984          if (!strcasecmp(utype, "user")) {
25985             ;
25986          } else if (!strcasecmp(utype, "friend")) {
25987             ;
25988          } else if (!strcasecmp(utype, "peer")) {
25989             ;
25990          } else {
25991             ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
25992             continue;
25993          }
25994          peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0, 0);
25995          if (peer) {
25996             ao2_t_link(peers, peer, "link peer into peers table");
25997             if ((peer->type & SIP_TYPE_PEER) && peer->addr.sin_addr.s_addr) {
25998                ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
25999             }
26000             unref_peer(peer, "unref the result of the build_peer call. Now, the links from the tables are the only ones left.");
26001             peer_count++;
26002          }
26003       }
26004    }
26005 
26006    /* Add default domains - host name, IP address and IP:port
26007     * Only do this if user added any sip domain with "localdomains" 
26008     * In order to *not* break backwards compatibility 
26009     *    Some phones address us at IP only, some with additional port number 
26010     */
26011    if (auto_sip_domains) {
26012       char temp[MAXHOSTNAMELEN];
26013 
26014       /* First our default IP address */
26015       if (bindaddr.sin_addr.s_addr) {
26016          add_sip_domain(ast_inet_ntoa(bindaddr.sin_addr), SIP_DOMAIN_AUTO, NULL);
26017       } else if (internip.sin_addr.s_addr) {
26018       /* Our internal IP address, if configured */
26019          add_sip_domain(ast_inet_ntoa(internip.sin_addr), SIP_DOMAIN_AUTO, NULL);
26020       } else {
26021          ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
26022       }
26023 
26024       /* If TCP is running on a different IP than UDP, then add it too */
26025       if (sip_tcp_desc.local_address.sin_addr.s_addr && !inaddrcmp(&bindaddr, &sip_tcp_desc.local_address))
26026          add_sip_domain(ast_inet_ntoa(sip_tcp_desc.local_address.sin_addr), SIP_DOMAIN_AUTO, NULL);
26027 
26028       /* If TLS is running on a differen IP than UDP and TCP, then add that too */
26029       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))
26030          add_sip_domain(ast_inet_ntoa(sip_tls_desc.local_address.sin_addr), SIP_DOMAIN_AUTO, NULL);
26031 
26032       /* Our extern IP address, if configured */
26033       if (externip.sin_addr.s_addr)
26034          add_sip_domain(ast_inet_ntoa(externip.sin_addr), SIP_DOMAIN_AUTO, NULL);
26035 
26036       /* Extern host name (NAT traversal support) */
26037       if (!ast_strlen_zero(externhost))
26038          add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
26039       
26040       /* Our host name */
26041       if (!gethostname(temp, sizeof(temp)))
26042          add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
26043    }
26044 
26045    /* Release configuration from memory */
26046    ast_config_destroy(cfg);
26047 
26048    /* Load the list of manual NOTIFY types to support */
26049    if (notify_types)
26050       ast_config_destroy(notify_types);
26051    if ((notify_types = ast_config_load(notify_config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
26052       ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed.\n", notify_config);
26053       notify_types = NULL;
26054    }
26055 
26056    /* Done, tell the manager */
26057    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);
26058    run_end = time(0);
26059    ast_debug(4, "SIP reload_config done...Runtime= %d sec\n", (int)(run_end-run_start));
26060 
26061    return 0;
26062 }
26063 
26064 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
26065 {
26066    struct sip_pvt *p;
26067    struct ast_udptl *udptl = NULL;
26068    
26069    p = chan->tech_pvt;
26070    if (!p)
26071       return NULL;
26072    
26073    sip_pvt_lock(p);
26074    if (p->udptl && ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
26075       udptl = p->udptl;
26076    sip_pvt_unlock(p);
26077    return udptl;
26078 }
26079 
26080 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
26081 {
26082    struct sip_pvt *p;
26083    
26084    p = chan->tech_pvt;
26085    if (!p)
26086       return -1;
26087    sip_pvt_lock(p);
26088    if (udptl)
26089       ast_udptl_get_peer(udptl, &p->udptlredirip);
26090    else
26091       memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
26092    if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
26093       if (!p->pendinginvite) {
26094          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);
26095          transmit_reinvite_with_sdp(p, TRUE, FALSE);
26096       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
26097          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);
26098          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
26099       }
26100    }
26101    /* Reset lastrtprx timer */
26102    p->lastrtprx = p->lastrtptx = time(NULL);
26103    sip_pvt_unlock(p);
26104    return 0;
26105 }
26106 
26107 /*! \brief Returns null if we can't reinvite audio (part of RTP interface) */
26108 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
26109 {
26110    struct sip_pvt *p = NULL;
26111    enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
26112 
26113    if (!(p = chan->tech_pvt))
26114       return AST_RTP_GET_FAILED;
26115 
26116    sip_pvt_lock(p);
26117    if (!(p->rtp)) {
26118       sip_pvt_unlock(p);
26119       return AST_RTP_GET_FAILED;
26120    }
26121 
26122    *rtp = p->rtp;
26123 
26124    if (ast_rtp_getnat(*rtp) && !ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT))
26125       res = AST_RTP_TRY_PARTIAL;
26126    else if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
26127       res = AST_RTP_TRY_NATIVE;
26128    else if (ast_test_flag(&global_jbconf, AST_JB_FORCED))
26129       res = AST_RTP_GET_FAILED;
26130 
26131    sip_pvt_unlock(p);
26132 
26133    return res;
26134 }
26135 
26136 /*! \brief Returns null if we can't reinvite video (part of RTP interface) */
26137 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
26138 {
26139    struct sip_pvt *p = NULL;
26140    enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
26141    
26142    if (!(p = chan->tech_pvt))
26143       return AST_RTP_GET_FAILED;
26144 
26145    sip_pvt_lock(p);
26146    if (!(p->vrtp)) {
26147       sip_pvt_unlock(p);
26148       return AST_RTP_GET_FAILED;
26149    }
26150 
26151    *rtp = p->vrtp;
26152 
26153    if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
26154       res = AST_RTP_TRY_NATIVE;
26155 
26156    sip_pvt_unlock(p);
26157 
26158    return res;
26159 }
26160 
26161 /*! \brief Returns null if we can't reinvite text (part of RTP interface) */
26162 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
26163 {
26164    struct sip_pvt *p = NULL;
26165    enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
26166    
26167    if (!(p = chan->tech_pvt))
26168       return AST_RTP_GET_FAILED;
26169 
26170    sip_pvt_lock(p);
26171    if (!(p->trtp)) {
26172       sip_pvt_unlock(p);
26173       return AST_RTP_GET_FAILED;
26174    }
26175 
26176    *rtp = p->trtp;
26177 
26178    if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
26179       res = AST_RTP_TRY_NATIVE;
26180 
26181    sip_pvt_unlock(p);
26182 
26183    return res;
26184 }
26185 
26186 /*! \brief Set the RTP peer for this call */
26187 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)
26188 {
26189    struct sip_pvt *p;
26190    int changed = 0;
26191 
26192    p = chan->tech_pvt;
26193    if (!p) 
26194       return -1;
26195 
26196    /* Disable early RTP bridge  */
26197    if ((rtp || vrtp || trtp) &&
26198       !ast_bridged_channel(chan) &&
26199       !sip_cfg.directrtpsetup) {
26200          return 0;
26201    }
26202 
26203    sip_pvt_lock(p);
26204    if (p->alreadygone) {
26205       /* If we're destroyed, don't bother */
26206       sip_pvt_unlock(p);
26207       return 0;
26208    }
26209 
26210    /* if this peer cannot handle reinvites of the media stream to devices
26211       that are known to be behind a NAT, then stop the process now
26212    */
26213         if (nat_active && !ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
26214                 sip_pvt_unlock(p);
26215                 return 0;
26216         }
26217 
26218    if (rtp) {
26219       changed |= ast_rtp_get_peer(rtp, &p->redirip);
26220    } else if (p->redirip.sin_addr.s_addr || ntohs(p->redirip.sin_port) != 0) {
26221       memset(&p->redirip, 0, sizeof(p->redirip));
26222       changed = 1;
26223    }
26224    if (vrtp) {
26225       changed |= ast_rtp_get_peer(vrtp, &p->vredirip);
26226    } else if (p->vredirip.sin_addr.s_addr || ntohs(p->vredirip.sin_port) != 0) {
26227       memset(&p->vredirip, 0, sizeof(p->vredirip));
26228       changed = 1;
26229    }
26230    if (trtp) {
26231       changed |= ast_rtp_get_peer(trtp, &p->tredirip);
26232    } else if (p->tredirip.sin_addr.s_addr || ntohs(p->tredirip.sin_port) != 0) {
26233       memset(&p->tredirip, 0, sizeof(p->tredirip));
26234       changed = 1;
26235    }
26236    if (codecs && (p->redircodecs != codecs)) {
26237       p->redircodecs = codecs;
26238       changed = 1;
26239    }
26240    if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
26241       if (chan->_state != AST_STATE_UP) { /* We are in early state */
26242          if (p->do_history)
26243             append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
26244          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));
26245       } else if (!p->pendinginvite) {     /* We are up, and have no outstanding invite */
26246          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));
26247          transmit_reinvite_with_sdp(p, FALSE, FALSE);
26248       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
26249          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));
26250          /* We have a pending Invite. Send re-invite when we're done with the invite */
26251          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);   
26252       }
26253    }
26254    /* Reset lastrtprx timer */
26255    p->lastrtprx = p->lastrtptx = time(NULL);
26256    sip_pvt_unlock(p);
26257    return 0;
26258 }
26259 
26260 static char *app_dtmfmode = "SIPDtmfMode";
26261 static char *app_sipaddheader = "SIPAddHeader";
26262 static char *app_sipremoveheader = "SIPRemoveHeader";
26263 
26264 /*! \brief Set the DTMFmode for an outbound SIP call (application) */
26265 static int sip_dtmfmode(struct ast_channel *chan, void *data)
26266 {
26267    struct sip_pvt *p;
26268    char *mode = data;
26269 
26270    if (!data) {
26271       ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
26272       return 0;
26273    }
26274    ast_channel_lock(chan);
26275    if (!IS_SIP_TECH(chan->tech)) {
26276       ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
26277       ast_channel_unlock(chan);
26278       return 0;
26279    }
26280    p = chan->tech_pvt;
26281    if (!p) {
26282       ast_channel_unlock(chan);
26283       return 0;
26284    }
26285    sip_pvt_lock(p);
26286    if (!strcasecmp(mode, "info")) {
26287       ast_clear_flag(&p->flags[0], SIP_DTMF);
26288       ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
26289       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
26290    } else if (!strcasecmp(mode, "shortinfo")) {
26291       ast_clear_flag(&p->flags[0], SIP_DTMF);
26292       ast_set_flag(&p->flags[0], SIP_DTMF_SHORTINFO);
26293       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
26294    } else if (!strcasecmp(mode, "rfc2833")) {
26295       ast_clear_flag(&p->flags[0], SIP_DTMF);
26296       ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
26297       p->jointnoncodeccapability |= AST_RTP_DTMF;
26298    } else if (!strcasecmp(mode, "inband")) { 
26299       ast_clear_flag(&p->flags[0], SIP_DTMF);
26300       ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
26301       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
26302    } else
26303       ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n", mode);
26304    if (p->rtp)
26305       ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
26306    if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
26307       if (!p->dsp) {
26308          p->dsp = ast_dsp_new();
26309          ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
26310       }
26311    } else {
26312       if (p->dsp) {
26313          ast_dsp_free(p->dsp);
26314          p->dsp = NULL;
26315       }
26316    }
26317    sip_pvt_unlock(p);
26318    ast_channel_unlock(chan);
26319    return 0;
26320 }
26321 
26322 /*! \brief Add a SIP header to an outbound INVITE */
26323 static int sip_addheader(struct ast_channel *chan, void *data)
26324 {
26325    int no = 0;
26326    int ok = FALSE;
26327    char varbuf[30];
26328    char *inbuf = data, *subbuf;
26329    
26330    if (ast_strlen_zero(inbuf)) {
26331       ast_log(LOG_WARNING, "This application requires the argument: Header\n");
26332       return 0;
26333    }
26334    ast_channel_lock(chan);
26335 
26336    /* Check for headers */
26337    while (!ok && no <= 50) {
26338       no++;
26339       snprintf(varbuf, sizeof(varbuf), "__SIPADDHEADER%.2d", no);
26340 
26341       /* Compare without the leading underscores */
26342       if ((pbx_builtin_getvar_helper(chan, (const char *) varbuf + 2) == (const char *) NULL)) {
26343          ok = TRUE;
26344       }
26345    }
26346    if (ok) {
26347       size_t len = strlen(inbuf);
26348       subbuf = alloca(len + 1);
26349       ast_get_encoded_str(inbuf, subbuf, len + 1);
26350       pbx_builtin_setvar_helper(chan, varbuf, subbuf);
26351       if (sipdebug) {
26352          ast_debug(1, "SIP Header added \"%s\" as %s\n", inbuf, varbuf);
26353       }
26354    } else {
26355       ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
26356    }
26357    ast_channel_unlock(chan);
26358    return 0;
26359 }
26360 
26361 /*! \brief Remove SIP headers added previously with SipAddHeader application */
26362 static int sip_removeheader(struct ast_channel *chan, void *data)
26363 {
26364    struct ast_var_t *newvariable;
26365    struct varshead *headp;
26366    int removeall = 0;
26367    char *inbuf = (char *) data;
26368 
26369    if (ast_strlen_zero(inbuf)) {
26370       removeall = 1;
26371    }
26372    ast_channel_lock(chan);
26373  
26374    headp=&chan->varshead;
26375    AST_LIST_TRAVERSE_SAFE_BEGIN (headp, newvariable, entries) {
26376       if (strncasecmp(ast_var_name(newvariable), "SIPADDHEADER", strlen("SIPADDHEADER")) == 0) {
26377          if (removeall || (!strncasecmp(ast_var_value(newvariable),inbuf,strlen(inbuf)))) {
26378             if (sipdebug)
26379                ast_log(LOG_DEBUG,"removing SIP Header \"%s\" as %s\n",
26380                   ast_var_value(newvariable),
26381                   ast_var_name(newvariable));
26382             AST_LIST_REMOVE_CURRENT(entries);
26383             ast_var_delete(newvariable);
26384          }
26385       }
26386    }
26387    AST_LIST_TRAVERSE_SAFE_END;
26388  
26389    ast_channel_unlock(chan);
26390    return 0;
26391 }
26392 
26393 /*! \brief Transfer call before connect with a 302 redirect
26394 \note Called by the transfer() dialplan application through the sip_transfer()
26395    pbx interface function if the call is in ringing state 
26396 \todo Fix this function so that we wait for reply to the REFER and
26397    react to errors, denials or other issues the other end might have.
26398  */
26399 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
26400 {
26401    char *cdest;
26402    char *extension, *host, *port;
26403    char tmp[80];
26404 
26405    cdest = ast_strdupa(dest);
26406    
26407    extension = strsep(&cdest, "@");
26408    host = strsep(&cdest, ":");
26409    port = strsep(&cdest, ":");
26410    if (ast_strlen_zero(extension)) {
26411       ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
26412       return 0;
26413    }
26414 
26415    /* we'll issue the redirect message here */
26416    if (!host) {
26417       char *localtmp;
26418 
26419       ast_copy_string(tmp, get_header(&p->initreq, "To"), sizeof(tmp));
26420       if (ast_strlen_zero(tmp)) {
26421          ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
26422          return 0;
26423       }
26424       if ( ( (localtmp = strcasestr(tmp, "sip:")) || (localtmp = strcasestr(tmp, "sips:")) ) 
26425          && (localtmp = strchr(localtmp, '@'))) {
26426          char lhost[80], lport[80];
26427 
26428          memset(lhost, 0, sizeof(lhost));
26429          memset(lport, 0, sizeof(lport));
26430          localtmp++;
26431          /* This is okey because lhost and lport are as big as tmp */
26432          sscanf(localtmp, "%80[^<>:; ]:%80[^<>:; ]", lhost, lport);
26433          if (ast_strlen_zero(lhost)) {
26434             ast_log(LOG_ERROR, "Can't find the host address\n");
26435             return 0;
26436          }
26437          host = ast_strdupa(lhost);
26438          if (!ast_strlen_zero(lport)) {
26439             port = ast_strdupa(lport);
26440          }
26441       }
26442    }
26443 
26444    ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s%s%s>", extension, host, port ? ":" : "", port ? port : "");
26445    transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
26446 
26447    sip_scheddestroy(p, SIP_TRANS_TIMEOUT);   /* Make sure we stop send this reply. */
26448    sip_alreadygone(p);
26449    /* hangup here */
26450    return 0;
26451 }
26452 
26453 /*! \brief Return SIP UA's codec (part of the RTP interface) */
26454 static int sip_get_codec(struct ast_channel *chan)
26455 {
26456    struct sip_pvt *p = chan->tech_pvt;
26457    return p->jointcapability ? p->jointcapability : p->capability;   
26458 }
26459 
26460 /*! \brief Send a poke to all known peers */
26461 static void sip_poke_all_peers(void)
26462 {
26463    int ms = 0, num = 0;
26464    struct ao2_iterator i;
26465    struct sip_peer *peer;
26466 
26467    if (!speerobjs)   /* No peers, just give up */
26468       return;
26469 
26470    i = ao2_iterator_init(peers, 0);
26471    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
26472       ao2_lock(peer);
26473       if (num == global_qualify_peers) {
26474          ms += global_qualify_gap;
26475          num = 0;
26476       } else {
26477          num++;
26478       }
26479       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ms, sip_poke_peer_s, peer,
26480             unref_peer(_data, "removing poke peer ref"),
26481             unref_peer(peer, "removing poke peer ref"),
26482             ref_peer(peer, "adding poke peer ref"));
26483       ao2_unlock(peer);
26484       unref_peer(peer, "toss iterator peer ptr");
26485    }
26486    ao2_iterator_destroy(&i);
26487 }
26488 
26489 /*! \brief Send all known registrations */
26490 static void sip_send_all_registers(void)
26491 {
26492    int ms;
26493    int regspacing;
26494    if (!regobjs)
26495       return;
26496    regspacing = default_expiry * 1000/regobjs;
26497    if (regspacing > 100)
26498       regspacing = 100;
26499    ms = regspacing;
26500    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
26501       ASTOBJ_WRLOCK(iterator);
26502       ms += regspacing;
26503       AST_SCHED_REPLACE_UNREF(iterator->expire, sched, ms, sip_reregister, iterator, 
26504                         registry_unref(_data, "REPLACE sched del decs the refcount"),
26505                         registry_unref(iterator, "REPLACE sched add failure decs the refcount"),
26506                         registry_addref(iterator, "REPLACE sched add incs the refcount"));
26507       ASTOBJ_UNLOCK(iterator);
26508    } while (0)
26509    );
26510 }
26511 
26512 /*! \brief Send all MWI subscriptions */
26513 static void sip_send_all_mwi_subscriptions(void)
26514 {
26515    ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
26516       ASTOBJ_WRLOCK(iterator);
26517       AST_SCHED_DEL(sched, iterator->resub);
26518       if ((iterator->resub = ast_sched_add(sched, 1, sip_subscribe_mwi_do, ASTOBJ_REF(iterator))) < 0) {
26519          ASTOBJ_UNREF(iterator, sip_subscribe_mwi_destroy);
26520       }
26521       ASTOBJ_UNLOCK(iterator);
26522    } while (0));
26523 }
26524 
26525 /*! \brief Reload module */
26526 static int sip_do_reload(enum channelreloadreason reason)
26527 {
26528    time_t start_poke, end_poke;
26529    
26530    reload_config(reason);
26531    ast_sched_dump(sched);
26532 
26533    start_poke = time(0);
26534    /* Prune peers who still are supposed to be deleted */
26535    unlink_marked_peers_from_tables();
26536 
26537    ast_debug(4, "--------------- Done destroying pruned peers\n");
26538 
26539    /* Send qualify (OPTIONS) to all peers */
26540    sip_poke_all_peers();
26541 
26542    /* Register with all services */
26543    sip_send_all_registers();
26544 
26545    sip_send_all_mwi_subscriptions();
26546 
26547    end_poke = time(0);
26548    
26549    ast_debug(4, "do_reload finished. peer poke/prune reg contact time = %d sec.\n", (int)(end_poke-start_poke));
26550 
26551    ast_debug(4, "--------------- SIP reload done\n");
26552 
26553    return 0;
26554 }
26555 
26556 /*! \brief Force reload of module from cli */
26557 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
26558 {
26559    
26560    switch (cmd) {
26561    case CLI_INIT:
26562       e->command = "sip reload";
26563       e->usage =
26564          "Usage: sip reload\n"
26565          "       Reloads SIP configuration from sip.conf\n";
26566       return NULL;
26567    case CLI_GENERATE:
26568       return NULL;
26569    }
26570 
26571    ast_mutex_lock(&sip_reload_lock);
26572    if (sip_reloading) 
26573       ast_verbose("Previous SIP reload not yet done\n");
26574    else {
26575       sip_reloading = TRUE;
26576       sip_reloadreason = (a && a->fd) ? CHANNEL_CLI_RELOAD : CHANNEL_MODULE_RELOAD;
26577    }
26578    ast_mutex_unlock(&sip_reload_lock);
26579    restart_monitor();
26580 
26581    return CLI_SUCCESS;
26582 }
26583 
26584 /*! \brief  Part of Asterisk module interface */
26585 static int reload(void)
26586 {
26587    if (sip_reload(0, 0, NULL))
26588       return 0;
26589    return 1;
26590 }
26591 
26592 /*! \brief SIP Cli commands definition */
26593 static struct ast_cli_entry cli_sip[] = {
26594    AST_CLI_DEFINE(sip_show_channels, "List active SIP channels or subscriptions"),
26595    AST_CLI_DEFINE(sip_show_channelstats, "List statistics for active SIP channels"),
26596    AST_CLI_DEFINE(sip_show_domains, "List our local SIP domains"),
26597    AST_CLI_DEFINE(sip_show_inuse, "List all inuse/limits"),
26598    AST_CLI_DEFINE(sip_show_objects, "List all SIP object allocations"),
26599    AST_CLI_DEFINE(sip_show_peers, "List defined SIP peers"),
26600    AST_CLI_DEFINE(sip_show_registry, "List SIP registration status"),
26601    AST_CLI_DEFINE(sip_unregister, "Unregister (force expiration) a SIP peer from the registry"),
26602    AST_CLI_DEFINE(sip_show_settings, "Show SIP global settings"),
26603    AST_CLI_DEFINE(sip_show_mwi, "Show MWI subscriptions"),
26604    AST_CLI_DEFINE(sip_cli_notify, "Send a notify packet to a SIP peer"),
26605    AST_CLI_DEFINE(sip_show_channel, "Show detailed SIP channel info"),
26606    AST_CLI_DEFINE(sip_show_history, "Show SIP dialog history"),
26607    AST_CLI_DEFINE(sip_show_peer, "Show details on specific SIP peer"),
26608    AST_CLI_DEFINE(sip_show_users, "List defined SIP users"),
26609    AST_CLI_DEFINE(sip_show_user, "Show details on specific SIP user"),
26610    AST_CLI_DEFINE(sip_qualify_peer, "Send an OPTIONS packet to a peer"),
26611    AST_CLI_DEFINE(sip_show_sched, "Present a report on the status of the sched queue"),
26612    AST_CLI_DEFINE(sip_prune_realtime, "Prune cached Realtime users/peers"),
26613    AST_CLI_DEFINE(sip_do_debug, "Enable/Disable SIP debugging"),
26614    AST_CLI_DEFINE(sip_set_history, "Enable/Disable SIP history"),
26615    AST_CLI_DEFINE(sip_reload, "Reload SIP configuration"),
26616    AST_CLI_DEFINE(sip_show_tcp, "List TCP Connections")
26617 };
26618 
26619 /*! \brief PBX load module - initialization */
26620 static int load_module(void)
26621 {
26622    ast_verbose("SIP channel loading...\n");
26623    /* the fact that ao2_containers can't resize automatically is a major worry! */
26624    /* if the number of objects gets above MAX_XXX_BUCKETS, things will slow down */
26625    peers = ao2_t_container_alloc(HASH_PEER_SIZE, peer_hash_cb, peer_cmp_cb, "allocate peers");
26626    peers_by_ip = ao2_t_container_alloc(HASH_PEER_SIZE, peer_iphash_cb, peer_ipcmp_cb, "allocate peers_by_ip");
26627    dialogs = ao2_t_container_alloc(HASH_DIALOG_SIZE, dialog_hash_cb, dialog_cmp_cb, "allocate dialogs");
26628    threadt = ao2_t_container_alloc(HASH_DIALOG_SIZE, threadt_hash_cb, threadt_cmp_cb, "allocate threadt table");
26629    
26630    ASTOBJ_CONTAINER_INIT(&regl); /* Registry object list -- not searched for anything */
26631    ASTOBJ_CONTAINER_INIT(&submwil); /* MWI subscription object list */
26632 
26633    if (!(sched = sched_context_create())) {
26634       ast_log(LOG_ERROR, "Unable to create scheduler context\n");
26635       return AST_MODULE_LOAD_FAILURE;
26636    }
26637 
26638    if (!(io = io_context_create())) {
26639       ast_log(LOG_ERROR, "Unable to create I/O context\n");
26640       sched_context_destroy(sched);
26641       return AST_MODULE_LOAD_FAILURE;
26642    }
26643 
26644    sip_reloadreason = CHANNEL_MODULE_LOAD;
26645 
26646    if(reload_config(sip_reloadreason)) /* Load the configuration from sip.conf */
26647       return AST_MODULE_LOAD_DECLINE;
26648 
26649    /* Prepare the version that does not require DTMF BEGIN frames.
26650     * We need to use tricks such as memcpy and casts because the variable
26651     * has const fields.
26652     */
26653    memcpy(&sip_tech_info, &sip_tech, sizeof(sip_tech));
26654    memset((void *) &sip_tech_info.send_digit_begin, 0, sizeof(sip_tech_info.send_digit_begin));
26655 
26656    /* Make sure we can register our sip channel type */
26657    if (ast_channel_register(&sip_tech)) {
26658       ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
26659       io_context_destroy(io);
26660       sched_context_destroy(sched);
26661       return AST_MODULE_LOAD_FAILURE;
26662    }
26663 
26664    /* Register all CLI functions for SIP */
26665    ast_cli_register_multiple(cli_sip, ARRAY_LEN(cli_sip));
26666 
26667    /* Tell the RTP subdriver that we're here */
26668    ast_rtp_proto_register(&sip_rtp);
26669 
26670    /* Tell the UDPTL subdriver that we're here */
26671    ast_udptl_proto_register(&sip_udptl);
26672 
26673    /* Register dialplan applications */
26674    ast_register_application_xml(app_dtmfmode, sip_dtmfmode);
26675    ast_register_application_xml(app_sipaddheader, sip_addheader);
26676    ast_register_application_xml(app_sipremoveheader, sip_removeheader);
26677 
26678    /* Register dialplan functions */
26679    ast_custom_function_register(&sip_header_function);
26680    ast_custom_function_register(&sippeer_function);
26681    ast_custom_function_register(&sipchaninfo_function);
26682    ast_custom_function_register(&checksipdomain_function);
26683 
26684    /* Register manager commands */
26685    ast_manager_register2("SIPpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peers,
26686          "List SIP peers (text format)", mandescr_show_peers);
26687    ast_manager_register2("SIPshowpeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peer,
26688          "Show SIP peer (text format)", mandescr_show_peer);
26689    ast_manager_register2("SIPqualifypeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_qualify_peer,
26690          "Show SIP peer (text format)", mandescr_show_peer);   /*! \todo Fix this XXX This must be all wrong XXXX */
26691    ast_manager_register2("SIPshowregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_show_registry,
26692          "Show SIP registrations (text format)", mandescr_show_registry);
26693    ast_manager_register2("SIPnotify", EVENT_FLAG_SYSTEM, manager_sipnotify,
26694          "Send a SIP notify", mandescr_sipnotify);
26695    sip_poke_all_peers();   
26696    sip_send_all_registers();
26697    sip_send_all_mwi_subscriptions();
26698 
26699    /* And start the monitor for the first time */
26700    restart_monitor();
26701 
26702    ast_realtime_require_field(ast_check_realtime("sipregs") ? "sipregs" : "sippeers",
26703       "name", RQ_CHAR, 10,
26704       "ipaddr", RQ_CHAR, 15,
26705       "port", RQ_UINTEGER2, 5,
26706       "regseconds", RQ_INTEGER4, 11,
26707       "defaultuser", RQ_CHAR, 10,
26708       "fullcontact", RQ_CHAR, 35,
26709       "regserver", RQ_CHAR, 20,
26710       "useragent", RQ_CHAR, 20,
26711       "lastms", RQ_INTEGER4, 11,
26712       SENTINEL);
26713 
26714    return AST_MODULE_LOAD_SUCCESS;
26715 }
26716 
26717 /*! \brief PBX unload module API */
26718 static int unload_module(void)
26719 {
26720    struct sip_pvt *p;
26721    struct sip_threadinfo *th;
26722    struct ast_context *con;
26723    struct ao2_iterator i;
26724 
26725    ast_sched_dump(sched);
26726    
26727    /* First, take us out of the channel type list */
26728    ast_channel_unregister(&sip_tech);
26729 
26730    /* Unregister dial plan functions */
26731    ast_custom_function_unregister(&sipchaninfo_function);
26732    ast_custom_function_unregister(&sippeer_function);
26733    ast_custom_function_unregister(&sip_header_function);
26734    ast_custom_function_unregister(&checksipdomain_function);
26735 
26736    /* Unregister dial plan applications */
26737    ast_unregister_application(app_dtmfmode);
26738    ast_unregister_application(app_sipaddheader);
26739    ast_unregister_application(app_sipremoveheader);
26740 
26741    /* Unregister CLI commands */
26742    ast_cli_unregister_multiple(cli_sip, ARRAY_LEN(cli_sip));
26743 
26744    /* Disconnect from the RTP subsystem */
26745    ast_rtp_proto_unregister(&sip_rtp);
26746 
26747    /* Disconnect from UDPTL */
26748    ast_udptl_proto_unregister(&sip_udptl);
26749 
26750    /* Unregister AMI actions */
26751    ast_manager_unregister("SIPpeers");
26752    ast_manager_unregister("SIPshowpeer");
26753    ast_manager_unregister("SIPqualifypeer");
26754    ast_manager_unregister("SIPshowregistry");
26755    ast_manager_unregister("SIPnotify");
26756    
26757    /* Kill TCP/TLS server threads */
26758    if (sip_tcp_desc.master)
26759       ast_tcptls_server_stop(&sip_tcp_desc);
26760    if (sip_tls_desc.master)
26761       ast_tcptls_server_stop(&sip_tls_desc);
26762 
26763    /* Kill all existing TCP/TLS threads */
26764    i = ao2_iterator_init(threadt, 0);
26765    while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
26766       pthread_t thread = th->threadid;
26767       th->stop = 1;
26768       pthread_kill(thread, SIGURG);
26769       pthread_join(thread, NULL);
26770       ao2_t_ref(th, -1, "decrement ref from iterator");
26771    }
26772    ao2_iterator_destroy(&i);
26773 
26774    /* Hangup all dialogs if they have an owner */
26775    i = ao2_iterator_init(dialogs, 0);
26776    while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
26777       if (p->owner)
26778          ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
26779       ao2_t_ref(p, -1, "toss dialog ptr from iterator_next");
26780    }
26781    ao2_iterator_destroy(&i);
26782 
26783    unlink_all_peers_from_tables();
26784 
26785    ast_mutex_lock(&monlock);
26786    if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
26787       pthread_cancel(monitor_thread);
26788       pthread_kill(monitor_thread, SIGURG);
26789       pthread_join(monitor_thread, NULL);
26790    }
26791    monitor_thread = AST_PTHREADT_STOP;
26792    ast_mutex_unlock(&monlock);
26793 
26794    /* Destroy all the dialogs and free their memory */
26795    i = ao2_iterator_init(dialogs, 0);
26796    while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
26797       dialog_unlink_all(p, TRUE, TRUE);
26798       ao2_t_ref(p, -1, "throw away iterator result"); 
26799    }
26800    ao2_iterator_destroy(&i);
26801 
26802    /* Free memory for local network address mask */
26803    ast_free_ha(localaddr);
26804 
26805    clear_realm_authentication(authl);
26806 
26807 
26808    if (default_tls_cfg.certfile)
26809       ast_free(default_tls_cfg.certfile);
26810    if (default_tls_cfg.cipher)
26811       ast_free(default_tls_cfg.cipher);
26812    if (default_tls_cfg.cafile)
26813       ast_free(default_tls_cfg.cafile);
26814    if (default_tls_cfg.capath)
26815       ast_free(default_tls_cfg.capath);
26816 
26817    ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
26818    ASTOBJ_CONTAINER_DESTROY(&regl);
26819    ASTOBJ_CONTAINER_DESTROYALL(&submwil, sip_subscribe_mwi_destroy);
26820    ASTOBJ_CONTAINER_DESTROY(&submwil);
26821 
26822    ao2_t_ref(peers, -1, "unref the peers table");
26823    ao2_t_ref(peers_by_ip, -1, "unref the peers_by_ip table");
26824    ao2_t_ref(dialogs, -1, "unref the dialogs table");
26825    ao2_t_ref(threadt, -1, "unref the thread table");
26826 
26827    clear_sip_domains();
26828    ast_free_ha(global_contact_ha);
26829    close(sipsock);
26830    sched_context_destroy(sched);
26831    con = ast_context_find(used_context);
26832    if (con)
26833       ast_context_destroy(con, "SIP");
26834    ast_unload_realtime("sipregs");
26835    ast_unload_realtime("sippeers");
26836 
26837    return 0;
26838 }
26839 
26840 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Session Initiation Protocol (SIP)",
26841       .load = load_module,
26842       .unload = unload_module,
26843       .reload = reload,
26844           );