Tue Aug 24 2010 19:41:28

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: 282894 $")
00211 
00212 #include <ctype.h>
00213 #include <sys/ioctl.h>
00214 #include <fcntl.h>
00215 #include <signal.h>
00216 #include <sys/signal.h>
00217 #include <regex.h>
00218 #include <time.h>
00219 
00220 #include "asterisk/network.h"
00221 #include "asterisk/paths.h"   /* need ast_config_AST_SYSTEM_NAME */
00222 
00223 #include "asterisk/lock.h"
00224 #include "asterisk/channel.h"
00225 #include "asterisk/config.h"
00226 #include "asterisk/module.h"
00227 #include "asterisk/pbx.h"
00228 #include "asterisk/sched.h"
00229 #include "asterisk/io.h"
00230 #include "asterisk/rtp.h"
00231 #include "asterisk/udptl.h"
00232 #include "asterisk/acl.h"
00233 #include "asterisk/manager.h"
00234 #include "asterisk/callerid.h"
00235 #include "asterisk/cli.h"
00236 #include "asterisk/app.h"
00237 #include "asterisk/musiconhold.h"
00238 #include "asterisk/dsp.h"
00239 #include "asterisk/features.h"
00240 #include "asterisk/srv.h"
00241 #include "asterisk/astdb.h"
00242 #include "asterisk/causes.h"
00243 #include "asterisk/utils.h"
00244 #include "asterisk/file.h"
00245 #include "asterisk/astobj.h"
00246 /* 
00247    Uncomment the define below,  if you are having refcount related memory leaks.
00248    With this uncommented, this module will generate a file, /tmp/refs, which contains
00249    a history of the ao2_ref() calls. To be useful, all calls to ao2_* functions should
00250    be modified to ao2_t_* calls, and include a tag describing what is happening with 
00251    enough detail, to make pairing up a reference count increment with its corresponding decrement.
00252    The refcounter program in utils/ can be invaluable in highlighting objects that are not
00253    balanced, along with the complete history for that object.
00254    In normal operation, the macros defined will throw away the tags, so they do not 
00255    affect the speed of the program at all. They can be considered to be documentation.
00256 */
00257 /* #define  REF_DEBUG 1 */
00258 #include "asterisk/astobj2.h"
00259 #include "asterisk/dnsmgr.h"
00260 #include "asterisk/devicestate.h"
00261 #include "asterisk/linkedlists.h"
00262 #include "asterisk/stringfields.h"
00263 #include "asterisk/monitor.h"
00264 #include "asterisk/netsock.h"
00265 #include "asterisk/localtime.h"
00266 #include "asterisk/abstract_jb.h"
00267 #include "asterisk/threadstorage.h"
00268 #include "asterisk/translate.h"
00269 #include "asterisk/ast_version.h"
00270 #include "asterisk/event.h"
00271 #include "asterisk/tcptls.h"
00272 #include "asterisk/strings.h"
00273 
00274 /*** DOCUMENTATION
00275    <application name="SIPDtmfMode" language="en_US">
00276       <synopsis>
00277          Change the dtmfmode for a SIP call.
00278       </synopsis>
00279       <syntax>
00280          <parameter name="mode" required="true">
00281             <enumlist>
00282                <enum name="inband" />
00283                <enum name="info" />
00284                <enum name="rfc2833" />
00285             </enumlist>
00286          </parameter>
00287       </syntax>
00288       <description>
00289          <para>Changes the dtmfmode for a SIP call.</para>
00290       </description>
00291    </application>
00292    <application name="SIPAddHeader" language="en_US">
00293       <synopsis>
00294          Add a SIP header to the outbound call.
00295       </synopsis>
00296       <syntax argsep=":">
00297          <parameter name="Header" required="true" />
00298          <parameter name="Content" required="true" />
00299       </syntax>
00300       <description>
00301          <para>Adds a header to a SIP call placed with DIAL.</para>
00302          <para>Remember to use the X-header if you are adding non-standard SIP
00303          headers, like <literal>X-Asterisk-Accountcode:</literal>. Use this with care.
00304          Adding the wrong headers may jeopardize the SIP dialog.</para>
00305          <para>Always returns <literal>0</literal>.</para>
00306       </description>
00307    </application>
00308    <application name="SIPRemoveHeader" language="en_US">
00309       <synopsis>
00310          Remove SIP headers previously added with SIPAddHeader
00311       </synopsis>
00312       <syntax>
00313          <parameter name="Header" required="false" />
00314       </syntax>
00315       <description>
00316          <para>SIPRemoveHeader() allows you to remove headers which were previously 
00317          added with SIPAddHeader(). If no parameter is supplied, all previously added 
00318          headers will be removed. If a parameter is supplied, only the matching headers 
00319          will be removed.</para>
00320          <para>For example you have added these 2 headers:</para>
00321          <para>SIPAddHeader(P-Asserted-Identity: sip:foo@bar);</para>
00322          <para>SIPAddHeader(P-Preferred-Identity: sip:bar@foo);</para>
00323          <para></para>
00324          <para>// remove all headers</para>
00325          <para>SIPRemoveHeader();</para>
00326          <para>// remove all P- headers</para>
00327          <para>SIPRemoveHeader(P-);</para>
00328          <para>// remove only the PAI header (note the : at the end)</para>
00329          <para>SIPRemoveHeader(P-Asserted-Identity:);</para>
00330          <para></para>
00331          <para>Always returns <literal>0</literal>.</para>
00332       </description>
00333    </application>
00334    <function name="SIP_HEADER" language="en_US">
00335       <synopsis>
00336          Gets the specified SIP header.
00337       </synopsis>
00338       <syntax>
00339          <parameter name="name" required="true" />
00340          <parameter name="number">
00341             <para>If not specified, defaults to <literal>1</literal>.</para>
00342          </parameter>
00343       </syntax>
00344       <description>
00345          <para>Since there are several headers (such as Via) which can occur multiple
00346          times, SIP_HEADER takes an optional second argument to specify which header with
00347          that name to retrieve. Headers start at offset <literal>1</literal>.</para>
00348       </description>
00349    </function>
00350    <function name="SIPPEER" language="en_US">
00351       <synopsis>
00352          Gets SIP peer information.
00353       </synopsis>
00354       <syntax>
00355          <parameter name="peername" required="true" />
00356          <parameter name="item">
00357             <enumlist>
00358                <enum name="ip">
00359                   <para>(default) The ip address.</para>
00360                </enum>
00361                <enum name="port">
00362                   <para>The port number.</para>
00363                </enum>
00364                <enum name="mailbox">
00365                   <para>The configured mailbox.</para>
00366                </enum>
00367                <enum name="context">
00368                   <para>The configured context.</para>
00369                </enum>
00370                <enum name="expire">
00371                   <para>The epoch time of the next expire.</para>
00372                </enum>
00373                <enum name="dynamic">
00374                   <para>Is it dynamic? (yes/no).</para>
00375                </enum>
00376                <enum name="callerid_name">
00377                   <para>The configured Caller ID name.</para>
00378                </enum>
00379                <enum name="callerid_num">
00380                   <para>The configured Caller ID number.</para>
00381                </enum>
00382                <enum name="callgroup">
00383                   <para>The configured Callgroup.</para>
00384                </enum>
00385                <enum name="pickupgroup">
00386                   <para>The configured Pickupgroup.</para>
00387                </enum>
00388                <enum name="codecs">
00389                   <para>The configured codecs.</para>
00390                </enum>
00391                <enum name="status">
00392                   <para>Status (if qualify=yes).</para>
00393                </enum>
00394                <enum name="regexten">
00395                   <para>Registration extension.</para>
00396                </enum>
00397                <enum name="limit">
00398                   <para>Call limit (call-limit).</para>
00399                </enum>
00400                <enum name="busylevel">
00401                   <para>Configured call level for signalling busy.</para>
00402                </enum>
00403                <enum name="curcalls">
00404                   <para>Current amount of calls. Only available if call-limit is set.</para>
00405                </enum>
00406                <enum name="language">
00407                   <para>Default language for peer.</para>
00408                </enum>
00409                <enum name="accountcode">
00410                   <para>Account code for this peer.</para>
00411                </enum>
00412                <enum name="useragent">
00413                   <para>Current user agent id for peer.</para>
00414                </enum>
00415                <enum name="chanvar[name]">
00416                   <para>A channel variable configured with setvar for this peer.</para>
00417                </enum>
00418                <enum name="codec[x]">
00419                   <para>Preferred codec index number <replaceable>x</replaceable> (beginning with zero).</para>
00420                </enum>
00421             </enumlist>
00422          </parameter>
00423       </syntax>
00424       <description />
00425    </function>
00426    <function name="SIPCHANINFO" language="en_US">
00427       <synopsis>
00428          Gets the specified SIP parameter from the current channel.
00429       </synopsis>
00430       <syntax>
00431          <parameter name="item" required="true">
00432             <enumlist>
00433                <enum name="peerip">
00434                   <para>The IP address of the peer.</para>
00435                </enum>
00436                <enum name="recvip">
00437                   <para>The source IP address of the peer.</para>
00438                </enum>
00439                <enum name="from">
00440                   <para>The URI from the <literal>From:</literal> header.</para>
00441                </enum>
00442                <enum name="uri">
00443                   <para>The URI from the <literal>Contact:</literal> header.</para>
00444                </enum>
00445                <enum name="useragent">
00446                   <para>The useragent.</para>
00447                </enum>
00448                <enum name="peername">
00449                   <para>The name of the peer.</para>
00450                </enum>
00451                <enum name="t38passthrough">
00452                   <para><literal>1</literal> if T38 is offered or enabled in this channel,
00453                   otherwise <literal>0</literal>.</para>
00454                </enum>
00455             </enumlist>
00456          </parameter>
00457       </syntax>
00458       <description />
00459    </function>
00460    <function name="CHECKSIPDOMAIN" language="en_US">
00461       <synopsis>
00462          Checks if domain is a local domain.
00463       </synopsis>
00464       <syntax>
00465          <parameter name="domain" required="true" />
00466       </syntax>
00467       <description>
00468          <para>This function checks if the <replaceable>domain</replaceable> in the argument is configured
00469          as a local SIP domain that this Asterisk server is configured to handle.
00470          Returns the domain name if it is locally handled, otherwise an empty string.
00471          Check the <literal>domain=</literal> configuration in <filename>sip.conf</filename>.</para>
00472       </description>
00473    </function>
00474  ***/
00475 
00476 #ifndef FALSE
00477 #define FALSE    0
00478 #endif
00479 
00480 #ifndef TRUE
00481 #define TRUE     1
00482 #endif
00483 
00484 /* Arguments for find_peer */
00485 #define FINDUSERS (1 << 0)
00486 #define FINDPEERS (1 << 1)
00487 #define FINDALLDEVICES (FINDUSERS | FINDPEERS)
00488 
00489 #define  SIPBUFSIZE     512      /*!< Buffer size for many operations */
00490 
00491 #define XMIT_ERROR      -2
00492 
00493 #define SIP_RESERVED ";/?:@&=+$,# "    /*!< Reserved characters in the username part of the URI */
00494 
00495 /* #define VOCAL_DATA_HACK */
00496 
00497 #define DEFAULT_DEFAULT_EXPIRY  120
00498 #define DEFAULT_MIN_EXPIRY      60
00499 #define DEFAULT_MAX_EXPIRY      3600
00500 #define DEFAULT_MWI_EXPIRY      3600
00501 #define DEFAULT_REGISTRATION_TIMEOUT 20
00502 #define DEFAULT_MAX_FORWARDS    "70"
00503 
00504 /* guard limit must be larger than guard secs */
00505 /* guard min must be < 1000, and should be >= 250 */
00506 #define EXPIRY_GUARD_SECS       15                /*!< How long before expiry do we reregister */
00507 #define EXPIRY_GUARD_LIMIT      30                /*!< Below here, we use EXPIRY_GUARD_PCT instead of 
00508                                                     EXPIRY_GUARD_SECS */
00509 #define EXPIRY_GUARD_MIN        500                /*!< This is the minimum guard time applied. If 
00510                                                    GUARD_PCT turns out to be lower than this, it 
00511                                                    will use this time instead.
00512                                                    This is in milliseconds. */
00513 #define EXPIRY_GUARD_PCT        0.20                /*!< Percentage of expires timeout to use when 
00514                                                     below EXPIRY_GUARD_LIMIT */
00515 #define DEFAULT_EXPIRY 900                          /*!< Expire slowly */
00516 
00517 static int min_expiry = DEFAULT_MIN_EXPIRY;        /*!< Minimum accepted registration time */
00518 static int max_expiry = DEFAULT_MAX_EXPIRY;        /*!< Maximum accepted registration time */
00519 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
00520 static int mwi_expiry = DEFAULT_MWI_EXPIRY;
00521 
00522 #define DEFAULT_QUALIFY_GAP   100
00523 #define DEFAULT_QUALIFY_PEERS 1
00524 
00525 
00526 #define CALLERID_UNKNOWN             "Anonymous"
00527 #define FROMDOMAIN_INVALID           "anonymous.invalid"
00528 
00529 #define DEFAULT_MAXMS                2000             /*!< Qualification: Must be faster than 2 seconds by default */
00530 #define DEFAULT_QUALIFYFREQ          60 * 1000        /*!< Qualification: How often to check for the host to be up */
00531 #define DEFAULT_FREQ_NOTOK           10 * 1000        /*!< Qualification: How often to check, if the host is down... */
00532 
00533 #define DEFAULT_RETRANS              1000             /*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
00534 #define MAX_RETRANS                  6                /*!< Try only 6 times for retransmissions, a total of 7 transmissions */
00535 #define DEFAULT_TIMER_T1                 500              /*!< SIP timer T1 (according to RFC 3261) */
00536 #define SIP_TRANS_TIMEOUT            64 * DEFAULT_TIMER_T1 /*!< SIP request timeout (rfc 3261) 64*T1 
00537                                                       \todo Use known T1 for timeout (peerpoke)
00538                                                       */
00539 #define DEFAULT_TRANS_TIMEOUT        -1               /*!< Use default SIP transaction timeout */
00540 #define PROVIS_KEEPALIVE_TIMEOUT     60000            /*!< How long to wait before retransmitting a provisional response (rfc 3261 13.3.1.1) */
00541 #define MAX_AUTHTRIES                3                /*!< Try authentication three times, then fail */
00542 
00543 #define SIP_MAX_HEADERS              64               /*!< Max amount of SIP headers to read */
00544 #define SIP_MAX_LINES                256              /*!< Max amount of lines in SIP attachment (like SDP) */
00545 #define SIP_MIN_PACKET               4096             /*!< Initialize size of memory to allocate for packets */
00546 #define MAX_HISTORY_ENTRIES        50                /*!< Max entires in the history list for a sip_pvt */
00547 
00548 #define INITIAL_CSEQ                 101              /*!< Our initial sip sequence number */
00549 
00550 #define DEFAULT_MAX_SE               1800             /*!< Session-Timer Default Session-Expires period (RFC 4028) */
00551 #define DEFAULT_MIN_SE               90               /*!< Session-Timer Default Min-SE period (RFC 4028) */
00552 
00553 #define SDP_MAX_RTPMAP_CODECS        32               /*!< Maximum number of codecs allowed in received SDP */
00554 
00555 /*! \brief Global jitterbuffer configuration - by default, jb is disabled */
00556 static struct ast_jb_conf default_jbconf =
00557 {
00558    .flags = 0,
00559    .max_size = -1,
00560    .resync_threshold = -1,
00561    .impl = "",
00562    .target_extra = -1,
00563 };
00564 static struct ast_jb_conf global_jbconf;     /*!< Global jitterbuffer configuration */
00565 
00566 static const char config[] = "sip.conf";     /*!< Main configuration file */
00567 static const char notify_config[] = "sip_notify.conf";   /*!< Configuration file for sending Notify with CLI commands to reconfigure or reboot phones */
00568 
00569 #define RTP    1
00570 #define NO_RTP 0
00571 
00572 /*! \brief Authorization scheme for call transfers 
00573 
00574 \note Not a bitfield flag, since there are plans for other modes,
00575    like "only allow transfers for authenticated devices" */
00576 enum transfermodes {
00577    TRANSFER_OPENFORALL,            /*!< Allow all SIP transfers */
00578    TRANSFER_CLOSED,                /*!< Allow no SIP transfers */
00579 };
00580 
00581 
00582 /*! \brief The result of a lot of functions */
00583 enum sip_result {
00584    AST_SUCCESS = 0,     /*!< FALSE means success, funny enough */
00585    AST_FAILURE = -1,    /*!< Failure code */
00586 };
00587 
00588 /*! \brief States for the INVITE transaction, not the dialog 
00589    \note this is for the INVITE that sets up the dialog
00590 */
00591 enum invitestates {
00592    INV_NONE = 0,          /*!< No state at all, maybe not an INVITE dialog */
00593    INV_CALLING = 1,  /*!< Invite sent, no answer */
00594    INV_PROCEEDING = 2,  /*!< We got/sent 1xx message */
00595    INV_EARLY_MEDIA = 3,    /*!< We got 18x message with to-tag back */
00596    INV_COMPLETED = 4,   /*!< Got final response with error. Wait for ACK, then CONFIRMED */
00597    INV_CONFIRMED = 5,   /*!< Confirmed response - we've got an ack (Incoming calls only) */
00598    INV_TERMINATED = 6,  /*!< Transaction done - either successful (AST_STATE_UP) or failed, but done 
00599                  The only way out of this is a BYE from one side */
00600    INV_CANCELLED = 7,   /*!< Transaction cancelled by client or server in non-terminated state */
00601 };
00602 
00603 /*! \brief Readable descriptions of device states.
00604        \note Should be aligned to above table as index */
00605 static const struct invstate2stringtable {
00606    const enum invitestates state;
00607    const char *desc;
00608 } invitestate2string[] = {
00609    {INV_NONE,              "None"  },
00610    {INV_CALLING,           "Calling (Trying)"},
00611    {INV_PROCEEDING,        "Proceeding "},
00612    {INV_EARLY_MEDIA,       "Early media"},
00613    {INV_COMPLETED,         "Completed (done)"},
00614    {INV_CONFIRMED,         "Confirmed (up)"},
00615    {INV_TERMINATED,        "Done"},
00616    {INV_CANCELLED,         "Cancelled"}
00617 };
00618 
00619 /*! \brief When sending a SIP message, we can send with a few options, depending on
00620    type of SIP request. UNRELIABLE is moslty used for responses to repeated requests,
00621    where the original response would be sent RELIABLE in an INVITE transaction */
00622 enum xmittype {
00623    XMIT_CRITICAL = 2,              /*!< Transmit critical SIP message reliably, with re-transmits.
00624                                               If it fails, it's critical and will cause a teardown of the session */
00625    XMIT_RELIABLE = 1,              /*!< Transmit SIP message reliably, with re-transmits */
00626    XMIT_UNRELIABLE = 0,            /*!< Transmit SIP message without bothering with re-transmits */
00627 };
00628 
00629 /*! \brief Results from the parse_register() function */
00630 enum parse_register_result {
00631    PARSE_REGISTER_DENIED,
00632    PARSE_REGISTER_FAILED,
00633    PARSE_REGISTER_UPDATE,
00634    PARSE_REGISTER_QUERY,
00635 };
00636 
00637 /*! \brief Type of subscription, based on the packages we do support, see \ref subscription_types */
00638 enum subscriptiontype { 
00639    NONE = 0,
00640    XPIDF_XML,
00641    DIALOG_INFO_XML,
00642    CPIM_PIDF_XML,
00643    PIDF_XML,
00644    MWI_NOTIFICATION
00645 };
00646 
00647 /*! \brief Subscription types that we support. We support
00648    - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
00649    - SIMPLE presence used for device status
00650    - Voicemail notification subscriptions
00651 */
00652 static const struct cfsubscription_types {
00653    enum subscriptiontype type;
00654    const char * const event;
00655    const char * const mediatype;
00656    const char * const text;
00657 } subscription_types[] = {
00658    { NONE,        "-",        "unknown",               "unknown" },
00659    /* RFC 4235: SIP Dialog event package */
00660    { DIALOG_INFO_XML, "dialog",   "application/dialog-info+xml", "dialog-info+xml" },
00661    { CPIM_PIDF_XML,   "presence", "application/cpim-pidf+xml",   "cpim-pidf+xml" },  /* RFC 3863 */
00662    { PIDF_XML,        "presence", "application/pidf+xml",        "pidf+xml" },       /* RFC 3863 */
00663    { XPIDF_XML,       "presence", "application/xpidf+xml",       "xpidf+xml" },       /* Pre-RFC 3863 with MS additions */
00664    { MWI_NOTIFICATION,  "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
00665 };
00666 
00667 
00668 /*! \brief Authentication types - proxy or www authentication 
00669    \note Endpoints, like Asterisk, should always use WWW authentication to
00670    allow multiple authentications in the same call - to the proxy and
00671    to the end point.
00672 */
00673 enum sip_auth_type {
00674    PROXY_AUTH = 407,
00675    WWW_AUTH = 401,
00676 };
00677 
00678 /*! \brief Authentication result from check_auth* functions */
00679 enum check_auth_result {
00680    AUTH_DONT_KNOW = -100,  /*!< no result, need to check further */
00681       /* XXX maybe this is the same as AUTH_NOT_FOUND */
00682 
00683    AUTH_SUCCESSFUL = 0,
00684    AUTH_CHALLENGE_SENT = 1,
00685    AUTH_SECRET_FAILED = -1,
00686    AUTH_USERNAME_MISMATCH = -2,
00687    AUTH_NOT_FOUND = -3, /*!< returned by register_verify */
00688    AUTH_FAKE_AUTH = -4,
00689    AUTH_UNKNOWN_DOMAIN = -5,
00690    AUTH_PEER_NOT_DYNAMIC = -6,
00691    AUTH_ACL_FAILED = -7,
00692    AUTH_BAD_TRANSPORT = -8,
00693 };
00694 
00695 /*! \brief States for outbound registrations (with register= lines in sip.conf */
00696 enum sipregistrystate {
00697    REG_STATE_UNREGISTERED = 0,   /*!< We are not registered 
00698        *  \note Initial state. We should have a timeout scheduled for the initial
00699        * (or next) registration transmission, calling sip_reregister
00700        */
00701 
00702    REG_STATE_REGSENT,   /*!< Registration request sent 
00703        * \note sent initial request, waiting for an ack or a timeout to
00704        * retransmit the initial request.
00705       */
00706 
00707    REG_STATE_AUTHSENT,  /*!< We have tried to authenticate 
00708        * \note entered after transmit_register with auth info,
00709        * waiting for an ack.
00710        */
00711 
00712    REG_STATE_REGISTERED,   /*!< Registered and done */
00713 
00714    REG_STATE_REJECTED,  /*!< Registration rejected *
00715        * \note only used when the remote party has an expire larger than
00716        * our max-expire. This is a final state from which we do not
00717        * recover (not sure how correctly).
00718        */
00719 
00720    REG_STATE_TIMEOUT,   /*!< Registration timed out *
00721       * \note XXX unused */
00722 
00723    REG_STATE_NOAUTH, /*!< We have no accepted credentials
00724        * \note fatal - no chance to proceed */
00725 
00726    REG_STATE_FAILED, /*!< Registration failed after several tries
00727        * \note fatal - no chance to proceed */
00728 };
00729 
00730 /*! \brief Modes in which Asterisk can be configured to run SIP Session-Timers */
00731 enum st_mode {
00732         SESSION_TIMER_MODE_INVALID = 0, /*!< Invalid value */ 
00733         SESSION_TIMER_MODE_ACCEPT,      /*!< Honor inbound Session-Timer requests */
00734         SESSION_TIMER_MODE_ORIGINATE,   /*!< Originate outbound and honor inbound requests */
00735         SESSION_TIMER_MODE_REFUSE       /*!< Ignore inbound Session-Timers requests */
00736 };
00737 
00738 /*! \brief The entity playing the refresher role for Session-Timers */
00739 enum st_refresher {
00740         SESSION_TIMER_REFRESHER_AUTO,    /*!< Negotiated                      */
00741         SESSION_TIMER_REFRESHER_UAC,     /*!< Session is refreshed by the UAC */
00742         SESSION_TIMER_REFRESHER_UAS      /*!< Session is refreshed by the UAS */
00743 };
00744 
00745 /*! \brief Define some implemented SIP transports 
00746    \note Asterisk does not support SCTP or UDP/DTLS 
00747 */
00748 enum sip_transport {
00749    SIP_TRANSPORT_UDP = 1,     /*!< Unreliable transport for SIP, needs retransmissions */
00750    SIP_TRANSPORT_TCP = 1 << 1,   /*!< Reliable, but unsecure */
00751    SIP_TRANSPORT_TLS = 1 << 2,   /*!< TCP/TLS - reliable and secure transport for signalling */
00752 };
00753 
00754 /*! \brief definition of a sip proxy server
00755  *
00756  * For outbound proxies, a sip_peer will contain a reference to a 
00757  * dynamically allocated instance of a sip_proxy. A sip_pvt may also
00758  * contain a reference to a peer's outboundproxy, or it may contain
00759  * a reference to the sip_cfg.outboundproxy.
00760  */
00761 struct sip_proxy {
00762    char name[MAXHOSTNAMELEN];      /*!< DNS name of domain/host or IP */
00763    struct sockaddr_in ip;          /*!< Currently used IP address and port */
00764    time_t last_dnsupdate;          /*!< When this was resolved */
00765    enum sip_transport transport; 
00766    int force;                      /*!< If it's an outbound proxy, Force use of this outbound proxy for all outbound requests */
00767    /* Room for a SRV record chain based on the name */
00768 };
00769 
00770 /*! \brief argument for the 'show channels|subscriptions' callback. */
00771 struct __show_chan_arg { 
00772    int fd;
00773    int subscriptions;
00774    int numchans;   /* return value */
00775 };
00776 
00777 
00778 /*! \brief States whether a SIP message can create a dialog in Asterisk. */
00779 enum can_create_dialog {
00780    CAN_NOT_CREATE_DIALOG,
00781    CAN_CREATE_DIALOG,
00782    CAN_CREATE_DIALOG_UNSUPPORTED_METHOD,
00783 };
00784 
00785 /*! \brief SIP Request methods known by Asterisk 
00786 
00787    \note Do _NOT_ make any changes to this enum, or the array following it;
00788    if you think you are doing the right thing, you are probably
00789    not doing the right thing. If you think there are changes
00790    needed, get someone else to review them first _before_
00791    submitting a patch. If these two lists do not match properly
00792    bad things will happen.
00793 */
00794 
00795 enum sipmethod {
00796    SIP_UNKNOWN,      /*!< Unknown response */
00797    SIP_RESPONSE,     /*!< Not request, response to outbound request */
00798    SIP_REGISTER,     /*!< Registration to the mothership, tell us where you are located */
00799    SIP_OPTIONS,      /*!< Check capabilities of a device, used for "ping" too */
00800    SIP_NOTIFY,    /*!< Status update, Part of the event package standard, result of a SUBSCRIBE or a REFER */
00801    SIP_INVITE,    /*!< Set up a session */
00802    SIP_ACK,    /*!< End of a three-way handshake started with INVITE. */
00803    SIP_PRACK,     /*!< Reliable pre-call signalling. Not supported in Asterisk. */
00804    SIP_BYE,    /*!< End of a session */
00805    SIP_REFER,     /*!< Refer to another URI (transfer) */
00806    SIP_SUBSCRIBE,    /*!< Subscribe for updates (voicemail, session status, device status, presence) */
00807    SIP_MESSAGE,      /*!< Text messaging */
00808    SIP_UPDATE,    /*!< Update a dialog. We can send UPDATE; but not accept it */
00809    SIP_INFO,      /*!< Information updates during a session */
00810    SIP_CANCEL,    /*!< Cancel an INVITE */
00811    SIP_PUBLISH,      /*!< Not supported in Asterisk */
00812    SIP_PING,      /*!< Not supported at all, no standard but still implemented out there */
00813 };
00814 
00815 /*! \brief Settings for the 'notifycid' option, see sip.conf.sample for details. */
00816 enum notifycid_setting {
00817    DISABLED       = 0,
00818    ENABLED        = 1,
00819    IGNORE_CONTEXT = 2,
00820 };
00821 
00822 /*! \brief The core structure to setup dialogs. We parse incoming messages by using
00823    structure and then route the messages according to the type.
00824 
00825       \note Note that sip_methods[i].id == i must hold or the code breaks */
00826 static const struct  cfsip_methods { 
00827    enum sipmethod id;
00828    int need_rtp;     /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
00829    char * const text;
00830    enum can_create_dialog can_create;
00831 } sip_methods[] = {
00832    { SIP_UNKNOWN,  RTP,    "-UNKNOWN-",   CAN_CREATE_DIALOG },
00833    { SIP_RESPONSE,    NO_RTP, "SIP/2.0",  CAN_NOT_CREATE_DIALOG },
00834    { SIP_REGISTER,    NO_RTP, "REGISTER",    CAN_CREATE_DIALOG },
00835    { SIP_OPTIONS,  NO_RTP, "OPTIONS",  CAN_CREATE_DIALOG },
00836    { SIP_NOTIFY,   NO_RTP, "NOTIFY",   CAN_CREATE_DIALOG },
00837    { SIP_INVITE,   RTP,    "INVITE",   CAN_CREATE_DIALOG },
00838    { SIP_ACK,   NO_RTP, "ACK",   CAN_NOT_CREATE_DIALOG },
00839    { SIP_PRACK,    NO_RTP, "PRACK",    CAN_NOT_CREATE_DIALOG },
00840    { SIP_BYE,   NO_RTP, "BYE",   CAN_NOT_CREATE_DIALOG },
00841    { SIP_REFER,    NO_RTP, "REFER",    CAN_CREATE_DIALOG },
00842    { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",  CAN_CREATE_DIALOG },
00843    { SIP_MESSAGE,  NO_RTP, "MESSAGE",  CAN_CREATE_DIALOG },
00844    { SIP_UPDATE,   NO_RTP, "UPDATE",   CAN_NOT_CREATE_DIALOG },
00845    { SIP_INFO,  NO_RTP, "INFO",  CAN_NOT_CREATE_DIALOG },
00846    { SIP_CANCEL,   NO_RTP, "CANCEL",   CAN_NOT_CREATE_DIALOG },
00847    { SIP_PUBLISH,  NO_RTP, "PUBLISH",  CAN_CREATE_DIALOG_UNSUPPORTED_METHOD },
00848    { SIP_PING,  NO_RTP, "PING",  CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
00849 };
00850 
00851 static unsigned int chan_idx;
00852 
00853 /*!  Define SIP option tags, used in Require: and Supported: headers 
00854    We need to be aware of these properties in the phones to use 
00855    the replace: header. We should not do that without knowing
00856    that the other end supports it... 
00857    This is nothing we can configure, we learn by the dialog
00858    Supported: header on the REGISTER (peer) or the INVITE
00859    (other devices)
00860    We are not using many of these today, but will in the future.
00861    This is documented in RFC 3261
00862 */
00863 #define SUPPORTED    1
00864 #define NOT_SUPPORTED      0
00865 
00866 /* SIP options */
00867 #define SIP_OPT_REPLACES   (1 << 0)
00868 #define SIP_OPT_100REL     (1 << 1)
00869 #define SIP_OPT_TIMER      (1 << 2)
00870 #define SIP_OPT_EARLY_SESSION (1 << 3)
00871 #define SIP_OPT_JOIN    (1 << 4)
00872 #define SIP_OPT_PATH    (1 << 5)
00873 #define SIP_OPT_PREF    (1 << 6)
00874 #define SIP_OPT_PRECONDITION  (1 << 7)
00875 #define SIP_OPT_PRIVACY    (1 << 8)
00876 #define SIP_OPT_SDP_ANAT   (1 << 9)
00877 #define SIP_OPT_SEC_AGREE  (1 << 10)
00878 #define SIP_OPT_EVENTLIST  (1 << 11)
00879 #define SIP_OPT_GRUU    (1 << 12)
00880 #define SIP_OPT_TARGET_DIALOG (1 << 13)
00881 #define SIP_OPT_NOREFERSUB (1 << 14)
00882 #define SIP_OPT_HISTINFO   (1 << 15)
00883 #define SIP_OPT_RESPRIORITY   (1 << 16)
00884 #define SIP_OPT_FROMCHANGE (1 << 17)
00885 #define SIP_OPT_RECLISTINV (1 << 18)
00886 #define SIP_OPT_RECLISTSUB (1 << 19)
00887 #define SIP_OPT_OUTBOUND   (1 << 20)
00888 #define SIP_OPT_UNKNOWN    (1 << 21)
00889 
00890 
00891 /*! \brief List of well-known SIP options. If we get this in a require,
00892    we should check the list and answer accordingly. */
00893 static const struct cfsip_options {
00894    int id;        /*!< Bitmap ID */
00895    int supported;    /*!< Supported by Asterisk ? */
00896    char * const text;   /*!< Text id, as in standard */
00897 } sip_options[] = {  /* XXX used in 3 places */
00898    /* RFC3262: PRACK 100% reliability */
00899    { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" }, 
00900    /* RFC3959: SIP Early session support */
00901    { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED,   "early-session" },
00902    /* SIMPLE events:  RFC4662 */
00903    { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
00904    /* RFC 4916- Connected line ID updates */
00905    { SIP_OPT_FROMCHANGE,   NOT_SUPPORTED, "from-change" },
00906    /* GRUU: Globally Routable User Agent URI's */
00907    { SIP_OPT_GRUU,      NOT_SUPPORTED, "gruu" },
00908    /* RFC4244 History info */
00909    { SIP_OPT_HISTINFO,  NOT_SUPPORTED, "histinfo" },
00910    /* RFC3911: SIP Join header support */
00911    { SIP_OPT_JOIN,      NOT_SUPPORTED, "join" },
00912    /* Disable the REFER subscription, RFC 4488 */
00913    { SIP_OPT_NOREFERSUB,   NOT_SUPPORTED, "norefersub" },
00914    /* SIP outbound - the final NAT battle - draft-sip-outbound */
00915    { SIP_OPT_OUTBOUND,  NOT_SUPPORTED, "outbound" },
00916    /* RFC3327: Path support */
00917    { SIP_OPT_PATH,      NOT_SUPPORTED, "path" },
00918    /* RFC3840: Callee preferences */
00919    { SIP_OPT_PREF,      NOT_SUPPORTED, "pref" },
00920    /* RFC3312: Precondition support */
00921    { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
00922    /* RFC3323: Privacy with proxies*/
00923    { SIP_OPT_PRIVACY,   NOT_SUPPORTED, "privacy" },
00924    /* RFC-ietf-sip-uri-list-conferencing-02.txt conference invite lists */
00925    { SIP_OPT_RECLISTINV,   NOT_SUPPORTED, "recipient-list-invite" },
00926    /* RFC-ietf-sip-uri-list-subscribe-02.txt - subscription lists */
00927    { SIP_OPT_RECLISTSUB,   NOT_SUPPORTED, "recipient-list-subscribe" },
00928    /* RFC3891: Replaces: header for transfer */
00929    { SIP_OPT_REPLACES,  SUPPORTED,  "replaces" },  
00930    /* One version of Polycom firmware has the wrong label */
00931    { SIP_OPT_REPLACES,  SUPPORTED,  "replace" },   
00932    /* RFC4412 Resource priorities */
00933    { SIP_OPT_RESPRIORITY,  NOT_SUPPORTED, "resource-priority" },
00934    /* RFC3329: Security agreement mechanism */
00935    { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
00936    /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
00937    { SIP_OPT_SDP_ANAT,  NOT_SUPPORTED, "sdp-anat" },
00938    /* RFC4028: SIP Session-Timers */
00939    { SIP_OPT_TIMER,  SUPPORTED,  "timer" },
00940    /* RFC4538: Target-dialog */
00941    { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "tdialog" },
00942 };
00943 
00944 
00945 /*! \brief SIP Methods we support 
00946    \todo This string should be set dynamically. We only support REFER and SUBSCRIBE if we have
00947    allowsubscribe and allowrefer on in sip.conf.
00948 */
00949 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY, INFO"
00950 
00951 /*! \brief SIP Extensions we support 
00952    \note This should be generated based on the previous array
00953       in combination with settings.
00954    \todo We should not have "timer" if it's disabled in the configuration file.
00955 */
00956 #define SUPPORTED_EXTENSIONS "replaces, timer" 
00957 
00958 /*! \brief Standard SIP unsecure port for UDP and TCP from RFC 3261. DO NOT CHANGE THIS */
00959 #define STANDARD_SIP_PORT  5060
00960 /*! \brief Standard SIP TLS port from RFC 3261. DO NOT CHANGE THIS */
00961 #define STANDARD_TLS_PORT  5061
00962 
00963 /*! \note in many SIP headers, absence of a port number implies port 5060,
00964  * and this is why we cannot change the above constant.
00965  * There is a limited number of places in asterisk where we could,
00966  * in principle, use a different "default" port number, but
00967  * we do not support this feature at the moment.
00968  * You can run Asterisk with SIP on a different port with a configuration
00969  * option. If you change this value, the signalling will be incorrect.
00970  */
00971 
00972 /*! \name DefaultValues Default values, set and reset in reload_config before reading configuration 
00973 
00974    These are default values in the source. There are other recommended values in the
00975    sip.conf.sample for new installations. These may differ to keep backwards compatibility,
00976    yet encouraging new behaviour on new installations 
00977  */
00978 /*@{*/ 
00979 #define DEFAULT_CONTEXT    "default"   /*!< The default context for [general] section as well as devices */
00980 #define DEFAULT_MOHINTERPRET    "default" /*!< The default music class */
00981 #define DEFAULT_MOHSUGGEST      ""
00982 #define DEFAULT_VMEXTEN    "asterisk"  /*!< Default voicemail extension */
00983 #define DEFAULT_CALLERID   "asterisk"  /*!< Default caller ID */
00984 #define DEFAULT_NOTIFYMIME    "application/simple-message-summary"
00985 #define DEFAULT_ALLOWGUEST TRUE
00986 #define DEFAULT_RTPKEEPALIVE  0     /*!< Default RTPkeepalive setting */
00987 #define DEFAULT_CALLCOUNTER   FALSE
00988 #define DEFAULT_SRVLOOKUP  TRUE     /*!< Recommended setting is ON */
00989 #define DEFAULT_COMPACTHEADERS   FALSE    /*!< Send compact (one-character) SIP headers. Default off */
00990 #define DEFAULT_TOS_SIP         0               /*!< Call signalling packets should be marked as DSCP CS3, but the default is 0 to be compatible with previous versions. */
00991 #define DEFAULT_TOS_AUDIO       0               /*!< Audio packets should be marked as DSCP EF (Expedited Forwarding), but the default is 0 to be compatible with previous versions. */
00992 #define DEFAULT_TOS_VIDEO       0               /*!< Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions. */
00993 #define DEFAULT_TOS_TEXT        0               /*!< Text packets should be marked as XXXX XXXX, but the default is 0 to be compatible with previous versions. */
00994 #define DEFAULT_COS_SIP         4      /*!< Level 2 class of service for SIP signalling */
00995 #define DEFAULT_COS_AUDIO       5      /*!< Level 2 class of service for audio media  */
00996 #define DEFAULT_COS_VIDEO       6      /*!< Level 2 class of service for video media */
00997 #define DEFAULT_COS_TEXT        5      /*!< Level 2 class of service for text media (T.140) */
00998 #define DEFAULT_ALLOW_EXT_DOM TRUE     /*!< Allow external domains */
00999 #define DEFAULT_REALM      "asterisk"  /*!< Realm for HTTP digest authentication */
01000 #define DEFAULT_NOTIFYRINGING TRUE     /*!< Notify devicestate system on ringing state */
01001 #define DEFAULT_NOTIFYCID     DISABLED /*!< Include CID with ringing notifications */
01002 #define DEFAULT_PEDANTIC   FALSE    /*!< Avoid following SIP standards for dialog matching */
01003 #define DEFAULT_AUTOCREATEPEER   FALSE    /*!< Don't create peers automagically */
01004 #define  DEFAULT_MATCHEXTERNIPLOCALLY FALSE  /*!< Match extern IP locally default setting */
01005 #define DEFAULT_QUALIFY    FALSE    /*!< Don't monitor devices */
01006 #define DEFAULT_CALLEVENTS FALSE    /*!< Extra manager SIP call events */
01007 #define DEFAULT_ALWAYSAUTHREJECT FALSE /*!< Don't reject authentication requests always */
01008 #define DEFAULT_REGEXTENONQUALIFY FALSE
01009 #define DEFAULT_T1MIN      100      /*!< 100 MS for minimal roundtrip time */
01010 #define DEFAULT_MAX_CALL_BITRATE (384)    /*!< Max bitrate for video */
01011 #ifndef DEFAULT_USERAGENT
01012 #define DEFAULT_USERAGENT "Asterisk PBX"  /*!< Default Useragent: header unless re-defined in sip.conf */
01013 #define DEFAULT_SDPSESSION "Asterisk PBX" /*!< Default SDP session name, (s=) header unless re-defined in sip.conf */
01014 #define DEFAULT_SDPOWNER "root"        /*!< Default SDP username field in (o=) header unless re-defined in sip.conf */
01015 #endif
01016 /*@}*/ 
01017 
01018 /*! \name DefaultSettings
01019    Default setttings are used as a channel setting and as a default when
01020    configuring devices 
01021 */
01022 /*@{*/ 
01023 static char default_language[MAX_LANGUAGE];
01024 static char default_callerid[AST_MAX_EXTENSION];
01025 static char default_fromdomain[AST_MAX_EXTENSION];
01026 static char default_notifymime[AST_MAX_EXTENSION];
01027 static int default_qualify;      /*!< Default Qualify= setting */
01028 static char default_vmexten[AST_MAX_EXTENSION];
01029 static char default_mohinterpret[MAX_MUSICCLASS];  /*!< Global setting for moh class to use when put on hold */
01030 static char default_mohsuggest[MAX_MUSICCLASS];    /*!< Global setting for moh class to suggest when putting 
01031                                                     *   a bridged channel on hold */
01032 static char default_parkinglot[AST_MAX_CONTEXT]; /*!< Parkinglot */
01033 static int default_maxcallbitrate;  /*!< Maximum bitrate for call */
01034 static struct ast_codec_pref default_prefs;     /*!< Default codec prefs */
01035 static unsigned int default_transports;         /*!< Default Transports (enum sip_transport) that are acceptable */
01036 static unsigned int default_primary_transport;     /*!< Default primary Transport (enum sip_transport) for outbound connections to devices */
01037 
01038 /*@}*/ 
01039 
01040 /*! \name GlobalSettings
01041    Global settings apply to the channel (often settings you can change in the general section
01042    of sip.conf
01043 */
01044 /*@{*/ 
01045 /*! \brief a place to store all global settings for the sip channel driver 
01046    These are settings that will be possibly to apply on a group level later on.
01047    \note Do not add settings that only apply to the channel itself and can't
01048          be applied to devices (trunks, services, phones)
01049 */
01050 struct sip_settings {
01051    int peer_rtupdate;      /*!< G: Update database with registration data for peer? */
01052    int rtsave_sysname;     /*!< G: Save system name at registration? */
01053    int ignore_regexpire;      /*!< G: Ignore expiration of peer  */
01054    int rtautoclear;     /*!< Realtime ?? */
01055    int directrtpsetup;     /*!< Enable support for Direct RTP setup (no re-invites) */
01056    int pedanticsipchecking;   /*!< Extra checking ?  Default off */
01057    int autocreatepeer;     /*!< Auto creation of peers at registration? Default off. */
01058    int srvlookup;       /*!< SRV Lookup on or off. Default is on */
01059    int allowguest;         /*!< allow unauthenticated peers to connect? */
01060    int alwaysauthreject;      /*!< Send 401 Unauthorized for all failing requests */
01061    int compactheaders;     /*!< send compact sip headers */
01062    int allow_external_domains;   /*!< Accept calls to external SIP domains? */
01063    int callevents;         /*!< Whether we send manager events or not */
01064    int regextenonqualify;     /*!< Whether to add/remove regexten when qualifying peers */
01065    int matchexterniplocally;  /*!< Match externip/externhost setting against localnet setting */
01066    int notifyringing;      /*!< Send notifications on ringing */
01067    int notifyhold;         /*!< Send notifications on hold */
01068    enum notifycid_setting notifycid; /*!< Send CID with ringing notifications */
01069    enum transfermodes allowtransfer;   /*!< SIP Refer restriction scheme */
01070    int allowsubscribe;          /*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE 
01071                    the global setting is in globals_flags[1] */
01072    char realm[MAXHOSTNAMELEN];      /*!< Default realm */
01073    struct sip_proxy outboundproxy;  /*!< Outbound proxy */
01074    char default_context[AST_MAX_CONTEXT];
01075    char default_subscribecontext[AST_MAX_CONTEXT];
01076 };
01077 
01078 static struct sip_settings sip_cfg;
01079 
01080 static int global_match_auth_username;    /*!< Match auth username if available instead of From: Default off. */
01081 
01082 static int global_relaxdtmf;     /*!< Relax DTMF */
01083 static int global_prematuremediafilter;   /*!< Enable/disable premature frames in a call (causing 183 early media) */
01084 static int global_relaxdtmf;        /*!< Relax DTMF */
01085 static int global_rtptimeout;    /*!< Time out call if no RTP */
01086 static int global_rtpholdtimeout;   /*!< Time out call if no RTP during hold */
01087 static int global_rtpkeepalive;     /*!< Send RTP keepalives */
01088 static int global_reg_timeout;
01089 static int global_regattempts_max;  /*!< Registration attempts before giving up */
01090 static int global_shrinkcallerid;   /*!< enable or disable shrinking of caller id  */
01091 static int global_callcounter;      /*!< Enable call counters for all devices. This is currently enabled by setting the peer
01092                   call-limit to INT_MAX. When we remove the call-limit from the code, we can make it
01093                   with just a boolean flag in the device structure */
01094 static unsigned int global_tos_sip;    /*!< IP type of service for SIP packets */
01095 static unsigned int global_tos_audio;     /*!< IP type of service for audio RTP packets */
01096 static unsigned int global_tos_video;     /*!< IP type of service for video RTP packets */
01097 static unsigned int global_tos_text;      /*!< IP type of service for text RTP packets */
01098 static unsigned int global_cos_sip;    /*!< 802.1p class of service for SIP packets */
01099 static unsigned int global_cos_audio;     /*!< 802.1p class of service for audio RTP packets */
01100 static unsigned int global_cos_video;     /*!< 802.1p class of service for video RTP packets */
01101 static unsigned int global_cos_text;      /*!< 802.1p class of service for text RTP packets */
01102 static int recordhistory;     /*!< Record SIP history. Off by default */
01103 static int dumphistory;       /*!< Dump history to verbose before destroying SIP dialog */
01104 static char global_regcontext[AST_MAX_CONTEXT];    /*!< Context for auto-extensions */
01105 static char global_useragent[AST_MAX_EXTENSION];   /*!< Useragent for the SIP channel */
01106 static char global_sdpsession[AST_MAX_EXTENSION];  /*!< SDP session name for the SIP channel */
01107 static char global_sdpowner[AST_MAX_EXTENSION]; /*!< SDP owner name for the SIP channel */
01108 static int global_authfailureevents;      /*!< Whether we send authentication failure manager events or not. Default no. */
01109 static int global_t1;         /*!< T1 time */
01110 static int global_t1min;      /*!< T1 roundtrip time minimum */
01111 static int global_timer_b;             /*!< Timer B - RFC 3261 Section 17.1.1.2 */
01112 static int global_autoframing;            /*!< Turn autoframing on or off. */
01113 static int global_qualifyfreq;         /*!< Qualify frequency */
01114 static int global_qualify_gap;              /*!< Time between our group of peer pokes */
01115 static int global_qualify_peers;          /*!< Number of peers to poke at a given time */
01116 
01117 
01118 /*! \brief Codecs that we support by default: */
01119 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
01120 
01121 static enum st_mode global_st_mode;           /*!< Mode of operation for Session-Timers           */
01122 static enum st_refresher global_st_refresher; /*!< Session-Timer refresher                        */
01123 static int global_min_se;                     /*!< Lowest threshold for session refresh interval  */
01124 static int global_max_se;                     /*!< Highest threshold for session refresh interval */
01125 
01126 static int global_dynamic_exclude_static = 0;   /*!< Exclude static peers from contact registrations */
01127 /*@}*/
01128 
01129 /*! \brief Global list of addresses dynamic peers are not allowed to use */
01130 static struct ast_ha *global_contact_ha = NULL;
01131 
01132 /*! \name Object counters @{
01133  * \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
01134  * should be used to modify these values. */
01135 static int speerobjs = 0;                /*!< Static peers */
01136 static int rpeerobjs = 0;                /*!< Realtime peers */
01137 static int apeerobjs = 0;                /*!< Autocreated peer objects */
01138 static int regobjs = 0;                  /*!< Registry objects */
01139 /* }@ */
01140 
01141 static struct ast_flags global_flags[2] = {{0}};        /*!< global SIP_ flags */
01142 static int global_t38_maxdatagram;        /*!< global T.38 FaxMaxDatagram override */
01143 
01144 static char used_context[AST_MAX_CONTEXT];      /*!< name of automatically created context for unloading */
01145 
01146 
01147 AST_MUTEX_DEFINE_STATIC(netlock);
01148 
01149 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
01150    when it's doing something critical. */
01151 AST_MUTEX_DEFINE_STATIC(monlock);
01152 
01153 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
01154 
01155 /*! \brief This is the thread for the monitor which checks for input on the channels
01156    which are not currently in use.  */
01157 static pthread_t monitor_thread = AST_PTHREADT_NULL;
01158 
01159 static int sip_reloading = FALSE;                       /*!< Flag for avoiding multiple reloads at the same time */
01160 static enum channelreloadreason sip_reloadreason;       /*!< Reason for last reload/load of configuration */
01161 
01162 static struct sched_context *sched;     /*!< The scheduling context */
01163 static struct io_context *io;           /*!< The IO context */
01164 static int *sipsock_read_id;            /*!< ID of IO entry for sipsock FD */
01165 
01166 #define DEC_CALL_LIMIT  0
01167 #define INC_CALL_LIMIT  1
01168 #define DEC_CALL_RINGING 2
01169 #define INC_CALL_RINGING 3
01170 
01171 /*! \brief The SIP socket definition */
01172 struct sip_socket {
01173    enum sip_transport type;   /*!< UDP, TCP or TLS */
01174    int fd;           /*!< Filed descriptor, the actual socket */
01175    uint16_t port;
01176    struct ast_tcptls_session_instance *tcptls_session;   /* If tcp or tls, a socket manager */
01177 };
01178 
01179 /*! \brief sip_request: The data grabbed from the UDP socket
01180  *
01181  * \verbatim
01182  * Incoming messages: we first store the data from the socket in data[],
01183  * adding a trailing \0 to make string parsing routines happy.
01184  * Then call parse_request() and req.method = find_sip_method();
01185  * to initialize the other fields. The \r\n at the end of each line is   
01186  * replaced by \0, so that data[] is not a conforming SIP message anymore.
01187  * After this processing, rlPart1 is set to non-NULL to remember
01188  * that we can run get_header() on this kind of packet.
01189  *
01190  * parse_request() splits the first line as follows:
01191  * Requests have in the first line      method uri SIP/2.0
01192  *      rlPart1 = method; rlPart2 = uri;
01193  * Responses have in the first line     SIP/2.0 NNN description
01194  *      rlPart1 = SIP/2.0; rlPart2 = NNN + description;
01195  *
01196  * For outgoing packets, we initialize the fields with init_req() or init_resp()
01197  * (which fills the first line to "METHOD uri SIP/2.0" or "SIP/2.0 code text"),
01198  * and then fill the rest with add_header() and add_content().
01199  * The \r\n at the end of the line are still there, so the get_header()
01200  * and similar functions don't work on these packets. 
01201  * \endverbatim
01202  */
01203 struct sip_request {
01204    ptrdiff_t rlPart1;           /*!< Offset of the SIP Method Name or "SIP/2.0" protocol version */
01205    ptrdiff_t rlPart2;           /*!< Offset of the Request URI or Response Status */
01206    int len;                /*!< bytes used in data[], excluding trailing null terminator. Rarely used. */
01207    int headers;            /*!< # of SIP Headers */
01208    int method;             /*!< Method of this request */
01209    int lines;              /*!< Body Content */
01210    unsigned int sdp_start; /*!< the line number where the SDP begins */
01211    unsigned int sdp_count; /*!< the number of lines of SDP */
01212    char debug;    /*!< print extra debugging if non zero */
01213    char has_to_tag;  /*!< non-zero if packet has To: tag */
01214    char ignore;      /*!< if non-zero This is a re-transmit, ignore it */
01215    /* Array of offsets into the request string of each SIP header*/
01216    ptrdiff_t header[SIP_MAX_HEADERS];
01217    /* Array of offsets into the request string of each SDP line*/
01218    ptrdiff_t line[SIP_MAX_LINES];
01219    struct ast_str *data;   
01220    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 Modes for SIP domain handling in the PBX */
01264 enum domain_mode {
01265    SIP_DOMAIN_AUTO,     /*!< This domain is auto-configured */
01266    SIP_DOMAIN_CONFIG,      /*!< This domain is from configuration */
01267 };
01268 
01269 /*! \brief Domain data structure. 
01270    \note In the future, we will connect this to a configuration tree specific
01271    for this domain
01272 */
01273 struct domain {
01274    char domain[MAXHOSTNAMELEN];     /*!< SIP domain we are responsible for */
01275    char context[AST_MAX_EXTENSION]; /*!< Incoming context for this domain */
01276    enum domain_mode mode;        /*!< How did we find this domain? */
01277    AST_LIST_ENTRY(domain) list;     /*!< List mechanics */
01278 };
01279 
01280 static AST_LIST_HEAD_STATIC(domain_list, domain);  /*!< The SIP domain list */
01281 
01282 
01283 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
01284 struct sip_history {
01285    AST_LIST_ENTRY(sip_history) list;
01286    char event[0]; /* actually more, depending on needs */
01287 };
01288 
01289 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
01290 
01291 /*! \brief sip_auth: Credentials for authentication to other SIP services */
01292 struct sip_auth {
01293    char realm[AST_MAX_EXTENSION];  /*!< Realm in which these credentials are valid */
01294    char username[256];             /*!< Username */
01295    char secret[256];               /*!< Secret */
01296    char md5secret[256];            /*!< MD5Secret */
01297    struct sip_auth *next;          /*!< Next auth structure in list */
01298 };
01299 
01300 /*! \name SIPflags
01301    Various flags for the flags field in the pvt structure 
01302    Trying to sort these up (one or more of the following):
01303    D: Dialog
01304    P: Peer/user
01305    G: Global flag
01306    When flags are used by multiple structures, it is important that
01307    they have a common layout so it is easy to copy them.
01308 */
01309 /*@{*/ 
01310 #define SIP_OUTGOING    (1 << 0) /*!< D: Direction of the last transaction in this dialog */
01311 #define SIP_RINGING     (1 << 2) /*!< D: Have sent 180 ringing */
01312 #define SIP_PROGRESS_SENT  (1 << 3) /*!< D: Have sent 183 message progress */
01313 #define SIP_NEEDREINVITE   (1 << 4) /*!< D: Do we need to send another reinvite? */
01314 #define SIP_PENDINGBYE     (1 << 5) /*!< D: Need to send bye after we ack? */
01315 #define SIP_GOTREFER    (1 << 6) /*!< D: Got a refer? */
01316 #define SIP_CALL_LIMIT     (1 << 7) /*!< D: Call limit enforced for this call */
01317 #define SIP_INC_COUNT      (1 << 8) /*!< D: Did this dialog increment the counter of in-use calls? */
01318 #define SIP_INC_RINGING    (1 << 9) /*!< D: Did this connection increment the counter of in-use calls? */
01319 #define SIP_DEFER_BYE_ON_TRANSFER   (1 << 10)   /*!< D: Do not hangup at first ast_hangup */
01320 
01321 #define SIP_PROMISCREDIR   (1 << 11)   /*!< DP: Promiscuous redirection */
01322 #define SIP_TRUSTRPID      (1 << 12)   /*!< DP: Trust RPID headers? */
01323 #define SIP_USEREQPHONE    (1 << 13)   /*!< DP: Add user=phone to numeric URI. Default off */
01324 #define SIP_USECLIENTCODE  (1 << 14)   /*!< DP: Trust X-ClientCode info message */
01325 
01326 /* DTMF flags - see str2dtmfmode() and dtmfmode2str() */
01327 #define SIP_DTMF     (7 << 15)   /*!< DP: DTMF Support: five settings, uses three bits */
01328 #define SIP_DTMF_RFC2833   (0 << 15)   /*!< DP: DTMF Support: RTP DTMF - "rfc2833" */
01329 #define SIP_DTMF_INBAND    (1 << 15)   /*!< DP: DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
01330 #define SIP_DTMF_INFO      (2 << 15)   /*!< DP: DTMF Support: SIP Info messages - "info" */
01331 #define SIP_DTMF_AUTO      (3 << 15)   /*!< DP: DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
01332 #define SIP_DTMF_SHORTINFO      (4 << 15)       /*!< DP: DTMF Support: SIP Info messages - "info" - short variant */
01333 
01334 /* NAT settings - see nat2str() */
01335 #define SIP_NAT         (3 << 18)   /*!< DP: four settings, uses two bits */
01336 #define SIP_NAT_NEVER      (0 << 18)   /*!< DP: No nat support */
01337 #define SIP_NAT_RFC3581    (1 << 18)   /*!< DP: NAT RFC3581 */
01338 #define SIP_NAT_ROUTE      (2 << 18)   /*!< DP: NAT Only ROUTE */
01339 #define SIP_NAT_ALWAYS     (3 << 18)   /*!< DP: NAT Both ROUTE and RFC3581 */
01340 
01341 /* re-INVITE related settings */
01342 #define SIP_REINVITE    (7 << 20)   /*!< DP: four settings, uses three bits */
01343 #define SIP_REINVITE_NONE  (0 << 20)   /*!< DP: no reinvite allowed */
01344 #define SIP_DIRECT_MEDIA   (1 << 20)   /*!< DP: allow peers to be reinvited to send media directly p2p */
01345 #define SIP_DIRECT_MEDIA_NAT  (2 << 20)   /*!< DP: allow media reinvite when new peer is behind NAT */
01346 #define SIP_REINVITE_UPDATE   (4 << 20)   /*!< DP: use UPDATE (RFC3311) when reinviting this peer */
01347 
01348 /* "insecure" settings - see insecure2str() */
01349 #define SIP_INSECURE    (3 << 23)   /*!< DP: three settings, uses two bits */
01350 #define SIP_INSECURE_NONE  (0 << 23)   /*!< DP: secure mode */
01351 #define SIP_INSECURE_PORT  (1 << 23)   /*!< DP: don't require matching port for incoming requests */
01352 #define SIP_INSECURE_INVITE   (1 << 24)   /*!< DP: don't require authentication for incoming INVITEs */
01353 
01354 /* Sending PROGRESS in-band settings */
01355 #define SIP_PROG_INBAND    (3 << 25)   /*!< DP: three settings, uses two bits */
01356 #define SIP_PROG_INBAND_NEVER (0 << 25)
01357 #define SIP_PROG_INBAND_NO (1 << 25)
01358 #define SIP_PROG_INBAND_YES   (2 << 25)
01359 
01360 #define SIP_SENDRPID    (1 << 29)   /*!< DP: Remote Party-ID Support */
01361 #define SIP_G726_NONSTANDARD  (1 << 31)   /*!< DP: Use non-standard packing for G726-32 data */
01362 
01363 /*! \brief Flags to copy from peer/user to dialog */
01364 #define SIP_FLAGS_TO_COPY \
01365    (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
01366     SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
01367     SIP_USEREQPHONE | SIP_INSECURE)
01368 /*@}*/ 
01369 
01370 /*! \name SIPflags2
01371    a second page of flags (for flags[1] */
01372 /*@{*/ 
01373 /* realtime flags */
01374 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0) /*!< GP: Should we keep RT objects in memory for extended time? */
01375 #define SIP_PAGE2_RTAUTOCLEAR    (1 << 2) /*!< GP: Should we clean memory from peers after expiry? */
01376 #define SIP_PAGE2_HAVEPEERCONTEXT   (1 << 3) /*< Are we associated with a configured peer context? */
01377 /* Space for addition of other realtime flags in the future */
01378 #define SIP_PAGE2_FORWARD_LOOP_DETECTED (1 << 8)/*!< 31: Do call forward when receiving 482 Loop Detected */
01379 #define SIP_PAGE2_STATECHANGEQUEUE  (1 << 9) /*!< D: Unsent state pending change exists */
01380 
01381 #define SIP_PAGE2_RPORT_PRESENT         (1 << 10)       /*!< Was rport received in the Via header? */
01382 #define SIP_PAGE2_VIDEOSUPPORT      (1 << 14)   /*!< DP: Video supported if offered? */
01383 #define SIP_PAGE2_TEXTSUPPORT    (1 << 15)   /*!< GDP: Global text enable */
01384 #define SIP_PAGE2_ALLOWSUBSCRIBE (1 << 16)   /*!< GP: Allow subscriptions from this peer? */
01385 #define SIP_PAGE2_ALLOWOVERLAP      (1 << 17)   /*!< DP: Allow overlap dialing ? */
01386 #define SIP_PAGE2_SUBSCRIBEMWIONLY  (1 << 18)   /*!< GP: Only issue MWI notification if subscribed to */
01387 #define SIP_PAGE2_IGNORESDPVERSION  (1 << 19)   /*!< GDP: Ignore the SDP session version number we receive and treat all sessions as new */
01388 
01389 #define SIP_PAGE2_T38SUPPORT             (3 << 20) /*!< GDP: T.38 Fax Support */
01390 #define SIP_PAGE2_T38SUPPORT_UDPTL          (1 << 20) /*!< GDP: T.38 Fax Support (no error correction) */
01391 #define SIP_PAGE2_T38SUPPORT_UDPTL_FEC         (2 << 20) /*!< GDP: T.38 Fax Support (FEC error correction) */
01392 #define SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY   (3 << 20)   /*!< GDP: T.38 Fax Support (redundancy error correction) */
01393 
01394 #define SIP_PAGE2_CALL_ONHOLD    (3 << 23)   /*!< D: Call hold states: */
01395 #define SIP_PAGE2_CALL_ONHOLD_ACTIVE    (1 << 23)       /*!< D: Active hold */
01396 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR   (2 << 23)   /*!< D: One directional hold */
01397 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE (3 << 23)   /*!< D: Inactive hold */
01398 
01399 #define SIP_PAGE2_RFC2833_COMPENSATE    (1 << 25)  /*!< DP: Compensate for buggy RFC2833 implementations */
01400 #define SIP_PAGE2_BUGGY_MWI      (1 << 26)   /*!< DP: Buggy CISCO MWI fix */
01401 #define SIP_PAGE2_DIALOG_ESTABLISHED    (1 << 27)       /*!< 29: Has a dialog been established? */
01402 #define SIP_PAGE2_FAX_DETECT     (3 << 28)   /*!< DP: Fax Detection support */
01403 #define SIP_PAGE2_FAX_DETECT_CNG (1 << 28)   /*!< DP: Fax Detection support - detect CNG in audio */
01404 #define SIP_PAGE2_FAX_DETECT_T38 (2 << 28)   /*!< DP: Fax Detection support - detect T.38 reinvite from peer */
01405 #define SIP_PAGE2_FAX_DETECT_BOTH   (3 << 28)   /*!< DP: Fax Detection support - detect both */
01406 #define SIP_PAGE2_REGISTERTRYING        (1 << 29)       /*!< DP: Send 100 Trying on REGISTER attempts */
01407 #define SIP_PAGE2_UDPTL_DESTINATION     (1 << 30)       /*!< DP: Use source IP of RTP as destination if NAT is enabled */
01408 #define SIP_PAGE2_VIDEOSUPPORT_ALWAYS  (1 << 31)       /*!< DP: Always set up video, even if endpoints don't support it */
01409 
01410 #define SIP_PAGE2_FLAGS_TO_COPY \
01411    (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_IGNORESDPVERSION | \
01412    SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | \
01413    SIP_PAGE2_BUGGY_MWI | SIP_PAGE2_TEXTSUPPORT | SIP_PAGE2_FAX_DETECT | \
01414    SIP_PAGE2_UDPTL_DESTINATION | SIP_PAGE2_VIDEOSUPPORT_ALWAYS | \
01415    SIP_PAGE2_HAVEPEERCONTEXT | SIP_PAGE2_FORWARD_LOOP_DETECTED)
01416 
01417 /*@}*/ 
01418 
01419 /*! \brief debugging state
01420  * We store separately the debugging requests from the config file
01421  * and requests from the CLI. Debugging is enabled if either is set
01422  * (which means that if sipdebug is set in the config file, we can
01423  * only turn it off by reloading the config).
01424  */
01425 enum sip_debug_e {
01426    sip_debug_none = 0,
01427    sip_debug_config = 1,
01428    sip_debug_console = 2,
01429 };
01430 
01431 static enum sip_debug_e sipdebug;
01432 
01433 /*! \brief extra debugging for 'text' related events.
01434  * At the moment this is set together with sip_debug_console.
01435  * \note It should either go away or be implemented properly.
01436  */
01437 static int sipdebug_text;
01438 
01439 /*! \brief T38 States for a call */
01440 enum t38state {
01441    T38_DISABLED = 0,                /*!< Not enabled */
01442    T38_LOCAL_REINVITE,              /*!< Offered from local - REINVITE */
01443    T38_PEER_REINVITE,               /*!< Offered from peer - REINVITE */
01444    T38_ENABLED                      /*!< Negotiated (enabled) */
01445 };
01446 
01447 /*! \brief T.38 channel settings (at some point we need to make this alloc'ed */
01448 struct t38properties {
01449    enum t38state state;    /*!< T.38 state */
01450    struct ast_control_t38_parameters our_parms;
01451    struct ast_control_t38_parameters their_parms;
01452 };
01453 
01454 /*! \brief Parameters to know status of transfer */
01455 enum referstatus {
01456    REFER_IDLE,                    /*!< No REFER is in progress */
01457    REFER_SENT,                    /*!< Sent REFER to transferee */
01458    REFER_RECEIVED,                /*!< Received REFER from transferrer */
01459    REFER_CONFIRMED,               /*!< Refer confirmed with a 100 TRYING (unused) */
01460    REFER_ACCEPTED,                /*!< Accepted by transferee */
01461    REFER_RINGING,                 /*!< Target Ringing */
01462    REFER_200OK,                   /*!< Answered by transfer target */
01463    REFER_FAILED,                  /*!< REFER declined - go on */
01464    REFER_NOAUTH                   /*!< We had no auth for REFER */
01465 };
01466 
01467 /*! \brief generic struct to map between strings and integers.
01468  * Fill it with x-s pairs, terminate with an entry with s = NULL;
01469  * Then you can call map_x_s(...) to map an integer to a string,
01470  * and map_s_x() for the string -> integer mapping.
01471  */
01472 struct _map_x_s {
01473    int x;
01474    const char *s;
01475 };              
01476 
01477 static const struct _map_x_s referstatusstrings[] = {
01478    { REFER_IDLE,     "<none>" },
01479    { REFER_SENT,     "Request sent" },
01480    { REFER_RECEIVED, "Request received" },
01481    { REFER_CONFIRMED,   "Confirmed" },
01482    { REFER_ACCEPTED, "Accepted" },
01483    { REFER_RINGING,  "Target ringing" },
01484    { REFER_200OK,    "Done" },
01485    { REFER_FAILED,      "Failed" },
01486    { REFER_NOAUTH,      "Failed - auth failure" },
01487    { -1,       NULL} /* terminator */
01488 };
01489 
01490 /*! \brief Structure to handle SIP transfers. Dynamically allocated when needed
01491    \note OEJ: Should be moved to string fields */
01492 struct sip_refer {
01493    char refer_to[AST_MAX_EXTENSION];      /*!< Place to store REFER-TO extension */
01494    char refer_to_domain[AST_MAX_EXTENSION];  /*!< Place to store REFER-TO domain */
01495    char refer_to_urioption[AST_MAX_EXTENSION];  /*!< Place to store REFER-TO uri options */
01496    char refer_to_context[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO context */
01497    char referred_by[AST_MAX_EXTENSION];      /*!< Place to store REFERRED-BY extension */
01498    char referred_by_name[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
01499    char refer_contact[AST_MAX_EXTENSION];    /*!< Place to store Contact info from a REFER extension */
01500    char replaces_callid[SIPBUFSIZE];         /*!< Replace info: callid */
01501    char replaces_callid_totag[SIPBUFSIZE/2];    /*!< Replace info: to-tag */
01502    char replaces_callid_fromtag[SIPBUFSIZE/2];     /*!< Replace info: from-tag */
01503    struct sip_pvt *refer_call;         /*!< Call we are referring. This is just a reference to a
01504                       * dialog owned by someone else, so we should not destroy
01505                       * it when the sip_refer object goes.
01506                       */
01507    int attendedtransfer;            /*!< Attended or blind transfer? */
01508    int localtransfer;            /*!< Transfer to local domain? */
01509    enum referstatus status;         /*!< REFER status */
01510 };
01511 
01512 
01513 /*! \brief Structure that encapsulates all attributes related to running 
01514  *   SIP Session-Timers feature on a per dialog basis.
01515  */
01516 struct sip_st_dlg {
01517    int st_active;                          /*!< Session-Timers on/off */ 
01518    int st_interval;                        /*!< Session-Timers negotiated session refresh interval */
01519    int st_schedid;                         /*!< Session-Timers ast_sched scheduler id */
01520    enum st_refresher st_ref;               /*!< Session-Timers session refresher */
01521    int st_expirys;                         /*!< Session-Timers number of expirys */
01522    int st_active_peer_ua;                  /*!< Session-Timers on/off in peer UA */
01523    int st_cached_min_se;                   /*!< Session-Timers cached Min-SE */
01524    int st_cached_max_se;                   /*!< Session-Timers cached Session-Expires */
01525    enum st_mode st_cached_mode;            /*!< Session-Timers cached M.O. */
01526    enum st_refresher st_cached_ref;        /*!< Session-Timers cached refresher */
01527    unsigned char quit_flag:1;              /*!< Stop trying to lock; just quit */
01528 };
01529 
01530 
01531 /*! \brief Structure that encapsulates all attributes related to configuration 
01532  *   of SIP Session-Timers feature on a per user/peer basis.
01533  */
01534 struct sip_st_cfg {
01535    enum st_mode st_mode_oper;      /*!< Mode of operation for Session-Timers           */
01536    enum st_refresher st_ref;       /*!< Session-Timer refresher                        */
01537    int st_min_se;                  /*!< Lowest threshold for session refresh interval  */
01538    int st_max_se;                  /*!< Highest threshold for session refresh interval */
01539 };
01540 
01541 struct offered_media {
01542    int offered;
01543    char text[128];
01544 };
01545 
01546 /*! \brief Structure used for each SIP dialog, ie. a call, a registration, a subscribe.
01547  * Created and initialized by sip_alloc(), the descriptor goes into the list of
01548  * descriptors (dialoglist).
01549  */
01550 struct sip_pvt {
01551    struct sip_pvt *next;         /*!< Next dialog in chain */
01552    enum invitestates invitestate;      /*!< Track state of SIP_INVITEs */
01553    int method;          /*!< SIP method that opened this dialog */
01554    AST_DECLARE_STRING_FIELDS(
01555       AST_STRING_FIELD(callid);  /*!< Global CallID */
01556       AST_STRING_FIELD(randdata);   /*!< Random data */
01557       AST_STRING_FIELD(accountcode);   /*!< Account code */
01558       AST_STRING_FIELD(realm);   /*!< Authorization realm */
01559       AST_STRING_FIELD(nonce);   /*!< Authorization nonce */
01560       AST_STRING_FIELD(opaque);  /*!< Opaque nonsense */
01561       AST_STRING_FIELD(qop);     /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
01562       AST_STRING_FIELD(domain);  /*!< Authorization domain */
01563       AST_STRING_FIELD(from);    /*!< The From: header */
01564       AST_STRING_FIELD(useragent);  /*!< User agent in SIP request */
01565       AST_STRING_FIELD(exten);   /*!< Extension where to start */
01566       AST_STRING_FIELD(context); /*!< Context for this call */
01567       AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
01568       AST_STRING_FIELD(subscribeuri); /*!< Subscribecontext */
01569       AST_STRING_FIELD(fromdomain); /*!< Domain to show in the from field */
01570       AST_STRING_FIELD(fromuser);   /*!< User to show in the user field */
01571       AST_STRING_FIELD(fromname);   /*!< Name to show in the user field */
01572       AST_STRING_FIELD(tohost);  /*!< Host we should put in the "to" field */
01573       AST_STRING_FIELD(todnid);  /*!< DNID of this call (overrides host) */
01574       AST_STRING_FIELD(language);   /*!< Default language for this call */
01575       AST_STRING_FIELD(mohinterpret);  /*!< MOH class to use when put on hold */
01576       AST_STRING_FIELD(mohsuggest); /*!< MOH class to suggest when putting a peer on hold */
01577       AST_STRING_FIELD(rdnis);   /*!< Referring DNIS */
01578       AST_STRING_FIELD(redircause); /*!< Referring cause */
01579       AST_STRING_FIELD(theirtag);   /*!< Their tag */
01580       AST_STRING_FIELD(username);   /*!< [user] name */
01581       AST_STRING_FIELD(peername);   /*!< [peer] name, not set if [user] */
01582       AST_STRING_FIELD(authname);   /*!< Who we use for authentication */
01583       AST_STRING_FIELD(uri);     /*!< Original requested URI */
01584       AST_STRING_FIELD(okcontacturi);  /*!< URI from the 200 OK on INVITE */
01585       AST_STRING_FIELD(peersecret); /*!< Password */
01586       AST_STRING_FIELD(peermd5secret);
01587       AST_STRING_FIELD(cid_num); /*!< Caller*ID number */
01588       AST_STRING_FIELD(cid_name);   /*!< Caller*ID name */
01589       AST_STRING_FIELD(fullcontact);   /*!< The Contact: that the UA registers with us */
01590          /* we only store the part in <brackets> in this field. */
01591       AST_STRING_FIELD(our_contact);   /*!< Our contact header */
01592       AST_STRING_FIELD(rpid);    /*!< Our RPID header */
01593       AST_STRING_FIELD(rpid_from);  /*!< Our RPID From header */
01594       AST_STRING_FIELD(url);     /*!< URL to be sent with next message to peer */
01595       AST_STRING_FIELD(parkinglot);    /*!< Parkinglot */
01596    );
01597    char via[128];                          /*!< Via: header */
01598    struct sip_socket socket;     /*!< The socket used for this dialog */
01599    unsigned int ocseq;        /*!< Current outgoing seqno */
01600    unsigned int icseq;        /*!< Current incoming seqno */
01601    ast_group_t callgroup;        /*!< Call group */
01602    ast_group_t pickupgroup;      /*!< Pickup group */
01603    int lastinvite;            /*!< Last Cseq of invite */
01604    struct ast_flags flags[2];    /*!< SIP_ flags */
01605 
01606    /* boolean or small integers that don't belong in flags */
01607    char do_history;        /*!< Set if we want to record history */
01608    char alreadygone;       /*!< already destroyed by our peer */
01609    char needdestroy;       /*!< need to be destroyed by the monitor thread */
01610    char outgoing_call;        /*!< this is an outgoing call */
01611    char answered_elsewhere;      /*!< This call is cancelled due to answer on another channel */
01612    char novideo;           /*!< Didn't get video in invite, don't offer */
01613    char notext;            /*!< Text not supported  (?) */
01614 
01615    int timer_t1;           /*!< SIP timer T1, ms rtt */
01616    int timer_b;                            /*!< SIP timer B, ms */
01617    unsigned int sipoptions;      /*!< Supported SIP options on the other end */
01618    unsigned int reqsipoptions;      /*!< Required SIP options on the other end */
01619    struct ast_codec_pref prefs;     /*!< codec prefs */
01620    int capability;            /*!< Special capability (codec) */
01621    int jointcapability;       /*!< Supported capability at both ends (codecs) */
01622    int peercapability;        /*!< Supported peer capability */
01623    int prefcodec;          /*!< Preferred codec (outbound only) */
01624    int noncodeccapability;       /*!< DTMF RFC2833 telephony-event */
01625    int jointnoncodeccapability;            /*!< Joint Non codec capability */
01626    int redircodecs;        /*!< Redirect codecs */
01627    int maxcallbitrate;        /*!< Maximum Call Bitrate for Video Calls */ 
01628    int t38_maxdatagram;       /*!< T.38 FaxMaxDatagram override */
01629    struct sip_proxy *outboundproxy; /*!< Outbound proxy for this dialog. Use ref_proxy to set this instead of setting it directly*/
01630    struct t38properties t38;     /*!< T38 settings */
01631    struct sockaddr_in udptlredirip; /*!< Where our T.38 UDPTL should be going if not to us */
01632    struct ast_udptl *udptl;      /*!< T.38 UDPTL session */
01633    int callingpres;        /*!< Calling presentation */
01634    int authtries;          /*!< Times we've tried to authenticate */
01635    int expiry;          /*!< How long we take to expire */
01636    long branch;            /*!< The branch identifier of this session */
01637    long invite_branch;        /*!< The branch used when we sent the initial INVITE */
01638    char tag[11];           /*!< Our tag for this session */
01639    int sessionid;          /*!< SDP Session ID */
01640    int sessionversion;        /*!< SDP Session Version */
01641    int64_t sessionversion_remote;      /*!< Remote UA's SDP Session Version */
01642    int session_modify;        /*!< Session modification request true/false  */
01643    unsigned int portinuri:1;     /*!< Non zero if a port has been specified, will also disable srv lookups */
01644    struct sockaddr_in sa;        /*!< Our peer */
01645    struct sockaddr_in redirip;      /*!< Where our RTP should be going if not to us */
01646    struct sockaddr_in vredirip;     /*!< Where our Video RTP should be going if not to us */
01647    struct sockaddr_in tredirip;     /*!< Where our Text RTP should be going if not to us */
01648    time_t lastrtprx;       /*!< Last RTP received */
01649    time_t lastrtptx;       /*!< Last RTP sent */
01650    int rtptimeout;            /*!< RTP timeout time */
01651    struct sockaddr_in recv;      /*!< Received as */
01652    struct sockaddr_in ourip;     /*!< Our IP (as seen from the outside) */
01653    struct ast_channel *owner;    /*!< Who owns us (if we have an owner) */
01654    struct sip_route *route;      /*!< Head of linked list of routing steps (fm Record-Route) */
01655    int route_persistant;         /*!< Is this the "real" route? */
01656    struct ast_variable *notify_headers;    /*!< Custom notify type */
01657    struct sip_auth *peerauth;    /*!< Realm authentication */
01658    int noncecount;            /*!< Nonce-count */
01659    unsigned int stalenonce:1; /*!< Marks the current nonce as responded too */
01660    char lastmsg[256];         /*!< Last Message sent/received */
01661    int amaflags;           /*!< AMA Flags */
01662    int pendinginvite;         /*!< Any pending INVITE or state NOTIFY (in subscribe pvt's) ? (seqno of this) */
01663    int glareinvite;        /*!< A invite received while a pending invite is already present is stored here.  Its seqno is the
01664                   value. Since this glare invite's seqno is not the same as the pending invite's, it must be 
01665                   held in order to properly process acknowledgements for our 491 response. */
01666    struct sip_request initreq;      /*!< Latest request that opened a new transaction
01667                      within this dialog.
01668                      NOT the request that opened the dialog */
01669 
01670    int initid;          /*!< Auto-congest ID if appropriate (scheduler) */
01671    int waitid;          /*!< Wait ID for scheduler after 491 or other delays */
01672    int autokillid;            /*!< Auto-kill ID (scheduler) */
01673    int t38id;                              /*!< T.38 Response ID */
01674    enum transfermodes allowtransfer;   /*!< REFER: restriction scheme */
01675    struct sip_refer *refer;      /*!< REFER: SIP transfer data structure */
01676    enum subscriptiontype subscribed;   /*!< SUBSCRIBE: Is this dialog a subscription?  */
01677    int stateid;            /*!< SUBSCRIBE: ID for devicestate subscriptions */
01678    int laststate;          /*!< SUBSCRIBE: Last known extension state */
01679    int dialogver;          /*!< SUBSCRIBE: Version for subscription dialog-info */
01680 
01681    struct ast_dsp *dsp;       /*!< A DSP for inband DTMF and fax CNG tone detection */
01682 
01683    struct sip_peer *relatedpeer;    /*!< If this dialog is related to a peer, which one 
01684                      Used in peerpoke, mwi subscriptions */
01685    struct sip_registry *registry;      /*!< If this is a REGISTER dialog, to which registry */
01686    struct ast_rtp *rtp;       /*!< RTP Session */
01687    struct ast_rtp *vrtp;         /*!< Video RTP session */
01688    struct ast_rtp *trtp;         /*!< Text RTP session */
01689    struct sip_pkt *packets;      /*!< Packets scheduled for re-transmission */
01690    struct sip_history_head *history;   /*!< History of this SIP dialog */
01691    size_t history_entries;       /*!< Number of entires in the history */
01692    struct ast_variable *chanvars;      /*!< Channel variables to set for inbound call */
01693    AST_LIST_HEAD_NOLOCK(request_queue, sip_request) request_queue; /*!< Requests that arrived but could not be processed immediately */
01694    int request_queue_sched_id;      /*!< Scheduler ID of any scheduled action to process queued requests */
01695    int provisional_keepalive_sched_id; /*!< Scheduler ID for provisional responses that need to be sent out to avoid cancellation */
01696    const char *last_provisional;   /*!< The last successfully transmitted provisonal response message */
01697    struct sip_invite_param *options;   /*!< Options for INVITE */
01698    int autoframing;        /*!< The number of Asters we group in a Pyroflax
01699                      before strolling to the Grokyzpå
01700                      (A bit unsure of this, please correct if
01701                      you know more) */
01702    struct sip_st_dlg *stimer;    /*!< SIP Session-Timers */              
01703   
01704    int red;             /*!< T.140 RTP Redundancy */
01705    int hangupcause;        /*!< Storage of hangupcause copied from our owner before we disconnect from the AST channel (only used at hangup) */
01706 
01707    struct sip_subscription_mwi *mwi;       /*!< If this is a subscription MWI dialog, to which subscription */
01708    /*! When receiving an SDP offer, it is important to take note of what media types were offered.
01709     * By doing this, even if we don't want to answer a particular media stream with something meaningful, we can
01710     * still put an m= line in our answer with the port set to 0.
01711     *
01712     * The reason for the length being 4 is that in this branch of Asterisk, the only media types supported are 
01713     * image, audio, text, and video. Therefore we need to keep track of which types of media were offered.
01714     *
01715     * Note that if we wanted to be 100% correct, we would keep a list of all media streams offered. That way we could respond
01716     * even to unknown media types, and we could respond to multiple streams of the same type. Such large-scale changes
01717     * are not a good idea for released branches, though, so we're compromising by just making sure that for the common cases:
01718     * audio and video, audio and T.38, and audio and text, we give the appropriate response to both media streams.
01719     *
01720     * The large-scale changes would be a good idea for implementing during an SDP rewrite.
01721     */
01722    struct offered_media offered_media[4];
01723 }; 
01724 
01725 
01726 /*! \brief
01727  * Here we implement the container for dialogs (sip_pvt), defining
01728  * generic wrapper functions to ease the transition from the current
01729  * implementation (a single linked list) to a different container.
01730  * In addition to a reference to the container, we need functions to lock/unlock
01731  * the container and individual items, and functions to add/remove
01732  * references to the individual items.
01733  */
01734 struct ao2_container *dialogs;
01735 
01736 #define sip_pvt_lock(x) ao2_lock(x)
01737 #define sip_pvt_trylock(x) ao2_trylock(x)
01738 #define sip_pvt_unlock(x) ao2_unlock(x)
01739 
01740 /*! \brief
01741  * when we create or delete references, make sure to use these
01742  * functions so we keep track of the refcounts.
01743  * To simplify the code, we allow a NULL to be passed to dialog_unref().
01744  */
01745 #ifdef REF_DEBUG
01746 #define dialog_ref(arg1,arg2) dialog_ref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
01747 #define dialog_unref(arg1,arg2) dialog_unref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
01748 
01749 static struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
01750 {
01751    if (p)
01752       _ao2_ref_debug(p, 1, tag, file, line, func);
01753    else
01754       ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
01755    return p;
01756 }
01757 
01758 static struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
01759 {
01760    if (p)
01761       _ao2_ref_debug(p, -1, tag, file, line, func);
01762    return NULL;
01763 }
01764 #else
01765 static struct sip_pvt *dialog_ref(struct sip_pvt *p, char *tag)
01766 {
01767    if (p)
01768       ao2_ref(p, 1);
01769    else
01770       ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
01771    return p;
01772 }
01773 
01774 static struct sip_pvt *dialog_unref(struct sip_pvt *p, char *tag)
01775 {
01776    if (p)
01777       ao2_ref(p, -1);
01778    return NULL;
01779 }
01780 #endif
01781 
01782 /*! \brief sip packet - raw format for outbound packets that are sent or scheduled for transmission
01783  * Packets are linked in a list, whose head is in the struct sip_pvt they belong to.
01784  * Each packet holds a reference to the parent struct sip_pvt.
01785  * This structure is allocated in __sip_reliable_xmit() and only for packets that
01786  * require retransmissions.
01787  */
01788 struct sip_pkt {
01789    struct sip_pkt *next;         /*!< Next packet in linked list */
01790    int retrans;            /*!< Retransmission number */
01791    int method;          /*!< SIP method for this packet */
01792    int seqno;           /*!< Sequence number */
01793    char is_resp;           /*!< 1 if this is a response packet (e.g. 200 OK), 0 if it is a request */
01794    char is_fatal;          /*!< non-zero if there is a fatal error */
01795    int response_code;      /*!< If this is a response, the response code */
01796    struct sip_pvt *owner;        /*!< Owner AST call */
01797    int retransid;          /*!< Retransmission ID */
01798    int timer_a;            /*!< SIP timer A, retransmission timer */
01799    int timer_t1;           /*!< SIP Timer T1, estimated RTT or 500 ms */
01800    int packetlen;          /*!< Length of packet */
01801    struct ast_str *data;
01802 }; 
01803 
01804 /*!
01805  * \brief A peer's mailbox
01806  *
01807  * We could use STRINGFIELDS here, but for only two strings, it seems like
01808  * too much effort ...
01809  */
01810 struct sip_mailbox {
01811    char *mailbox;
01812    char *context;
01813    unsigned int delme:1;
01814    /*! Associated MWI subscription */
01815    struct ast_event_sub *event_sub;
01816    AST_LIST_ENTRY(sip_mailbox) entry;
01817 };
01818 
01819 enum sip_peer_type {
01820    SIP_TYPE_PEER = (1 << 0),
01821    SIP_TYPE_USER = (1 << 1),
01822 };
01823 
01824 /*! \brief Structure for SIP peer data, we place calls to peers if registered  or fixed IP address (host) 
01825 */
01826 /* XXX field 'name' must be first otherwise sip_addrcmp() will fail, as will astobj2 hashing of the structure */
01827 struct sip_peer {
01828    char name[80];             /*!< the unique name of this object */
01829    AST_DECLARE_STRING_FIELDS(
01830       AST_STRING_FIELD(secret);     /*!< Password for inbound auth */
01831       AST_STRING_FIELD(md5secret);     /*!< Password in MD5 */
01832       AST_STRING_FIELD(remotesecret);     /*!< Remote secret (trunks, remote devices) */
01833       AST_STRING_FIELD(context);    /*!< Default context for incoming calls */
01834       AST_STRING_FIELD(subscribecontext); /*!< Default context for subscriptions */
01835       AST_STRING_FIELD(username);      /*!< Temporary username until registration */ 
01836       AST_STRING_FIELD(accountcode);      /*!< Account code */
01837       AST_STRING_FIELD(tohost);     /*!< If not dynamic, IP address */
01838       AST_STRING_FIELD(regexten);      /*!< Extension to register (if regcontext is used) */
01839       AST_STRING_FIELD(fromuser);      /*!< From: user when calling this peer */
01840       AST_STRING_FIELD(fromdomain);    /*!< From: domain when calling this peer */
01841       AST_STRING_FIELD(fullcontact);      /*!< Contact registered with us (not in sip.conf) */
01842       AST_STRING_FIELD(cid_num);    /*!< Caller ID num */
01843       AST_STRING_FIELD(cid_name);      /*!< Caller ID name */
01844       AST_STRING_FIELD(vmexten);       /*!< Dialplan extension for MWI notify message*/
01845       AST_STRING_FIELD(language);      /*!<  Default language for prompts */
01846       AST_STRING_FIELD(mohinterpret);     /*!<  Music on Hold class */
01847       AST_STRING_FIELD(mohsuggest);    /*!<  Music on Hold class */
01848       AST_STRING_FIELD(parkinglot);    /*!<  Parkinglot */
01849       AST_STRING_FIELD(useragent);     /*!<  User agent in SIP request (saved from registration) */
01850       );
01851    struct sip_socket socket;  /*!< Socket used for this peer */
01852    enum sip_transport default_outbound_transport;    /*!< Peer Registration may change the default outbound transport.
01853                                     If register expires, default should be reset. to this value */
01854    unsigned int transports:3;      /*!< Transports (enum sip_transport) that are acceptable for this peer */
01855    struct sip_auth *auth;     /*!< Realm authentication list */
01856    int amaflags;        /*!< AMA Flags (for billing) */
01857    int callingpres;     /*!< Calling id presentation */
01858    int inUse;        /*!< Number of calls in use */
01859    int inRinging;       /*!< Number of calls ringing */
01860    int onHold;                     /*!< Peer has someone on hold */
01861    int call_limit;         /*!< Limit of concurrent calls */
01862    int t38_maxdatagram;    /*!< T.38 FaxMaxDatagram override */
01863    int busy_level;         /*!< Level of active channels where we signal busy */
01864    enum transfermodes allowtransfer;   /*! SIP Refer restriction scheme */
01865    struct ast_codec_pref prefs;  /*!<  codec prefs */
01866    int lastmsgssent;
01867    unsigned int sipoptions;   /*!<  Supported SIP options */
01868    struct ast_flags flags[2]; /*!<  SIP_ flags */
01869 
01870    /*! Mailboxes that this peer cares about */
01871    AST_LIST_HEAD_NOLOCK(, sip_mailbox) mailboxes;
01872 
01873    /* things that don't belong in flags */
01874    char is_realtime;    /*!< this is a 'realtime' peer */
01875    char rt_fromcontact;    /*!< copy fromcontact from realtime */
01876    char host_dynamic;      /*!< Dynamic Peers register with Asterisk */
01877    char selfdestruct;      /*!< Automatic peers need to destruct themselves */
01878    char the_mark;       /*!< moved out of ASTOBJ into struct proper; That which bears the_mark should be deleted! */
01879 
01880    int expire;       /*!<  When to expire this peer registration */
01881    int capability;         /*!<  Codec capability */
01882    int rtptimeout;         /*!<  RTP timeout */
01883    int rtpholdtimeout;     /*!<  RTP Hold Timeout */
01884    int rtpkeepalive;    /*!<  Send RTP packets for keepalive */
01885    ast_group_t callgroup;     /*!<  Call group */
01886    ast_group_t pickupgroup;   /*!<  Pickup group */
01887    struct sip_proxy *outboundproxy; /*!< Outbound proxy for this peer */
01888    struct ast_dnsmgr_entry *dnsmgr;/*!<  DNS refresh manager for peer */
01889    struct sockaddr_in addr;   /*!<  IP address of peer */
01890    int maxcallbitrate;     /*!< Maximum Bitrate for a video call */
01891    unsigned int portinuri:1;  /*!< Whether the port should be included in the URI */
01892 
01893    /* Qualification */
01894    struct sip_pvt *call;      /*!<  Call pointer */
01895    int pokeexpire;         /*!<  When to expire poke (qualify= checking) */
01896    int lastms;       /*!<  How long last response took (in ms), or -1 for no response */
01897    int maxms;        /*!<  Max ms we will accept for the host to be up, 0 to not monitor */
01898    int qualifyfreq;     /*!<  Qualification: How often to check for the host to be up */
01899    struct timeval ps;      /*!<  Time for sending SIP OPTION in sip_pke_peer() */
01900    struct sockaddr_in defaddr;   /*!<  Default IP address, used until registration */
01901    struct ast_ha *ha;      /*!<  Access control list */
01902    struct ast_ha *contactha;       /*!<  Restrict what IPs are allowed in the Contact header (for registration) */
01903    struct ast_variable *chanvars;   /*!<  Variables to set for channel created by user */
01904    struct sip_pvt *mwipvt;    /*!<  Subscription for MWI */
01905    int autoframing;
01906    struct sip_st_cfg stimer;  /*!<  SIP Session-Timers */
01907    int timer_t1;        /*!<  The maximum T1 value for the peer */
01908    int timer_b;         /*!<  The maximum timer B (transaction timeouts) */
01909    int deprecated_username; /*!< If it's a realtime peer, are they using the deprecated "username" instead of "defaultuser" */
01910    
01911    /*XXX Seems like we suddenly have two flags with the same content. Why? To be continued... */
01912    enum sip_peer_type type; /*!< Distinguish between "user" and "peer" types. This is used solely for CLI and manager commands */
01913 };
01914 
01915 
01916 /*! 
01917  * \brief Registrations with other SIP proxies
01918  *
01919  * Created by sip_register(), the entry is linked in the 'regl' list,
01920  * and never deleted (other than at 'sip reload' or module unload times).
01921  * The entry always has a pending timeout, either waiting for an ACK to
01922  * the REGISTER message (in which case we have to retransmit the request),
01923  * or waiting for the next REGISTER message to be sent (either the initial one,
01924  * or once the previously completed registration one expires).
01925  * The registration can be in one of many states, though at the moment
01926  * the handling is a bit mixed.
01927  */
01928 struct sip_registry {
01929    ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
01930    AST_DECLARE_STRING_FIELDS(
01931       AST_STRING_FIELD(callid);  /*!< Global Call-ID */
01932       AST_STRING_FIELD(realm);   /*!< Authorization realm */
01933       AST_STRING_FIELD(nonce);   /*!< Authorization nonce */
01934       AST_STRING_FIELD(opaque);  /*!< Opaque nonsense */
01935       AST_STRING_FIELD(qop);     /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
01936       AST_STRING_FIELD(domain);  /*!< Authorization domain */
01937       AST_STRING_FIELD(username);   /*!< Who we are registering as */
01938       AST_STRING_FIELD(authuser);   /*!< Who we *authenticate* as */
01939       AST_STRING_FIELD(hostname);   /*!< Domain or host we register to */
01940       AST_STRING_FIELD(secret);  /*!< Password in clear text */   
01941       AST_STRING_FIELD(md5secret);  /*!< Password in md5 */
01942       AST_STRING_FIELD(callback);   /*!< Contact extension */
01943       AST_STRING_FIELD(random);
01944       AST_STRING_FIELD(peername);   /*!< Peer registering to */
01945    );
01946    enum sip_transport transport; /*!< Transport for this registration UDP, TCP or TLS */
01947    int portno;       /*!<  Optional port override */
01948    int expire;       /*!< Sched ID of expiration */
01949    int configured_expiry;     /*!< Configured value to use for the Expires header */
01950    int expiry;       /*!< Negotiated value used for the Expires header */
01951    int regattempts;     /*!< Number of attempts (since the last success) */
01952    int timeout;         /*!< sched id of sip_reg_timeout */
01953    int refresh;         /*!< How often to refresh */
01954    struct sip_pvt *call;      /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
01955    enum sipregistrystate regstate;  /*!< Registration state (see above) */
01956    struct timeval regtime;    /*!< Last successful registration time */
01957    int callid_valid;    /*!< 0 means we haven't chosen callid for this registry yet. */
01958    unsigned int ocseq;     /*!< Sequence number we got to for REGISTERs for this registry */
01959    struct ast_dnsmgr_entry *dnsmgr; /*!<  DNS refresh manager for register */
01960    struct sockaddr_in us;     /*!< Who the server thinks we are */
01961    int noncecount;         /*!< Nonce-count */
01962    char lastmsg[256];      /*!< Last Message sent/received */
01963 };
01964 
01965 enum sip_tcptls_alert {
01966    /*! \brief There is new data to be sent out */
01967    TCPTLS_ALERT_DATA,
01968    /*! \brief A request to stop the tcp_handler thread */
01969    TCPTLS_ALERT_STOP,
01970 };
01971 
01972 struct tcptls_packet {
01973    AST_LIST_ENTRY(tcptls_packet) entry;
01974    struct ast_str *data;
01975    size_t len;
01976 };
01977 /*! \brief Definition of a thread that handles a socket */
01978 struct sip_threadinfo {
01979    int stop;
01980    int alert_pipe[2]; /*! Used to alert tcptls thread when packet is ready to be written */
01981    pthread_t threadid;
01982    struct ast_tcptls_session_instance *tcptls_session;
01983    enum sip_transport type;   /*!< We keep a copy of the type here so we can display it in the connection list */
01984    AST_LIST_HEAD_NOLOCK(, tcptls_packet) packet_q;
01985 };
01986 
01987 /*! \brief Definition of an MWI subscription to another server */
01988 struct sip_subscription_mwi {
01989    ASTOBJ_COMPONENTS_FULL(struct sip_subscription_mwi,1,1);
01990    AST_DECLARE_STRING_FIELDS(
01991       AST_STRING_FIELD(username);     /*!< Who we are sending the subscription as */
01992       AST_STRING_FIELD(authuser);     /*!< Who we *authenticate* as */
01993       AST_STRING_FIELD(hostname);     /*!< Domain or host we subscribe to */
01994       AST_STRING_FIELD(secret);       /*!< Password in clear text */
01995       AST_STRING_FIELD(mailbox);      /*!< Mailbox store to put MWI into */
01996       );
01997    enum sip_transport transport;    /*!< Transport to use */
01998    int portno;                      /*!< Optional port override */
01999    int resub;                       /*!< Sched ID of resubscription */
02000    unsigned int subscribed:1;       /*!< Whether we are currently subscribed or not */
02001    struct sip_pvt *call;            /*!< Outbound subscription dialog */
02002    struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager for subscription */
02003    struct sockaddr_in us;           /*!< Who the server thinks we are */
02004 };
02005 
02006 /* --- Hash tables of various objects --------*/
02007 #ifdef LOW_MEMORY
02008 static const int HASH_PEER_SIZE = 17;
02009 static const int HASH_DIALOG_SIZE = 17;
02010 #else
02011 static const int HASH_PEER_SIZE = 563; /*!< Size of peer hash table, prime number preferred! */
02012 static const int HASH_DIALOG_SIZE = 563;
02013 #endif
02014 static struct ao2_container *threadt;
02015 
02016 /*! \brief  The peer list: Users, Peers and Friends */
02017 struct ao2_container *peers;
02018 struct ao2_container *peers_by_ip;
02019 
02020 /*! \brief  The register list: Other SIP proxies we register with and place calls to */
02021 static struct ast_register_list {
02022    ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
02023    int recheck;
02024 } regl;
02025 
02026 /*! \brief  The MWI subscription list */
02027 static struct ast_subscription_mwi_list {
02028    ASTOBJ_CONTAINER_COMPONENTS(struct sip_subscription_mwi);
02029 } submwil;
02030 
02031 /*! \brief
02032  * \note The only member of the peer used here is the name field
02033  */
02034 static int peer_hash_cb(const void *obj, const int flags)
02035 {
02036    const struct sip_peer *peer = obj;
02037 
02038    return ast_str_case_hash(peer->name);
02039 }
02040 
02041 /*!
02042  * \note The only member of the peer used here is the name field
02043  */
02044 static int peer_cmp_cb(void *obj, void *arg, int flags)
02045 {
02046    struct sip_peer *peer = obj, *peer2 = arg;
02047 
02048    return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
02049 }
02050 
02051 /*!
02052  * \note the peer's ip address field is used to create key.
02053  */
02054 static int peer_iphash_cb(const void *obj, const int flags)
02055 {
02056    const struct sip_peer *peer = obj;
02057    int ret1 = peer->addr.sin_addr.s_addr;
02058    if (ret1 < 0)
02059       ret1 = -ret1;
02060 
02061    return ret1;
02062 }
02063 
02064 /*!
02065  * Match Peers by IP and Port number.
02066  *
02067  * This function has two modes.
02068  *  - If the peer arg does not have INSECURE_PORT set, then we will only return
02069  *    a match for a peer that matches both the IP and port.
02070  *  - If the peer arg does have the INSECURE_PORT flag set, then we will only
02071  *    return a match for a peer that matches the IP and has insecure=port
02072  *    in its configuration.
02073  *
02074  * This callback will be used twice when doing peer matching.  There is a first
02075  * pass for full IP+port matching, and a second pass in case there is a match
02076  * that meets the insecure=port criteria.
02077  *
02078  * \note Connections coming in over TCP or TLS should never be matched by port.
02079  *
02080  * \note the peer's addr struct provides to fields combined to make a key: the sin_addr.s_addr and sin_port fields.
02081  */
02082 static int peer_ipcmp_cb(void *obj, void *arg, int flags)
02083 {
02084    struct sip_peer *peer = obj, *peer2 = arg;
02085 
02086    if (peer->addr.sin_addr.s_addr != peer2->addr.sin_addr.s_addr) {
02087       /* IP doesn't match */
02088       return 0;
02089    }
02090 
02091    /* We matched the IP, check to see if we need to match by port as well. */
02092    if ((peer->transports & peer2->transports) & (SIP_TRANSPORT_TLS | SIP_TRANSPORT_TCP)) {
02093       /* peer matching on port is not possible with TCP/TLS */
02094       return CMP_MATCH | CMP_STOP;
02095    } else if (ast_test_flag(&peer2->flags[0], SIP_INSECURE_PORT)) {
02096       /* We are allowing match without port for peers configured that
02097        * way in this pass through the peers. */
02098       return ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT) ?
02099             (CMP_MATCH | CMP_STOP) : 0;
02100    }
02101 
02102    /* Now only return a match if the port matches, as well. */
02103    return peer->addr.sin_port == peer2->addr.sin_port ? (CMP_MATCH | CMP_STOP) : 0;
02104 }
02105 
02106 
02107 static int threadt_hash_cb(const void *obj, const int flags)
02108 {
02109    const struct sip_threadinfo *th = obj;
02110 
02111    return (int) th->tcptls_session->remote_address.sin_addr.s_addr;
02112 }
02113 
02114 static int threadt_cmp_cb(void *obj, void *arg, int flags)
02115 {
02116    struct sip_threadinfo *th = obj, *th2 = arg;
02117 
02118    return (th->tcptls_session == th2->tcptls_session) ? CMP_MATCH | CMP_STOP : 0;
02119 }
02120 
02121 /*!
02122  * \note The only member of the dialog used here callid string
02123  */
02124 static int dialog_hash_cb(const void *obj, const int flags)
02125 {
02126    const struct sip_pvt *pvt = obj;
02127 
02128    return ast_str_case_hash(pvt->callid);
02129 }
02130 
02131 /*!
02132  * \note The only member of the dialog used here callid string
02133  */
02134 static int dialog_cmp_cb(void *obj, void *arg, int flags)
02135 {
02136    struct sip_pvt *pvt = obj, *pvt2 = arg;
02137    
02138    return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH | CMP_STOP : 0;
02139 }
02140 
02141 static int temp_pvt_init(void *);
02142 static void temp_pvt_cleanup(void *);
02143 
02144 /*! \brief A per-thread temporary pvt structure */
02145 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
02146 
02147 #ifdef LOW_MEMORY
02148 static void ts_ast_rtp_destroy(void *);
02149 
02150 AST_THREADSTORAGE_CUSTOM(ts_audio_rtp, NULL, ts_ast_rtp_destroy);
02151 AST_THREADSTORAGE_CUSTOM(ts_video_rtp, NULL, ts_ast_rtp_destroy);
02152 AST_THREADSTORAGE_CUSTOM(ts_text_rtp, NULL, ts_ast_rtp_destroy);
02153 #endif
02154 
02155 /*! \brief Authentication list for realm authentication 
02156  * \todo Move the sip_auth list to AST_LIST */
02157 static struct sip_auth *authl = NULL;
02158 
02159 
02160 /* --- Sockets and networking --------------*/
02161 
02162 /*! \brief Main socket for UDP SIP communication.
02163  *
02164  * sipsock is shared between the SIP manager thread (which handles reload
02165  * requests), the udp io handler (sipsock_read()) and the user routines that
02166  * issue udp writes (using __sip_xmit()).
02167  * The socket is -1 only when opening fails (this is a permanent condition),
02168  * or when we are handling a reload() that changes its address (this is
02169  * a transient situation during which we might have a harmless race, see
02170  * below). Because the conditions for the race to be possible are extremely
02171  * rare, we don't want to pay the cost of locking on every I/O.
02172  * Rather, we remember that when the race may occur, communication is
02173  * bound to fail anyways, so we just live with this event and let
02174  * the protocol handle this above us.
02175  */
02176 static int sipsock  = -1;
02177 
02178 static struct sockaddr_in bindaddr; /*!< UDP: The address we bind to */
02179 
02180 /*! \brief our (internal) default address/port to put in SIP/SDP messages
02181  *  internip is initialized picking a suitable address from one of the
02182  * interfaces, and the same port number we bind to. It is used as the
02183  * default address/port in SIP messages, and as the default address
02184  * (but not port) in SDP messages.
02185  */
02186 static struct sockaddr_in internip;
02187 
02188 /*! \brief our external IP address/port for SIP sessions.
02189  * externip.sin_addr is only set when we know we might be behind
02190  * a NAT, and this is done using a variety of (mutually exclusive)
02191  * ways from the config file:
02192  *
02193  * + with "externip = host[:port]" we specify the address/port explicitly.
02194  *   The address is looked up only once when (re)loading the config file;
02195  * 
02196  * + with "externhost = host[:port]" we do a similar thing, but the
02197  *   hostname is stored in externhost, and the hostname->IP mapping
02198  *   is refreshed every 'externrefresh' seconds;
02199  * 
02200  * + with "stunaddr = host[:port]" we run queries every externrefresh seconds
02201  *   to the specified server, and store the result in externip.
02202  *
02203  * Other variables (externhost, externexpire, externrefresh) are used
02204  * to support the above functions.
02205  */
02206 static struct sockaddr_in externip;    /*!< External IP address if we are behind NAT */
02207 
02208 static char externhost[MAXHOSTNAMELEN];      /*!< External host name */
02209 static time_t externexpire;         /*!< Expiration counter for re-resolving external host name in dynamic DNS */
02210 static int externrefresh = 10;
02211 static struct sockaddr_in stunaddr;    /*!< stun server address */
02212 
02213 /*! \brief  List of local networks
02214  * We store "localnet" addresses from the config file into an access list,
02215  * marked as 'DENY', so the call to ast_apply_ha() will return
02216  * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
02217  * (i.e. presumably public) addresses.
02218  */
02219 static struct ast_ha *localaddr;    /*!< List of local networks, on the same side of NAT as this Asterisk */
02220 
02221 static int ourport_tcp;          /*!< The port used for TCP connections */
02222 static int ourport_tls;          /*!< The port used for TCP/TLS connections */
02223 static struct sockaddr_in debugaddr;
02224 
02225 static struct ast_config *notify_types = NULL;     /*!< The list of manual NOTIFY types we know how to send */
02226 
02227 /*! some list management macros. */
02228  
02229 #define UNLINK(element, head, prev) do {  \
02230    if (prev)            \
02231       (prev)->next = (element)->next;  \
02232    else              \
02233       (head) = (element)->next;  \
02234    } while (0)
02235 
02236 enum t38_action_flag {
02237    SDP_T38_NONE = 0, /*!< Do not modify T38 information at all */
02238    SDP_T38_INITIATE, /*!< Remote side has requested T38 with us */
02239    SDP_T38_ACCEPT,   /*!< Remote side accepted our T38 request */
02240 };
02241 
02242 /*---------------------------- Forward declarations of functions in chan_sip.c */
02243 /* Note: This is added to help splitting up chan_sip.c into several files
02244    in coming releases. */
02245 
02246 /*--- PBX interface functions */
02247 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
02248 static int sip_devicestate(void *data);
02249 static int sip_sendtext(struct ast_channel *ast, const char *text);
02250 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
02251 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
02252 static int sip_hangup(struct ast_channel *ast);
02253 static int sip_answer(struct ast_channel *ast);
02254 static struct ast_frame *sip_read(struct ast_channel *ast);
02255 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
02256 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
02257 static int sip_transfer(struct ast_channel *ast, const char *dest);
02258 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
02259 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
02260 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
02261 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
02262 static const char *sip_get_callid(struct ast_channel *chan);
02263 
02264 static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin);
02265 static int sip_standard_port(enum sip_transport type, int port);
02266 static int sip_prepare_socket(struct sip_pvt *p);
02267 static int sip_parse_host(char *line, int lineno, char **hostname, int *portnum, enum sip_transport *transport);
02268 
02269 /*--- Transmitting responses and requests */
02270 static int sipsock_read(int *id, int fd, short events, void *ignore);
02271 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len);
02272 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod);
02273 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
02274 static int retrans_pkt(const void *data);
02275 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);
02276 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
02277 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
02278 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
02279 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp);
02280 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
02281 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);
02282 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
02283 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
02284 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable);
02285 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
02286 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
02287 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
02288 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
02289 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
02290 static int transmit_info_with_vidupdate(struct sip_pvt *p);
02291 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
02292 static int transmit_refer(struct sip_pvt *p, const char *dest);
02293 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
02294 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
02295 static int transmit_notify_custom(struct sip_pvt *p, struct ast_variable *vars);
02296 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
02297 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
02298 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
02299 static void copy_request(struct sip_request *dst, const struct sip_request *src);
02300 static void receive_message(struct sip_pvt *p, struct sip_request *req);
02301 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req);
02302 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only);
02303 
02304 /*--- Dialog management */
02305 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
02306              int useglobal_nat, const int intended_method, struct sip_request *req);
02307 static int __sip_autodestruct(const void *data);
02308 static void sip_scheddestroy(struct sip_pvt *p, int ms);
02309 static int sip_cancel_destroy(struct sip_pvt *p);
02310 static struct sip_pvt *sip_destroy(struct sip_pvt *p);
02311 static void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist);
02312 static void *registry_unref(struct sip_registry *reg, char *tag);
02313 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist);
02314 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
02315 static void __sip_pretend_ack(struct sip_pvt *p);
02316 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
02317 static int auto_congest(const void *arg);
02318 static int update_call_counter(struct sip_pvt *fup, int event);
02319 static int hangup_sip2cause(int cause);
02320 static const char *hangup_cause2sip(int cause);
02321 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
02322 static void free_old_route(struct sip_route *route);
02323 static void list_route(struct sip_route *route);
02324 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
02325 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
02326                      struct sip_request *req, char *uri);
02327 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
02328 static void check_pendings(struct sip_pvt *p);
02329 static void *sip_park_thread(void *stuff);
02330 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
02331 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
02332 
02333 /*--- Codec handling / SDP */
02334 static void try_suggested_sip_codec(struct sip_pvt *p);
02335 static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
02336 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
02337 static int find_sdp(struct sip_request *req);
02338 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
02339 static int process_sdp_o(const char *o, struct sip_pvt *p);
02340 static int process_sdp_c(const char *c, struct ast_hostent *hp);
02341 static int process_sdp_a_sendonly(const char *a, int *sendonly);
02342 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp *newaudiortp, int *last_rtpmap_codec);
02343 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp *newvideortp, int *last_rtpmap_codec);
02344 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);
02345 static int process_sdp_a_image(const char *a, struct sip_pvt *p);
02346 static void add_codec_to_sdp(const struct sip_pvt *p, int codec,
02347               struct ast_str **m_buf, struct ast_str **a_buf,
02348               int debug, int *min_packet_size);
02349 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
02350             struct ast_str **m_buf, struct ast_str **a_buf,
02351             int debug);
02352 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
02353 static void do_setnat(struct sip_pvt *p, int natflags);
02354 static void stop_media_flows(struct sip_pvt *p);
02355 
02356 /*--- Authentication stuff */
02357 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
02358 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
02359 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
02360                 const char *secret, const char *md5secret, int sipmethod,
02361                 char *uri, enum xmittype reliable, int ignore);
02362 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
02363                      int sipmethod, char *uri, enum xmittype reliable,
02364                      struct sockaddr_in *sin, struct sip_peer **authpeer);
02365 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);
02366 
02367 /*--- Domain handling */
02368 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
02369 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
02370 static void clear_sip_domains(void);
02371 
02372 /*--- SIP realm authentication */
02373 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno);
02374 static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */
02375 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
02376 
02377 /*--- Misc functions */
02378 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t);
02379 static int sip_do_reload(enum channelreloadreason reason);
02380 static int reload_config(enum channelreloadreason reason);
02381 static int expire_register(const void *data);
02382 static void *do_monitor(void *data);
02383 static int restart_monitor(void);
02384 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
02385 static struct ast_variable *copy_vars(struct ast_variable *src);
02386 /* static int sip_addrcmp(char *name, struct sockaddr_in *sin);   Support for peer matching */
02387 static int sip_refer_allocate(struct sip_pvt *p);
02388 static void ast_quiet_chan(struct ast_channel *chan);
02389 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
02390 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
02391 
02392 /*!
02393  * \brief generic function for determining if a correct transport is being 
02394  * used to contact a peer
02395  *
02396  * this is done as a macro so that the "tmpl" var can be passed either a 
02397  * sip_request or a sip_peer 
02398  */
02399 #define check_request_transport(peer, tmpl) ({ \
02400    int ret = 0; \
02401    if (peer->socket.type == tmpl->socket.type) \
02402       ; \
02403    else if (!(peer->transports & tmpl->socket.type)) {\
02404       ast_log(LOG_ERROR, \
02405          "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
02406          get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
02407          ); \
02408       ret = 1; \
02409    } else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
02410       ast_log(LOG_WARNING, \
02411          "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
02412          peer->name, get_transport(tmpl->socket.type) \
02413       ); \
02414    } else { \
02415       ast_debug(1, \
02416          "peer '%s' has contacted us over %s even though we prefer %s.\n", \
02417          peer->name, get_transport(tmpl->socket.type), get_transport(peer->socket.type) \
02418       ); \
02419    }\
02420    (ret); \
02421 })
02422 
02423 
02424 /*--- Device monitoring and Device/extension state/event handling */
02425 static int cb_extensionstate(char *context, char* exten, int state, void *data);
02426 static int sip_devicestate(void *data);
02427 static int sip_poke_noanswer(const void *data);
02428 static int sip_poke_peer(struct sip_peer *peer, int force);
02429 static void sip_poke_all_peers(void);
02430 static void sip_peer_hold(struct sip_pvt *p, int hold);
02431 static void mwi_event_cb(const struct ast_event *, void *);
02432 
02433 /*--- Applications, functions, CLI and manager command helpers */
02434 static const char *sip_nat_mode(const struct sip_pvt *p);
02435 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02436 static char *transfermode2str(enum transfermodes mode) attribute_const;
02437 static const char *nat2str(int nat) attribute_const;
02438 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
02439 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02440 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02441 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02442 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02443 static void  print_group(int fd, ast_group_t group, int crlf);
02444 static const char *dtmfmode2str(int mode) attribute_const;
02445 static int str2dtmfmode(const char *str) attribute_unused;
02446 static const char *insecure2str(int mode) attribute_const;
02447 static void cleanup_stale_contexts(char *new, char *old);
02448 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
02449 static const char *domain_mode_to_text(const enum domain_mode mode);
02450 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02451 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02452 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02453 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02454 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02455 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02456 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02457 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02458 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02459 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
02460 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
02461 static char *complete_sip_peer(const char *word, int state, int flags2);
02462 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
02463 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
02464 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
02465 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
02466 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
02467 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02468 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02469 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02470 static char *sip_do_debug_ip(int fd, char *arg);
02471 static char *sip_do_debug_peer(int fd, char *arg);
02472 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02473 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02474 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02475 static int sip_dtmfmode(struct ast_channel *chan, void *data);
02476 static int sip_addheader(struct ast_channel *chan, void *data);
02477 static int sip_do_reload(enum channelreloadreason reason);
02478 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02479 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
02480 
02481 /*--- Debugging 
02482    Functions for enabling debug per IP or fully, or enabling history logging for
02483    a SIP dialog
02484 */
02485 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to debuglog at end of dialog, before destroying data */
02486 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
02487 static inline int sip_debug_test_pvt(struct sip_pvt *p);
02488 
02489 
02490 /*! \brief Append to SIP dialog history 
02491    \return Always returns 0 */
02492 #define append_history(p, event, fmt , args... )   append_history_full(p, "%-15s " fmt, event, ## args)
02493 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
02494 static void sip_dump_history(struct sip_pvt *dialog);
02495 
02496 /*--- Device object handling */
02497 static struct sip_peer *temp_peer(const char *name);
02498 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
02499 static int update_call_counter(struct sip_pvt *fup, int event);
02500 static void sip_destroy_peer(struct sip_peer *peer);
02501 static void sip_destroy_peer_fn(void *peer);
02502 static void set_peer_defaults(struct sip_peer *peer);
02503 static struct sip_peer *temp_peer(const char *name);
02504 static void register_peer_exten(struct sip_peer *peer, int onoff);
02505 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int forcenamematch, int devstate_only, int transport);
02506 static int sip_poke_peer_s(const void *data);
02507 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
02508 static void reg_source_db(struct sip_peer *peer);
02509 static void destroy_association(struct sip_peer *peer);
02510 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
02511 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
02512 static void set_socket_transport(struct sip_socket *socket, int transport);
02513 
02514 /* Realtime device support */
02515 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);
02516 static void update_peer(struct sip_peer *p, int expire);
02517 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
02518 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername);
02519 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin, int devstate_only);
02520 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02521 
02522 /*--- Internal UA client handling (outbound registrations) */
02523 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p);
02524 static void sip_registry_destroy(struct sip_registry *reg);
02525 static int sip_register(const char *value, int lineno);
02526 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
02527 static int sip_reregister(const void *data);
02528 static int __sip_do_register(struct sip_registry *r);
02529 static int sip_reg_timeout(const void *data);
02530 static void sip_send_all_registers(void);
02531 static int sip_reinvite_retry(const void *data);
02532 
02533 /*--- Parsing SIP requests and responses */
02534 static void append_date(struct sip_request *req);  /* Append date to SIP packet */
02535 static int determine_firstline_parts(struct sip_request *req);
02536 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
02537 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
02538 static int find_sip_method(const char *msg);
02539 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
02540 static int parse_request(struct sip_request *req);
02541 static const char *get_header(const struct sip_request *req, const char *name);
02542 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
02543 static int method_match(enum sipmethod id, const char *name);
02544 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
02545 static char *get_in_brackets(char *tmp);
02546 static const char *find_alias(const char *name, const char *_default);
02547 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
02548 static int lws2sws(char *msgbuf, int len);
02549 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
02550 static char *remove_uri_parameters(char *uri);
02551 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
02552 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
02553 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
02554 static int set_address_from_contact(struct sip_pvt *pvt);
02555 static void check_via(struct sip_pvt *p, struct sip_request *req);
02556 static char *get_calleridname(const char *input, char *output, size_t outputsize);
02557 static int get_rpid_num(const char *input, char *output, int maxlen);
02558 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
02559 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
02560 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline);
02561 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
02562 
02563 /*-- TCP connection handling ---*/
02564 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session);
02565 static void *sip_tcp_worker_fn(void *);
02566 
02567 /*--- Constructing requests and responses */
02568 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
02569 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
02570 static void deinit_req(struct sip_request *req);
02571 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
02572 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
02573 static int init_resp(struct sip_request *resp, const char *msg);
02574 static inline int resp_needs_contact(const char *msg, enum sipmethod method);
02575 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
02576 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
02577 static void build_via(struct sip_pvt *p);
02578 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
02579 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog);
02580 static char *generate_random_string(char *buf, size_t size);
02581 static void build_callid_pvt(struct sip_pvt *pvt);
02582 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
02583 static void make_our_tag(char *tagbuf, size_t len);
02584 static int add_header(struct sip_request *req, const char *var, const char *value);
02585 static int add_content(struct sip_request *req, const char *line);
02586 static int finalize_content(struct sip_request *req);
02587 static int add_text(struct sip_request *req, const char *text);
02588 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
02589 static int add_vidupdate(struct sip_request *req);
02590 static void add_route(struct sip_request *req, struct sip_route *route);
02591 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
02592 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
02593 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
02594 static void set_destination(struct sip_pvt *p, char *uri);
02595 static void append_date(struct sip_request *req);
02596 static void build_contact(struct sip_pvt *p);
02597 static void build_rpid(struct sip_pvt *p);
02598 
02599 /*------Request handling functions */
02600 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
02601 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);
02602 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
02603 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
02604 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
02605 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
02606 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
02607 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
02608 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
02609 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
02610 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *nounlock);
02611 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
02612 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);
02613 
02614 /*------Response handling functions */
02615 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02616 static void handle_response_notify(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02617 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02618 static void handle_response_subscribe(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02619 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02620 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02621 
02622 /*----- RTP interface functions */
02623 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);
02624 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02625 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02626 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02627 static int sip_get_codec(struct ast_channel *chan);
02628 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);
02629 
02630 /*------ T38 Support --------- */
02631 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
02632 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
02633 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
02634 static void change_t38_state(struct sip_pvt *p, int state);
02635 
02636 /*------ Session-Timers functions --------- */
02637 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
02638 static int  proc_session_timer(const void *vp);
02639 static void stop_session_timer(struct sip_pvt *p);
02640 static void start_session_timer(struct sip_pvt *p);
02641 static void restart_session_timer(struct sip_pvt *p);
02642 static const char *strefresher2str(enum st_refresher r);
02643 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
02644 static int parse_minse(const char *p_hdrval, int *const p_interval);
02645 static int st_get_se(struct sip_pvt *, int max);
02646 static enum st_refresher st_get_refresher(struct sip_pvt *);
02647 static enum st_mode st_get_mode(struct sip_pvt *);
02648 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
02649 
02650 /*!--- SIP MWI Subscription support */
02651 static int sip_subscribe_mwi(const char *value, int lineno);
02652 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
02653 static void sip_send_all_mwi_subscriptions(void);
02654 static int sip_subscribe_mwi_do(const void *data);
02655 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
02656 
02657 /*! \brief Definition of this channel for PBX channel registration */
02658 static const struct ast_channel_tech sip_tech = {
02659    .type = "SIP",
02660    .description = "Session Initiation Protocol (SIP)",
02661    .capabilities = AST_FORMAT_AUDIO_MASK, /* all audio formats */
02662    .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
02663    .requester = sip_request_call,         /* called with chan unlocked */
02664    .devicestate = sip_devicestate,        /* called with chan unlocked (not chan-specific) */
02665    .call = sip_call,       /* called with chan locked */
02666    .send_html = sip_sendhtml,
02667    .hangup = sip_hangup,         /* called with chan locked */
02668    .answer = sip_answer,         /* called with chan locked */
02669    .read = sip_read,       /* called with chan locked */
02670    .write = sip_write,        /* called with chan locked */
02671    .write_video = sip_write,     /* called with chan locked */
02672    .write_text = sip_write,
02673    .indicate = sip_indicate,     /* called with chan locked */
02674    .transfer = sip_transfer,     /* called with chan locked */
02675    .fixup = sip_fixup,        /* called with chan locked */
02676    .send_digit_begin = sip_senddigit_begin,  /* called with chan unlocked */
02677    .send_digit_end = sip_senddigit_end,
02678    .bridge = ast_rtp_bridge,        /* XXX chan unlocked ? */
02679    .early_bridge = ast_rtp_early_bridge,
02680    .send_text = sip_sendtext,    /* called with chan locked */
02681    .func_channel_read = acf_channel_read,
02682    .queryoption = sip_queryoption,
02683    .get_pvt_uniqueid = sip_get_callid,
02684 };
02685 
02686 /*! \brief This version of the sip channel tech has no send_digit_begin
02687  * callback so that the core knows that the channel does not want
02688  * DTMF BEGIN frames.
02689  * The struct is initialized just before registering the channel driver,
02690  * and is for use with channels using SIP INFO DTMF.
02691  */
02692 static struct ast_channel_tech sip_tech_info;
02693 
02694 
02695 /*! \brief Working TLS connection configuration */
02696 static struct ast_tls_config sip_tls_cfg;
02697 
02698 /*! \brief Default TLS connection configuration */
02699 static struct ast_tls_config default_tls_cfg;
02700 
02701 /*! \brief The TCP server definition */
02702 static struct ast_tcptls_session_args sip_tcp_desc = {
02703    .accept_fd = -1,
02704    .master = AST_PTHREADT_NULL,
02705    .tls_cfg = NULL,
02706    .poll_timeout = -1,
02707    .name = "SIP TCP server",
02708    .accept_fn = ast_tcptls_server_root,
02709    .worker_fn = sip_tcp_worker_fn,
02710 };
02711 
02712 /*! \brief The TCP/TLS server definition */
02713 static struct ast_tcptls_session_args sip_tls_desc = {
02714    .accept_fd = -1,
02715    .master = AST_PTHREADT_NULL,
02716    .tls_cfg = &sip_tls_cfg,
02717    .poll_timeout = -1,
02718    .name = "SIP TLS server",
02719    .accept_fn = ast_tcptls_server_root,
02720    .worker_fn = sip_tcp_worker_fn,
02721 };
02722 
02723 /* wrapper macro to tell whether t points to one of the sip_tech descriptors */
02724 #define IS_SIP_TECH(t)  ((t) == &sip_tech || (t) == &sip_tech_info)
02725 
02726 /*! \brief map from an integer value to a string.
02727  * If no match is found, return errorstring
02728  */
02729 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
02730 {
02731    const struct _map_x_s *cur;
02732 
02733    for (cur = table; cur->s; cur++)
02734       if (cur->x == x)
02735          return cur->s;
02736    return errorstring;
02737 }
02738 
02739 /*! \brief map from a string to an integer value, case insensitive.
02740  * If no match is found, return errorvalue.
02741  */
02742 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
02743 {
02744    const struct _map_x_s *cur;
02745 
02746    for (cur = table; cur->s; cur++)
02747       if (!strcasecmp(cur->s, s))
02748          return cur->x;
02749    return errorvalue;
02750 }
02751 
02752 
02753 /*! \brief Interface structure with callbacks used to connect to RTP module */
02754 static struct ast_rtp_protocol sip_rtp = {
02755    .type = "SIP",
02756    .get_rtp_info = sip_get_rtp_peer,
02757    .get_vrtp_info = sip_get_vrtp_peer,
02758    .get_trtp_info = sip_get_trtp_peer,
02759    .set_rtp_peer = sip_set_rtp_peer,
02760    .get_codec = sip_get_codec,
02761 };
02762 
02763 /*!
02764  * duplicate a list of channel variables, \return the copy.
02765  */
02766 static struct ast_variable *copy_vars(struct ast_variable *src)
02767 {
02768    struct ast_variable *res = NULL, *tmp, *v = NULL;
02769 
02770    for (v = src ; v ; v = v->next) {
02771       if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
02772          tmp->next = res;
02773          res = tmp;
02774       }
02775    }
02776    return res;
02777 }
02778 
02779 static void tcptls_packet_destructor(void *obj)
02780 {
02781    struct tcptls_packet *packet = obj;
02782 
02783    ast_free(packet->data);
02784 }
02785 
02786 static void sip_tcptls_client_args_destructor(void *obj)
02787 {
02788    struct ast_tcptls_session_args *args = obj;
02789    if (args->tls_cfg) {
02790       ast_free(args->tls_cfg->certfile);
02791       ast_free(args->tls_cfg->cipher);
02792       ast_free(args->tls_cfg->cafile);
02793       ast_free(args->tls_cfg->capath);
02794    }
02795    ast_free(args->tls_cfg);
02796    ast_free((char *) args->name);
02797 }
02798 
02799 static void sip_threadinfo_destructor(void *obj)
02800 {
02801    struct sip_threadinfo *th = obj;
02802    struct tcptls_packet *packet;
02803    if (th->alert_pipe[1] > -1) {
02804       close(th->alert_pipe[0]);
02805    }
02806    if (th->alert_pipe[1] > -1) {
02807       close(th->alert_pipe[1]);
02808    }
02809    th->alert_pipe[0] = th->alert_pipe[1] = -1;
02810 
02811    while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
02812       ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
02813    }
02814 
02815    if (th->tcptls_session) {
02816       ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
02817    }
02818 }
02819 
02820 /*! \brief creates a sip_threadinfo object and links it into the threadt table. */
02821 static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
02822 {
02823    struct sip_threadinfo *th;
02824 
02825    if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
02826       return NULL;
02827    }
02828 
02829    th->alert_pipe[0] = th->alert_pipe[1] = -1;
02830 
02831    if (pipe(th->alert_pipe) == -1) {
02832       ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
02833       ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
02834       return NULL;
02835    }
02836    ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
02837    th->tcptls_session = tcptls_session;
02838    th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
02839    ao2_t_link(threadt, th, "Adding new tcptls helper thread");
02840    ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
02841    return th;
02842 }
02843 
02844 /*! \brief used to indicate to a tcptls thread that data is ready to be written */
02845 static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
02846 {
02847    int res = len;
02848    struct sip_threadinfo *th = NULL;
02849    struct tcptls_packet *packet = NULL;
02850    struct sip_threadinfo tmp = {
02851       .tcptls_session = tcptls_session,
02852    };
02853    enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
02854 
02855    if (!tcptls_session) {
02856       return XMIT_ERROR;
02857    }
02858 
02859    ast_mutex_lock(&tcptls_session->lock);
02860 
02861    if ((tcptls_session->fd == -1) ||
02862       !(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
02863       !(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
02864       !(packet->data = ast_str_create(len))) {
02865       goto tcptls_write_setup_error;
02866    }
02867 
02868    /* goto tcptls_write_error should _NOT_ be used beyond this point */
02869    ast_str_set(&packet->data, 0, "%s", (char *) buf);
02870    packet->len = len;
02871 
02872    /* alert tcptls thread handler that there is a packet to be sent.
02873     * must lock the thread info object to guarantee control of the
02874     * packet queue */
02875    ao2_lock(th);
02876    if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
02877       ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
02878       ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
02879       packet = NULL;
02880       res = XMIT_ERROR;
02881    } else { /* it is safe to queue the frame after issuing the alert when we hold the threadinfo lock */
02882       AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
02883    }
02884    ao2_unlock(th);
02885 
02886    ast_mutex_unlock(&tcptls_session->lock);
02887    ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
02888    return res;
02889 
02890 tcptls_write_setup_error:
02891    if (th) {
02892       ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
02893    }
02894    if (packet) {
02895       ao2_t_ref(packet, -1, "could not allocate packet's data");
02896    }
02897    ast_mutex_unlock(&tcptls_session->lock);
02898 
02899    return XMIT_ERROR;
02900 }
02901 
02902 /*! \brief SIP TCP connection handler */
02903 static void *sip_tcp_worker_fn(void *data)
02904 {
02905    struct ast_tcptls_session_instance *tcptls_session = data;
02906 
02907    return _sip_tcp_helper_thread(NULL, tcptls_session);
02908 }
02909 
02910 /*! \brief SIP TCP thread management function 
02911    This function reads from the socket, parses the packet into a request
02912 */
02913 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session) 
02914 {
02915    int res, cl;
02916    struct sip_request req = { 0, } , reqcpy = { 0, };
02917    struct sip_threadinfo *me = NULL;
02918    char buf[1024] = "";
02919    struct pollfd fds[2] = { { 0 }, { 0 }, };
02920    struct ast_tcptls_session_args *ca = NULL;
02921 
02922    /* If this is a server session, then the connection has already been setup,
02923     * simply create the threadinfo object so we can access this thread for writing.
02924     * 
02925     * if this is a client connection more work must be done.
02926     * 1. We own the parent session args for a client connection.  This pointer needs
02927     *    to be held on to so we can decrement it's ref count on thread destruction.
02928     * 2. The threadinfo object was created before this thread was launched, however
02929     *    it must be found within the threadt table.
02930     * 3. Last, the tcptls_session must be started.
02931     */
02932    if (!tcptls_session->client) {
02933       if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
02934          goto cleanup;
02935       }
02936       ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
02937    } else {
02938       struct sip_threadinfo tmp = {
02939          .tcptls_session = tcptls_session,
02940       };
02941 
02942       if ((!(ca = tcptls_session->parent)) ||
02943          (!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
02944          (!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
02945          goto cleanup;
02946       }
02947    }
02948 
02949    me->threadid = pthread_self();
02950    ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
02951 
02952    /* set up pollfd to watch for reads on both the socket and the alert_pipe */
02953    fds[0].fd = tcptls_session->fd;
02954    fds[1].fd = me->alert_pipe[0];
02955    fds[0].events = fds[1].events = POLLIN | POLLPRI;
02956 
02957    if (!(req.data = ast_str_create(SIP_MIN_PACKET)))
02958       goto cleanup;
02959    if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET)))
02960       goto cleanup;
02961 
02962    for (;;) {
02963       struct ast_str *str_save;
02964 
02965       res = ast_poll(fds, 2, -1); /* polls for both socket and alert_pipe */
02966 
02967       if (res < 0) {
02968          ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
02969          goto cleanup;
02970       }
02971 
02972       /* handle the socket event, check for both reads from the socket fd,
02973        * and writes from alert_pipe fd */
02974       if (fds[0].revents) { /* there is data on the socket to be read */
02975 
02976          fds[0].revents = 0;
02977 
02978          /* clear request structure */
02979          str_save = req.data;
02980          memset(&req, 0, sizeof(req));
02981          req.data = str_save;
02982          ast_str_reset(req.data);
02983 
02984          str_save = reqcpy.data;
02985          memset(&reqcpy, 0, sizeof(reqcpy));
02986          reqcpy.data = str_save;
02987          ast_str_reset(reqcpy.data);
02988 
02989          memset(buf, 0, sizeof(buf));
02990 
02991          if (tcptls_session->ssl) {
02992             set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
02993             req.socket.port = htons(ourport_tls);
02994          } else {
02995             set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
02996             req.socket.port = htons(ourport_tcp);
02997          }
02998          req.socket.fd = tcptls_session->fd;
02999 
03000          /* Read in headers one line at a time */
03001          while (req.len < 4 || strncmp(REQ_OFFSET_TO_STR(&req, len - 4), "\r\n\r\n", 4)) {
03002             ast_mutex_lock(&tcptls_session->lock);
03003             if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
03004                ast_mutex_unlock(&tcptls_session->lock);
03005                goto cleanup;
03006             }
03007             ast_mutex_unlock(&tcptls_session->lock);
03008             if (me->stop)
03009                 goto cleanup;
03010             ast_str_append(&req.data, 0, "%s", buf);
03011             req.len = req.data->used;
03012          }
03013          copy_request(&reqcpy, &req);
03014          parse_request(&reqcpy);
03015          /* In order to know how much to read, we need the content-length header */
03016          if (sscanf(get_header(&reqcpy, "Content-Length"), "%30d", &cl)) {
03017             while (cl > 0) {
03018                size_t bytes_read;
03019                ast_mutex_lock(&tcptls_session->lock);
03020                if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, cl), tcptls_session->f))) {
03021                   ast_mutex_unlock(&tcptls_session->lock);
03022                   goto cleanup;
03023                }
03024                buf[bytes_read] = '\0';
03025                ast_mutex_unlock(&tcptls_session->lock);
03026                if (me->stop)
03027                   goto cleanup;
03028                cl -= strlen(buf);
03029                ast_str_append(&req.data, 0, "%s", buf);
03030                req.len = req.data->used;
03031             }
03032          }
03033          /*! \todo XXX If there's no Content-Length or if the content-length and what
03034                we receive is not the same - we should generate an error */
03035 
03036          req.socket.tcptls_session = tcptls_session;
03037          handle_request_do(&req, &tcptls_session->remote_address);
03038       }
03039 
03040       if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
03041          enum sip_tcptls_alert alert;
03042          struct tcptls_packet *packet;
03043 
03044          fds[1].revents = 0;
03045 
03046          if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
03047             ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
03048             continue;
03049          }
03050 
03051          switch (alert) {
03052          case TCPTLS_ALERT_STOP:
03053             goto cleanup;
03054          case TCPTLS_ALERT_DATA:
03055             ao2_lock(me);
03056             if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
03057                ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty");
03058             } else if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
03059                ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
03060             }
03061 
03062             if (packet) {
03063                ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
03064             }
03065             ao2_unlock(me);
03066             break;
03067          default:
03068             ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
03069          }
03070       }
03071    }
03072 
03073    ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
03074 
03075 cleanup:
03076    if (me) {
03077       ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
03078       ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
03079    }
03080    deinit_req(&reqcpy);
03081    deinit_req(&req);
03082 
03083    /* if client, we own the parent session arguments and must decrement ref */
03084    if (ca) {
03085       ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
03086    }
03087 
03088    if (tcptls_session) {
03089       ast_mutex_lock(&tcptls_session->lock);
03090       if (tcptls_session->f) {
03091          fclose(tcptls_session->f);
03092          tcptls_session->f = NULL;
03093       }
03094       if (tcptls_session->fd != -1) {
03095          close(tcptls_session->fd);
03096          tcptls_session->fd = -1;
03097       }
03098       tcptls_session->parent = NULL;
03099       ast_mutex_unlock(&tcptls_session->lock);
03100 
03101       ao2_ref(tcptls_session, -1);
03102       tcptls_session = NULL;
03103    }
03104    return NULL;
03105 }
03106 
03107 /* this func is used with ao2_callback to unlink/delete all marked
03108    peers */
03109 static int peer_is_marked(void *peerobj, void *arg, int flags)
03110 {
03111    struct sip_peer *peer = peerobj;
03112    return peer->the_mark ? CMP_MATCH : 0;
03113 }
03114 
03115 
03116 /* \brief Unlink all marked peers from ao2 containers */
03117 static void unlink_marked_peers_from_tables(void)
03118 {
03119    ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, NULL,
03120                   "initiating callback to remove marked peers");
03121    ao2_t_callback(peers_by_ip, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, NULL,
03122                   "initiating callback to remove marked peers");
03123 }
03124 
03125 /* \brief Unlink single peer from all ao2 containers */
03126 static void unlink_peer_from_tables(struct sip_peer *peer)
03127 {
03128    ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
03129    if (peer->addr.sin_addr.s_addr) {
03130       ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
03131    }
03132 }
03133 
03134 /*!
03135  * helper functions to unreference various types of objects.
03136  * By handling them this way, we don't have to declare the
03137  * destructor on each call, which removes the chance of errors.
03138  */
03139 static void *unref_peer(struct sip_peer *peer, char *tag)
03140 {
03141    ao2_t_ref(peer, -1, tag);
03142    return NULL;
03143 }
03144 
03145 static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
03146 {
03147    ao2_t_ref(peer, 1, tag);
03148    return peer;
03149 }
03150 
03151 /*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
03152  *
03153  * This function sets pvt's outboundproxy pointer to the one referenced
03154  * by the proxy parameter. Because proxy may be a refcounted object, and
03155  * because pvt's old outboundproxy may also be a refcounted object, we need
03156  * to maintain the proper refcounts.
03157  *
03158  * \param pvt The sip_pvt for which we wish to set the outboundproxy
03159  * \param proxy The sip_proxy which we will point pvt towards.
03160  * \return Returns void
03161  */
03162 static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
03163 {
03164    struct sip_proxy *old_obproxy = pvt->outboundproxy;
03165    /* The sip_cfg.outboundproxy is statically allocated, and so
03166     * we don't ever need to adjust refcounts for it
03167     */
03168    if (proxy && proxy != &sip_cfg.outboundproxy) {
03169       ao2_ref(proxy, +1);
03170    }
03171    pvt->outboundproxy = proxy;
03172    if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
03173       ao2_ref(old_obproxy, -1);
03174    }
03175 }
03176 
03177 /*!
03178  * \brief Unlink a dialog from the dialogs container, as well as any other places
03179  * that it may be currently stored.
03180  *
03181  * \note A reference to the dialog must be held before calling this function, and this
03182  * function does not release that reference.
03183  */
03184 static void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist)
03185 {
03186    struct sip_pkt *cp;
03187 
03188    dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
03189 
03190    ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
03191 
03192    /* Unlink us from the owner (channel) if we have one */
03193    if (dialog->owner) {
03194       if (lockowner)
03195          ast_channel_lock(dialog->owner);
03196       ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
03197       dialog->owner->tech_pvt = dialog_unref(dialog->owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
03198       if (lockowner)
03199          ast_channel_unlock(dialog->owner);
03200    }
03201    if (dialog->registry) {
03202       if (dialog->registry->call == dialog)
03203          dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
03204       dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
03205    }
03206    if (dialog->stateid > -1) {
03207       ast_extension_state_del(dialog->stateid, NULL);
03208       dialog_unref(dialog, "removing extension_state, should unref the associated dialog ptr that was stored there.");
03209       dialog->stateid = -1; /* shouldn't we 'zero' this out? */
03210    }
03211    /* Remove link from peer to subscription of MWI */
03212    if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog)
03213       dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
03214    if (dialog->relatedpeer && dialog->relatedpeer->call == dialog)
03215       dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
03216 
03217    /* remove all current packets in this dialog */
03218    while((cp = dialog->packets)) {
03219       dialog->packets = dialog->packets->next;
03220       AST_SCHED_DEL(sched, cp->retransid);
03221       dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
03222       if (cp->data) {
03223          ast_free(cp->data);
03224       }
03225       ast_free(cp);
03226    }
03227 
03228    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"));
03229 
03230    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"));
03231    
03232    if (dialog->autokillid > -1)
03233       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"));
03234 
03235    if (dialog->request_queue_sched_id > -1) {
03236       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"));
03237    }
03238 
03239    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"));
03240 
03241    if (dialog->t38id > -1) {
03242       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"));
03243    }
03244 
03245    dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
03246    return NULL;
03247 }
03248 
03249 static void *registry_unref(struct sip_registry *reg, char *tag)
03250 {
03251    ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
03252    ASTOBJ_UNREF(reg, sip_registry_destroy);
03253    return NULL;
03254 }
03255 
03256 /*! \brief Add object reference to SIP registry */
03257 static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
03258 {
03259    ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
03260    return ASTOBJ_REF(reg); /* Add pointer to registry in packet */
03261 }
03262 
03263 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
03264 static struct ast_udptl_protocol sip_udptl = {
03265    type: "SIP",
03266    get_udptl_info: sip_get_udptl_peer,
03267    set_udptl_peer: sip_set_udptl_peer,
03268 };
03269 
03270 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03271    __attribute__((format(printf, 2, 3)));
03272 
03273 
03274 /*! \brief Convert transfer status to string */
03275 static const char *referstatus2str(enum referstatus rstatus)
03276 {
03277    return map_x_s(referstatusstrings, rstatus, "");
03278 }
03279 
03280 static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
03281 {
03282    append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
03283    pvt->needdestroy = 1;
03284 }
03285 
03286 /*! \brief Initialize the initital request packet in the pvt structure.
03287    This packet is used for creating replies and future requests in
03288    a dialog */
03289 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
03290 {
03291    if (p->initreq.headers)
03292       ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
03293    else
03294       ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
03295    /* Use this as the basis */
03296    copy_request(&p->initreq, req);
03297    parse_request(&p->initreq);
03298    if (req->debug)
03299       ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
03300 }
03301 
03302 /*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
03303 static void sip_alreadygone(struct sip_pvt *dialog)
03304 {
03305    ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
03306    dialog->alreadygone = 1;
03307 }
03308 
03309 /*! Resolve DNS srv name or host name in a sip_proxy structure */
03310 static int proxy_update(struct sip_proxy *proxy)
03311 {
03312    /* if it's actually an IP address and not a name,
03313            there's no need for a managed lookup */
03314    if (!inet_aton(proxy->name, &proxy->ip.sin_addr)) {
03315       /* Ok, not an IP address, then let's check if it's a domain or host */
03316       /* XXX Todo - if we have proxy port, don't do SRV */
03317       if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
03318          ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
03319          return FALSE;
03320       }
03321    }
03322    proxy->last_dnsupdate = time(NULL);
03323    return TRUE;
03324 }
03325 
03326 /*! \brief converts ascii port to int representation. If no
03327  *  pt buffer is provided or the pt has errors when being converted
03328  *  to an int value, the port provided as the standard is used.
03329  */
03330 static int port_str2int(const char *pt, unsigned int standard)
03331 {
03332    int port = standard;
03333    if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
03334       port = standard;
03335    }
03336 
03337    return port;
03338 }
03339 
03340 /*! \brief Allocate and initialize sip proxy */
03341 static struct sip_proxy *proxy_allocate(char *name, char *port, int force)
03342 {
03343    struct sip_proxy *proxy;
03344 
03345    if (ast_strlen_zero(name)) {
03346       return NULL;
03347    }
03348 
03349    proxy = ao2_alloc(sizeof(*proxy), NULL);
03350    if (!proxy)
03351       return NULL;
03352    proxy->force = force;
03353    ast_copy_string(proxy->name, name, sizeof(proxy->name));
03354    proxy->ip.sin_port = htons(port_str2int(port, STANDARD_SIP_PORT));
03355    proxy->ip.sin_family = AF_INET;
03356    proxy_update(proxy);
03357    return proxy;
03358 }
03359 
03360 /*! \brief Get default outbound proxy or global proxy */
03361 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
03362 {
03363    if (peer && peer->outboundproxy) {
03364       if (sipdebug)
03365          ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
03366       append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
03367       return peer->outboundproxy;
03368    }
03369    if (sip_cfg.outboundproxy.name[0]) {
03370       if (sipdebug)
03371          ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
03372       append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
03373       return &sip_cfg.outboundproxy;
03374    }
03375    if (sipdebug)
03376       ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
03377    return NULL;
03378 }
03379 
03380 /*! \brief returns true if 'name' (with optional trailing whitespace)
03381  * matches the sip method 'id'.
03382  * Strictly speaking, SIP methods are case SENSITIVE, but we do
03383  * a case-insensitive comparison to be more tolerant.
03384  * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
03385  */
03386 static int method_match(enum sipmethod id, const char *name)
03387 {
03388    int len = strlen(sip_methods[id].text);
03389    int l_name = name ? strlen(name) : 0;
03390    /* true if the string is long enough, and ends with whitespace, and matches */
03391    return (l_name >= len && name[len] < 33 &&
03392       !strncasecmp(sip_methods[id].text, name, len));
03393 }
03394 
03395 /*! \brief  find_sip_method: Find SIP method from header */
03396 static int find_sip_method(const char *msg)
03397 {
03398    int i, res = 0;
03399    
03400    if (ast_strlen_zero(msg))
03401       return 0;
03402    for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
03403       if (method_match(i, msg))
03404          res = sip_methods[i].id;
03405    }
03406    return res;
03407 }
03408 
03409 /*! \brief Parse supported header in incoming packet */
03410 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
03411 {
03412    char *next, *sep;
03413    char *temp;
03414    unsigned int profile = 0;
03415    int i, found;
03416 
03417    if (ast_strlen_zero(supported) )
03418       return 0;
03419    temp = ast_strdupa(supported);
03420 
03421    if (sipdebug)
03422       ast_debug(3, "Begin: parsing SIP \"Supported: %s\"\n", supported);
03423 
03424    for (next = temp; next; next = sep) {
03425       found = FALSE;
03426       if ( (sep = strchr(next, ',')) != NULL)
03427          *sep++ = '\0';
03428       next = ast_skip_blanks(next);
03429       if (sipdebug)
03430          ast_debug(3, "Found SIP option: -%s-\n", next);
03431       for (i = 0; i < ARRAY_LEN(sip_options); i++) {
03432          if (!strcasecmp(next, sip_options[i].text)) {
03433             profile |= sip_options[i].id;
03434             found = TRUE;
03435             if (sipdebug)
03436                ast_debug(3, "Matched SIP option: %s\n", next);
03437             break;
03438          }
03439       }
03440 
03441       /* This function is used to parse both Suported: and Require: headers.
03442       Let the caller of this function know that an unknown option tag was 
03443       encountered, so that if the UAC requires it then the request can be 
03444       rejected with a 420 response. */
03445       if (!found)
03446          profile |= SIP_OPT_UNKNOWN;
03447 
03448       if (!found && sipdebug) {
03449          if (!strncasecmp(next, "x-", 2))
03450             ast_debug(3, "Found private SIP option, not supported: %s\n", next);
03451          else
03452             ast_debug(3, "Found no match for SIP option: %s (Please file bug report!)\n", next);
03453       }
03454    }
03455 
03456    if (pvt)
03457       pvt->sipoptions = profile;
03458    return profile;
03459 }
03460 
03461 /*! \brief See if we pass debug IP filter */
03462 static inline int sip_debug_test_addr(const struct sockaddr_in *addr) 
03463 {
03464    if (!sipdebug)
03465       return 0;
03466    if (debugaddr.sin_addr.s_addr) {
03467       if (((ntohs(debugaddr.sin_port) != 0)
03468          && (debugaddr.sin_port != addr->sin_port))
03469          || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
03470          return 0;
03471    }
03472    return 1;
03473 }
03474 
03475 /*! \brief The real destination address for a write */
03476 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
03477 {
03478    if (p->outboundproxy)
03479       return &p->outboundproxy->ip;
03480 
03481    return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
03482 }
03483 
03484 /*! \brief Display SIP nat mode */
03485 static const char *sip_nat_mode(const struct sip_pvt *p)
03486 {
03487    return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
03488 }
03489 
03490 /*! \brief Test PVT for debugging output */
03491 static inline int sip_debug_test_pvt(struct sip_pvt *p) 
03492 {
03493    if (!sipdebug)
03494       return 0;
03495    return sip_debug_test_addr(sip_real_dst(p));
03496 }
03497 
03498 /*! \brief Return int representing a bit field of transport types found in const char *transport */
03499 static int get_transport_str2enum(const char *transport)
03500 {
03501    int res = 0;
03502 
03503    if (ast_strlen_zero(transport)) {
03504       return res;
03505    }
03506 
03507    if (!strcasecmp(transport, "udp")) {
03508       res |= SIP_TRANSPORT_UDP;
03509    }
03510    if (!strcasecmp(transport, "tcp")) {
03511       res |= SIP_TRANSPORT_TCP;
03512    }
03513    if (!strcasecmp(transport, "tls")) {
03514       res |= SIP_TRANSPORT_TLS;
03515    }
03516 
03517    return res;
03518 }
03519 
03520 /*! \brief Return configuration of transports for a device */
03521 static inline const char *get_transport_list(unsigned int transports) {
03522    switch (transports) {
03523       case SIP_TRANSPORT_UDP:
03524          return "UDP";
03525       case SIP_TRANSPORT_TCP:
03526          return "TCP";
03527       case SIP_TRANSPORT_TLS:
03528          return "TLS";
03529       case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
03530          return "TCP,UDP";
03531       case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
03532          return "TLS,UDP";
03533       case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
03534          return "TLS,TCP";
03535       default:
03536          return transports ? 
03537             "TLS,TCP,UDP" : "UNKNOWN"; 
03538    }
03539 }
03540 
03541 /*! \brief Return transport as string */
03542 static inline const char *get_transport(enum sip_transport t)
03543 {
03544    switch (t) {
03545    case SIP_TRANSPORT_UDP:
03546       return "UDP";
03547    case SIP_TRANSPORT_TCP:
03548       return "TCP";
03549    case SIP_TRANSPORT_TLS:
03550       return "TLS";
03551    }
03552 
03553    return "UNKNOWN";
03554 }
03555 
03556 /*! \brief Return protocol string for srv dns query */
03557 static inline const char *get_srv_protocol(enum sip_transport t)
03558 {
03559    switch (t) {
03560    case SIP_TRANSPORT_UDP:
03561       return "udp";
03562    case SIP_TRANSPORT_TLS:
03563    case SIP_TRANSPORT_TCP:
03564       return "tcp";
03565    }
03566 
03567    return "udp";
03568 }
03569 
03570 /*! \brief Return service string for srv dns query */
03571 static inline const char *get_srv_service(enum sip_transport t)
03572 {
03573    switch (t) {
03574    case SIP_TRANSPORT_TCP:
03575    case SIP_TRANSPORT_UDP:
03576       return "sip";
03577    case SIP_TRANSPORT_TLS:
03578       return "sips";
03579    }
03580    return "sip";
03581 }
03582 
03583 /*! \brief Return transport of dialog.
03584    \note this is based on a false assumption. We don't always use the
03585    outbound proxy for all requests in a dialog. It depends on the
03586    "force" parameter. The FIRST request is always sent to the ob proxy.
03587    \todo Fix this function to work correctly
03588 */
03589 static inline const char *get_transport_pvt(struct sip_pvt *p)
03590 {
03591    if (p->outboundproxy && p->outboundproxy->transport) {
03592       set_socket_transport(&p->socket, p->outboundproxy->transport);
03593    }
03594 
03595    return get_transport(p->socket.type);
03596 }
03597 
03598 /*! \brief Transmit SIP message 
03599    Sends a SIP request or response on a given socket (in the pvt)
03600    Called by retrans_pkt, send_request, send_response and 
03601    __sip_reliable_xmit
03602 */
03603 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len)
03604 {
03605    int res = 0;
03606    const struct sockaddr_in *dst = sip_real_dst(p);
03607 
03608    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));
03609 
03610    if (sip_prepare_socket(p) < 0)
03611       return XMIT_ERROR;
03612 
03613    if (p->socket.type == SIP_TRANSPORT_UDP) {
03614       res = sendto(p->socket.fd, data->str, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
03615    } else if (p->socket.tcptls_session) {
03616       res = sip_tcptls_write(p->socket.tcptls_session, data->str, len);
03617    } else {
03618       ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
03619       return XMIT_ERROR;
03620    }
03621 
03622    if (res == -1) {
03623       switch (errno) {
03624       case EBADF:       /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
03625       case EHOSTUNREACH:   /* Host can't be reached */
03626       case ENETDOWN:       /* Inteface down */
03627       case ENETUNREACH: /* Network failure */
03628       case ECONNREFUSED:      /* ICMP port unreachable */ 
03629          res = XMIT_ERROR; /* Don't bother with trying to transmit again */
03630       }
03631    }
03632    if (res != len)
03633       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));
03634 
03635    return res;
03636 }
03637 
03638 /*! \brief Build a Via header for a request */
03639 static void build_via(struct sip_pvt *p)
03640 {
03641    /* Work around buggy UNIDEN UIP200 firmware */
03642    const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
03643 
03644    /* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
03645    snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s:%d;branch=z9hG4bK%08x%s",
03646        get_transport_pvt(p),
03647        ast_inet_ntoa(p->ourip.sin_addr),
03648        ntohs(p->ourip.sin_port), (int) p->branch, rport);
03649 }
03650 
03651 /*! \brief NAT fix - decide which IP address to use for Asterisk server?
03652  *
03653  * Using the localaddr structure built up with localnet statements in sip.conf
03654  * apply it to their address to see if we need to substitute our
03655  * externip or can get away with our internal bindaddr
03656  * 'us' is always overwritten.
03657  */
03658 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p)
03659 {
03660    struct sockaddr_in theirs;
03661    /* Set want_remap to non-zero if we want to remap 'us' to an externally
03662     * reachable IP address and port. This is done if:
03663     * 1. we have a localaddr list (containing 'internal' addresses marked
03664     *    as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
03665     *    and AST_SENSE_ALLOW on 'external' ones);
03666     * 2. either stunaddr or externip is set, so we know what to use as the
03667     *    externally visible address;
03668     * 3. the remote address, 'them', is external;
03669     * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
03670     *    when passed to ast_apply_ha() so it does need to be remapped.
03671     *    This fourth condition is checked later.
03672     */
03673    int want_remap;
03674 
03675    *us = internip;      /* starting guess for the internal address */
03676    /* now ask the system what would it use to talk to 'them' */
03677    ast_ouraddrfor(them, &us->sin_addr);
03678    theirs.sin_addr = *them;
03679 
03680    want_remap = localaddr &&
03681       (externip.sin_addr.s_addr || stunaddr.sin_addr.s_addr) &&
03682       ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
03683 
03684    if (want_remap &&
03685        (!sip_cfg.matchexterniplocally || !ast_apply_ha(localaddr, us)) ) {
03686       /* if we used externhost or stun, see if it is time to refresh the info */
03687       if (externexpire && time(NULL) >= externexpire) {
03688          if (stunaddr.sin_addr.s_addr) {
03689             ast_stun_request(sipsock, &stunaddr, NULL, &externip);
03690          } else {
03691             if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
03692                ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
03693          }
03694          externexpire = time(NULL) + externrefresh;
03695       }
03696       if (externip.sin_addr.s_addr)
03697          *us = externip;
03698       else
03699          ast_log(LOG_WARNING, "stun failed\n");
03700       ast_debug(1, "Target address %s is not local, substituting externip\n", 
03701          ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
03702    } else if (p) {
03703       /* no remapping, but we bind to a specific address, so use it. */
03704       switch (p->socket.type) {
03705       case SIP_TRANSPORT_TCP:
03706          if (sip_tcp_desc.local_address.sin_addr.s_addr) {
03707             *us = sip_tcp_desc.local_address;
03708          } else {
03709             us->sin_port = sip_tcp_desc.local_address.sin_port;
03710          }
03711          break;
03712       case SIP_TRANSPORT_TLS:
03713          if (sip_tls_desc.local_address.sin_addr.s_addr) {
03714             *us = sip_tls_desc.local_address;
03715          } else {
03716             us->sin_port = sip_tls_desc.local_address.sin_port;
03717          }
03718             break;
03719       case SIP_TRANSPORT_UDP:
03720          /* fall through on purpose */
03721       default:
03722          if (bindaddr.sin_addr.s_addr) {
03723             *us = bindaddr;
03724          }
03725       }
03726    } else if (bindaddr.sin_addr.s_addr) {
03727       *us = bindaddr;
03728    }
03729    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));
03730 }
03731 
03732 /*! \brief Append to SIP dialog history with arg list  */
03733 static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
03734 {
03735    char buf[80], *c = buf; /* max history length */
03736    struct sip_history *hist;
03737    int l;
03738 
03739    vsnprintf(buf, sizeof(buf), fmt, ap);
03740    strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
03741    l = strlen(buf) + 1;
03742    if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
03743       return;
03744    if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
03745       ast_free(hist);
03746       return;
03747    }
03748    memcpy(hist->event, buf, l);
03749    if (p->history_entries == MAX_HISTORY_ENTRIES) {
03750       struct sip_history *oldest;
03751       oldest = AST_LIST_REMOVE_HEAD(p->history, list);
03752       p->history_entries--;
03753       ast_free(oldest);
03754    }
03755    AST_LIST_INSERT_TAIL(p->history, hist, list);
03756    p->history_entries++;
03757 }
03758 
03759 /*! \brief Append to SIP dialog history with arg list  */
03760 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03761 {
03762    va_list ap;
03763 
03764    if (!p)
03765       return;
03766 
03767    if (!p->do_history && !recordhistory && !dumphistory)
03768       return;
03769 
03770    va_start(ap, fmt);
03771    append_history_va(p, fmt, ap);
03772    va_end(ap);
03773 
03774    return;
03775 }
03776 
03777 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
03778 static int retrans_pkt(const void *data)
03779 {
03780    struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
03781    int reschedule = DEFAULT_RETRANS;
03782    int xmitres = 0;
03783    
03784    /* Lock channel PVT */
03785    sip_pvt_lock(pkt->owner);
03786 
03787    if (pkt->retrans < MAX_RETRANS) {
03788       pkt->retrans++;
03789       if (!pkt->timer_t1) {   /* Re-schedule using timer_a and timer_t1 */
03790          if (sipdebug)
03791             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);
03792       } else {
03793          int siptimer_a;
03794 
03795          if (sipdebug)
03796             ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
03797          if (!pkt->timer_a)
03798             pkt->timer_a = 2 ;
03799          else
03800             pkt->timer_a = 2 * pkt->timer_a;
03801  
03802          /* For non-invites, a maximum of 4 secs */
03803          siptimer_a = pkt->timer_t1 * pkt->timer_a;   /* Double each time */
03804          if (pkt->method != SIP_INVITE && siptimer_a > 4000)
03805             siptimer_a = 4000;
03806       
03807          /* Reschedule re-transmit */
03808          reschedule = siptimer_a;
03809          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);
03810       } 
03811 
03812       if (sip_debug_test_pvt(pkt->owner)) {
03813          const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
03814          ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
03815             pkt->retrans, sip_nat_mode(pkt->owner),
03816             ast_inet_ntoa(dst->sin_addr),
03817             ntohs(dst->sin_port), pkt->data->str);
03818       }
03819 
03820       append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
03821       xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
03822       sip_pvt_unlock(pkt->owner);
03823       if (xmitres == XMIT_ERROR)
03824          ast_log(LOG_WARNING, "Network error on retransmit in dialog %s\n", pkt->owner->callid);
03825       else 
03826          return  reschedule;
03827    } 
03828    /* Too many retries */
03829    if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
03830       if (pkt->is_fatal || sipdebug)   /* Tell us if it's critical or if we're debugging */
03831          ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s) -- See doc/sip-retransmit.txt.\n",
03832             pkt->owner->callid, pkt->seqno,
03833             pkt->is_fatal ? "Critical" : "Non-critical", pkt->is_resp ? "Response" : "Request");
03834    } else if (pkt->method == SIP_OPTIONS && sipdebug) {
03835          ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s)  -- See doc/sip-retransmit.txt.\n", pkt->owner->callid);
03836 
03837    } 
03838    if (xmitres == XMIT_ERROR) {
03839       ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
03840       append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03841    } else 
03842       append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03843       
03844    pkt->retransid = -1;
03845 
03846    if (pkt->is_fatal) {
03847       while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
03848          sip_pvt_unlock(pkt->owner);   /* SIP_PVT, not channel */
03849          usleep(1);
03850          sip_pvt_lock(pkt->owner);
03851       }
03852 
03853       if (pkt->owner->owner && !pkt->owner->owner->hangupcause) 
03854          pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
03855       
03856       if (pkt->owner->owner) {
03857          sip_alreadygone(pkt->owner);
03858          ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet (see doc/sip-retransmit.txt).\n", pkt->owner->callid);
03859          ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_PROTOCOL_ERROR);
03860          ast_channel_unlock(pkt->owner->owner);
03861       } else {
03862          /* If no channel owner, destroy now */
03863 
03864          /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
03865          if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
03866             pvt_set_needdestroy(pkt->owner, "no response to critical packet");
03867             sip_alreadygone(pkt->owner);
03868             append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
03869          }
03870       }
03871    }
03872 
03873    if (pkt->method == SIP_BYE) {
03874       /* We're not getting answers on SIP BYE's.  Tear down the call anyway. */
03875       if (pkt->owner->owner) 
03876          ast_channel_unlock(pkt->owner->owner);
03877       append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
03878       pvt_set_needdestroy(pkt->owner, "no response to BYE");
03879    }
03880 
03881    /* Remove the packet */
03882    for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
03883       if (cur == pkt) {
03884          UNLINK(cur, pkt->owner->packets, prev);
03885          sip_pvt_unlock(pkt->owner);
03886          if (pkt->owner)
03887             pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03888          if (pkt->data)
03889             ast_free(pkt->data);
03890          pkt->data = NULL;
03891          ast_free(pkt);
03892          return 0;
03893       }
03894    }
03895    /* error case */
03896    ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
03897    sip_pvt_unlock(pkt->owner);
03898    return 0;
03899 }
03900 
03901 /*! \brief Transmit packet with retransmits 
03902    \return 0 on success, -1 on failure to allocate packet 
03903 */
03904 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)
03905 {
03906    struct sip_pkt *pkt = NULL;
03907    int siptimer_a = DEFAULT_RETRANS;
03908    int xmitres = 0;
03909    int respid;
03910 
03911    if (sipmethod == SIP_INVITE) {
03912       /* Note this is a pending invite */
03913       p->pendinginvite = seqno;
03914    }
03915 
03916    /* If the transport is something reliable (TCP or TLS) then don't really send this reliably */
03917    /* I removed the code from retrans_pkt that does the same thing so it doesn't get loaded into the scheduler */
03918    /*! \todo According to the RFC some packets need to be retransmitted even if its TCP, so this needs to get revisited */
03919    if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
03920       xmitres = __sip_xmit(p, data, len); /* Send packet */
03921       if (xmitres == XMIT_ERROR) {  /* Serious network trouble, no need to try again */
03922          append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
03923          return AST_FAILURE;
03924       } else {
03925          return AST_SUCCESS;
03926       }
03927    }
03928 
03929    if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
03930       return AST_FAILURE;
03931    /* copy data, add a terminator and save length */
03932    if (!(pkt->data = ast_str_create(len))) {
03933       ast_free(pkt);
03934       return AST_FAILURE;
03935    }
03936    ast_str_set(&pkt->data, 0, "%s%s", data->str, "\0");
03937    pkt->packetlen = len;
03938    /* copy other parameters from the caller */
03939    pkt->method = sipmethod;
03940    pkt->seqno = seqno;
03941    pkt->is_resp = resp;
03942    pkt->is_fatal = fatal;
03943    pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
03944    pkt->next = p->packets;
03945    p->packets = pkt; /* Add it to the queue */
03946    if (resp) {
03947       /* Parse out the response code */
03948       if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
03949          pkt->response_code = respid;
03950       }
03951    }
03952    pkt->timer_t1 = p->timer_t1;  /* Set SIP timer T1 */
03953    pkt->retransid = -1;
03954    if (pkt->timer_t1)
03955       siptimer_a = pkt->timer_t1 * 2;
03956 
03957    /* Schedule retransmission */
03958    AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
03959    if (sipdebug)
03960       ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id  #%d\n", pkt->retransid);
03961 
03962    xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);   /* Send packet */
03963 
03964    if (xmitres == XMIT_ERROR) {  /* Serious network trouble, no need to try again */
03965       append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03966       ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
03967       AST_SCHED_DEL(sched, pkt->retransid);
03968       p->packets = pkt->next;
03969       pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03970       ast_free(pkt->data);
03971       ast_free(pkt);
03972       return AST_FAILURE;
03973    } else {
03974       return AST_SUCCESS;
03975    }
03976 }
03977 
03978 /*! \brief Kill a SIP dialog (called only by the scheduler)
03979  * The scheduler has a reference to this dialog when p->autokillid != -1,
03980  * and we are called using that reference. So if the event is not
03981  * rescheduled, we need to call dialog_unref().
03982  */
03983 static int __sip_autodestruct(const void *data)
03984 {
03985    struct sip_pvt *p = (struct sip_pvt *)data;
03986 
03987    /* If this is a subscription, tell the phone that we got a timeout */
03988    if (p->subscribed) {
03989       transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);  /* Send last notification */
03990       p->subscribed = NONE;
03991       append_history(p, "Subscribestatus", "timeout");
03992       ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
03993       return 10000;  /* Reschedule this destruction so that we know that it's gone */
03994    }
03995 
03996    /* If there are packets still waiting for delivery, delay the destruction */
03997    if (p->packets) {
03998       if (!p->needdestroy) {
03999          char method_str[31];
04000          ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
04001          append_history(p, "ReliableXmit", "timeout");
04002          if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
04003             if (method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
04004                pvt_set_needdestroy(p, "autodestruct");
04005             }
04006          }
04007          return 10000;
04008       } else {
04009          /* They've had their chance to respond. Time to bail */
04010          __sip_pretend_ack(p);
04011       }
04012    }
04013 
04014    if (p->subscribed == MWI_NOTIFICATION)
04015       if (p->relatedpeer)
04016          p->relatedpeer = unref_peer(p->relatedpeer, "__sip_autodestruct: unref peer p->relatedpeer");   /* Remove link to peer. If it's realtime, make sure it's gone from memory) */
04017 
04018    /* Reset schedule ID */
04019    p->autokillid = -1;
04020 
04021    if (p->owner) {
04022       ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
04023       ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
04024    } else if (p->refer && !p->alreadygone) {
04025       ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
04026       transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
04027       append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
04028       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
04029    } else {
04030       append_history(p, "AutoDestroy", "%s", p->callid);
04031       ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
04032       dialog_unlink_all(p, TRUE, TRUE); /* once it's unlinked and unrefd everywhere, it'll be freed automagically */
04033       /* dialog_unref(p, "unref dialog-- no other matching conditions"); -- unlink all now should finish off the dialog's references and free it. */
04034       /* sip_destroy(p); */      /* Go ahead and destroy dialog. All attempts to recover is done */
04035       /* sip_destroy also absorbs the reference */
04036    }
04037    dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
04038    return 0;
04039 }
04040 
04041 /*! \brief Schedule destruction of SIP dialog */
04042 static void sip_scheddestroy(struct sip_pvt *p, int ms)
04043 {
04044    if (ms < 0) {
04045       if (p->timer_t1 == 0) {
04046          p->timer_t1 = global_t1;   /* Set timer T1 if not set (RFC 3261) */
04047          p->timer_b = global_timer_b;  /* Set timer B if not set (RFC 3261) */
04048       }
04049       ms = p->timer_t1 * 64;
04050    }
04051    if (sip_debug_test_pvt(p))
04052       ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
04053    if (sip_cancel_destroy(p))
04054       ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
04055 
04056    if (p->do_history)
04057       append_history(p, "SchedDestroy", "%d ms", ms);
04058    p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
04059 
04060    if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0)
04061       stop_session_timer(p);
04062 }
04063 
04064 /*! \brief Cancel destruction of SIP dialog.
04065  * Be careful as this also absorbs the reference - if you call it
04066  * from within the scheduler, this might be the last reference.
04067  */
04068 static int sip_cancel_destroy(struct sip_pvt *p)
04069 {
04070    int res = 0;
04071    if (p->autokillid > -1) {
04072       int res3;
04073 
04074       if (!(res3 = ast_sched_del(sched, p->autokillid))) {
04075          append_history(p, "CancelDestroy", "");
04076          p->autokillid = -1;
04077          dialog_unref(p, "dialog unrefd because autokillid is de-sched'd");
04078       }
04079    }
04080    return res;
04081 }
04082 
04083 /*! \brief Acknowledges receipt of a packet and stops retransmission 
04084  * called with p locked*/
04085 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
04086 {
04087    struct sip_pkt *cur, *prev = NULL;
04088    const char *msg = "Not Found";   /* used only for debugging */
04089    int res = FALSE;
04090 
04091    /* If we have an outbound proxy for this dialog, then delete it now since
04092      the rest of the requests in this dialog needs to follow the routing.
04093      If obforcing is set, we will keep the outbound proxy during the whole
04094      dialog, regardless of what the SIP rfc says
04095    */
04096    if (p->outboundproxy && !p->outboundproxy->force){
04097       ref_proxy(p, NULL);
04098    }
04099 
04100    for (cur = p->packets; cur; prev = cur, cur = cur->next) {
04101       if (cur->seqno != seqno || cur->is_resp != resp)
04102          continue;
04103       if (cur->is_resp || cur->method == sipmethod) {
04104          res = TRUE;
04105          msg = "Found";
04106          if (!resp && (seqno == p->pendinginvite)) {
04107             ast_debug(1, "Acked pending invite %d\n", p->pendinginvite);
04108             p->pendinginvite = 0;
04109          }
04110          if (cur->retransid > -1) {
04111             if (sipdebug)
04112                ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
04113          }
04114          /* This odd section is designed to thwart a 
04115           * race condition in the packet scheduler. There are
04116           * two conditions under which deleting the packet from the
04117           * scheduler can fail.
04118           *
04119           * 1. The packet has been removed from the scheduler because retransmission
04120           * is being attempted. The problem is that if the packet is currently attempting
04121           * retransmission and we are at this point in the code, then that MUST mean
04122           * that retrans_pkt is waiting on p's lock. Therefore we will relinquish the
04123           * lock temporarily to allow retransmission.
04124           *
04125           * 2. The packet has reached its maximum number of retransmissions and has
04126           * been permanently removed from the packet scheduler. If this is the case, then
04127           * the packet's retransid will be set to -1. The atomicity of the setting and checking
04128           * of the retransid to -1 is ensured since in both cases p's lock is held.
04129           */
04130          while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
04131             sip_pvt_unlock(p);
04132             usleep(1);
04133             sip_pvt_lock(p);
04134          }
04135          UNLINK(cur, p->packets, prev);
04136          dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
04137          if (cur->data)
04138             ast_free(cur->data);
04139          ast_free(cur);
04140          break;
04141       }
04142    }
04143    ast_debug(1, "Stopping retransmission on '%s' of %s %d: Match %s\n",
04144       p->callid, resp ? "Response" : "Request", seqno, msg);
04145    return res;
04146 }
04147 
04148 /*! \brief Pretend to ack all packets
04149  * called with p locked */
04150 static void __sip_pretend_ack(struct sip_pvt *p)
04151 {
04152    struct sip_pkt *cur = NULL;
04153 
04154    while (p->packets) {
04155       int method;
04156       if (cur == p->packets) {
04157          ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
04158          return;
04159       }
04160       cur = p->packets;
04161       method = (cur->method) ? cur->method : find_sip_method(cur->data->str);
04162       __sip_ack(p, cur->seqno, cur->is_resp, method);
04163    }
04164 }
04165 
04166 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
04167 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
04168 {
04169    struct sip_pkt *cur;
04170    int res = FALSE;
04171 
04172    for (cur = p->packets; cur; cur = cur->next) {
04173       if (cur->seqno == seqno && cur->is_resp == resp &&
04174          (cur->is_resp || method_match(sipmethod, cur->data->str))) {
04175          /* this is our baby */
04176          if (cur->retransid > -1) {
04177             if (sipdebug)
04178                ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
04179          }
04180          AST_SCHED_DEL(sched, cur->retransid);
04181          res = TRUE;
04182          break;
04183       }
04184    }
04185    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");
04186    return res;
04187 }
04188 
04189 
04190 /*! \brief Copy SIP request, parse it */
04191 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
04192 {
04193    copy_request(dst, src);
04194    parse_request(dst);
04195 }
04196 
04197 /*! \brief add a blank line if no body */
04198 static void add_blank(struct sip_request *req)
04199 {
04200    if (!req->lines) {
04201       /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
04202       ast_str_append(&req->data, 0, "\r\n");
04203       req->len = ast_str_strlen(req->data);
04204    }
04205 }
04206 
04207 static int send_provisional_keepalive_full(struct sip_pvt *pvt, int with_sdp)
04208 {
04209    const char *msg = NULL;
04210 
04211    if (!pvt->last_provisional || !strncasecmp(pvt->last_provisional, "100", 3)) {
04212       msg = "183 Session Progress";
04213    }
04214 
04215    if (pvt->invitestate < INV_COMPLETED) {
04216       if (with_sdp) {
04217          transmit_response_with_sdp(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq, XMIT_UNRELIABLE, FALSE);
04218       } else {
04219          transmit_response(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq);
04220       }
04221       return PROVIS_KEEPALIVE_TIMEOUT;
04222    }
04223 
04224    return 0;
04225 }
04226 
04227 static int send_provisional_keepalive(const void *data) {
04228    struct sip_pvt *pvt = (struct sip_pvt *) data;
04229 
04230    return send_provisional_keepalive_full(pvt, 0);
04231 }
04232 
04233 static int send_provisional_keepalive_with_sdp(const void *data) {
04234    struct sip_pvt *pvt = (void *)data;
04235 
04236    return send_provisional_keepalive_full(pvt, 1);
04237 }
04238 
04239 static void update_provisional_keepalive(struct sip_pvt *pvt, int with_sdp)
04240 {
04241    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"));
04242 
04243    pvt->provisional_keepalive_sched_id = ast_sched_add(sched, PROVIS_KEEPALIVE_TIMEOUT,
04244       with_sdp ? send_provisional_keepalive_with_sdp : send_provisional_keepalive, dialog_ref(pvt, "Increment refcount to pass dialog pointer to sched callback"));
04245 }
04246 
04247 /*! \brief Transmit response on SIP request*/
04248 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
04249 {
04250    int res;
04251 
04252    finalize_content(req);
04253    add_blank(req);
04254    if (sip_debug_test_pvt(p)) {
04255       const struct sockaddr_in *dst = sip_real_dst(p);
04256 
04257       ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
04258          reliable ? "Reliably " : "", sip_nat_mode(p),
04259          ast_inet_ntoa(dst->sin_addr),
04260          ntohs(dst->sin_port), req->data->str);
04261    }
04262    if (p->do_history) {
04263       struct sip_request tmp = { .rlPart1 = 0, };
04264       parse_copy(&tmp, req);
04265       append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), 
04266          (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlPart2) : sip_methods[tmp.method].text);
04267       deinit_req(&tmp);
04268    }
04269 
04270    /* If we are sending a final response to an INVITE, stop retransmitting provisional responses */
04271    if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
04272       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"));
04273    }
04274 
04275    res = (reliable) ?
04276        __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
04277       __sip_xmit(p, req->data, req->len);
04278    deinit_req(req);
04279    if (res > 0)
04280       return 0;
04281    return res;
04282 }
04283 
04284 /*! \brief Send SIP Request to the other part of the dialogue */
04285 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
04286 {
04287    int res;
04288 
04289    /* If we have an outbound proxy, reset peer address 
04290       Only do this once.
04291    */
04292    if (p->outboundproxy) {
04293       p->sa = p->outboundproxy->ip;
04294    }
04295 
04296    finalize_content(req);
04297    add_blank(req);
04298    if (sip_debug_test_pvt(p)) {
04299       if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
04300          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);
04301       else
04302          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);
04303    }
04304    if (p->do_history) {
04305       struct sip_request tmp = { .rlPart1 = 0, };
04306       parse_copy(&tmp, req);
04307       append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
04308       deinit_req(&tmp);
04309    }
04310    res = (reliable) ?
04311       __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
04312       __sip_xmit(p, req->data, req->len);
04313    deinit_req(req);
04314    return res;
04315 }
04316 
04317 /*! \brief Query an option on a SIP dialog */
04318 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
04319 {
04320    int res = -1;
04321    enum ast_t38_state state = T38_STATE_UNAVAILABLE;
04322    struct sip_pvt *p = (struct sip_pvt *) chan->tech_pvt;
04323 
04324    switch (option) {
04325    case AST_OPTION_T38_STATE:
04326       /* Make sure we got an ast_t38_state enum passed in */
04327       if (*datalen != sizeof(enum ast_t38_state)) {
04328          ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
04329          return -1;
04330       }
04331 
04332       sip_pvt_lock(p);
04333 
04334       /* 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 */
04335       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
04336          switch (p->t38.state) {
04337          case T38_LOCAL_REINVITE:
04338          case T38_PEER_REINVITE:
04339             state = T38_STATE_NEGOTIATING;
04340             break;
04341          case T38_ENABLED:
04342             state = T38_STATE_NEGOTIATED;
04343             break;
04344          default:
04345             state = T38_STATE_UNKNOWN;
04346          }
04347       }
04348 
04349       sip_pvt_unlock(p);
04350 
04351       *((enum ast_t38_state *) data) = state;
04352       res = 0;
04353 
04354       break;
04355    default:
04356       break;
04357    }
04358 
04359    return res;
04360 }
04361 
04362 /*! \brief Locate closing quote in a string, skipping escaped quotes.
04363  * optionally with a limit on the search.
04364  * start must be past the first quote.
04365  */
04366 static const char *find_closing_quote(const char *start, const char *lim)
04367 {
04368    char last_char = '\0';
04369    const char *s;
04370    for (s = start; *s && s != lim; last_char = *s++) {
04371       if (*s == '"' && last_char != '\\')
04372          break;
04373    }
04374    return s;
04375 }
04376 
04377 /*! \brief Pick out text in brackets from character string
04378    \return pointer to terminated stripped string
04379    \param tmp input string that will be modified
04380    Examples:
04381 \verbatim
04382    "foo" <bar> valid input, returns bar
04383    foo      returns the whole string
04384    < "foo ... >   returns the string between brackets
04385    < "foo...   bogus (missing closing bracket), returns the whole string
04386          XXX maybe should still skip the opening bracket
04387 \endverbatim
04388  */
04389 static char *get_in_brackets(char *tmp)
04390 {
04391    const char *parse = tmp;
04392    char *first_bracket;
04393 
04394    /*
04395     * Skip any quoted text until we find the part in brackets.
04396    * On any error give up and return the full string.
04397    */
04398    while ( (first_bracket = strchr(parse, '<')) ) {
04399       char *first_quote = strchr(parse, '"');
04400 
04401       if (!first_quote || first_quote > first_bracket)
04402          break; /* no need to look at quoted part */
04403       /* the bracket is within quotes, so ignore it */
04404       parse = find_closing_quote(first_quote + 1, NULL);
04405       if (!*parse) { /* not found, return full string ? */
04406          /* XXX or be robust and return in-bracket part ? */
04407          ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
04408          break;
04409       }
04410       parse++;
04411    }
04412    if (first_bracket) {
04413       char *second_bracket = strchr(first_bracket + 1, '>');
04414       if (second_bracket) {
04415          *second_bracket = '\0';
04416          tmp = first_bracket + 1;
04417       } else {
04418          ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
04419       }
04420    }
04421    
04422    return tmp;
04423 }
04424 
04425 /*! \brief * parses a URI in its components.
04426  *
04427  * \note 
04428  * - If scheme is specified, drop it from the top.
04429  * - If a component is not requested, do not split around it.
04430  * - Multiple scheme's can be specified ',' delimited. ex: "sip:,sips:"
04431  *
04432  * This means that if we don't have domain, we cannot split
04433  * name:pass and domain:port.
04434  * It is safe to call with ret_name, pass, domain, port
04435  * pointing all to the same place.
04436  * Init pointers to empty string so we never get NULL dereferencing.
04437  * Overwrites the string.
04438  * return 0 on success, other values on error.
04439  * \verbatim 
04440  * general form we are expecting is sip[s]:username[:password][;parameter]@host[:port][;...] 
04441  * \endverbatim
04442  * 
04443  */
04444 static int parse_uri(char *uri, const char *scheme,
04445    char **ret_name, char **pass, char **domain, char **port, char **options, char **transport)
04446 {
04447    char *name = NULL;
04448    int error = 0;
04449 
04450    /* init field as required */
04451    if (pass)
04452       *pass = "";
04453    if (port)
04454       *port = "";
04455    if (scheme) {
04456       int l;
04457       char *scheme2 = ast_strdupa(scheme);
04458       char *cur = strsep(&scheme2, ",");
04459       for (; !ast_strlen_zero(cur); cur = strsep(&scheme2, ",")) {
04460          l = strlen(cur);
04461          if (!strncasecmp(uri, cur, l)) {
04462             uri += l;
04463             break;
04464          }
04465       }
04466       if (ast_strlen_zero(cur)) {
04467          ast_debug(1, "No supported scheme found in '%s' using the scheme[s] %s\n", uri, scheme);
04468          error = -1;
04469       }
04470    }
04471    if (transport) {
04472       char *t, *type = "";
04473       *transport = "";
04474       if ((t = strstr(uri, "transport="))) {
04475          strsep(&t, "=");
04476          if ((type = strsep(&t, ";"))) {
04477             *transport = type;
04478          }
04479       }
04480    }
04481 
04482    if (!domain) {
04483       /* if we don't want to split around domain, keep everything as a name,
04484        * so we need to do nothing here, except remember why.
04485        */
04486    } else {
04487       /* store the result in a temp. variable to avoid it being
04488        * overwritten if arguments point to the same place.
04489        */
04490       char *c, *dom = "";
04491 
04492       if ((c = strchr(uri, '@')) == NULL) {
04493          /* domain-only URI, according to the SIP RFC. */
04494          dom = uri;
04495          name = "";
04496       } else {
04497          *c++ = '\0';
04498          dom = c;
04499          name = uri;
04500       }
04501 
04502       /* Remove options in domain and name */
04503       dom = strsep(&dom, ";");
04504       name = strsep(&name, ";");
04505 
04506       if (port && (c = strchr(dom, ':'))) { /* Remove :port */
04507          *c++ = '\0';
04508          *port = c;
04509       }
04510       if (pass && (c = strchr(name, ':'))) { /* user:password */
04511          *c++ = '\0';
04512          *pass = c;
04513       }
04514       *domain = dom;
04515    }
04516    if (ret_name)  /* same as for domain, store the result only at the end */
04517       *ret_name = name;
04518    if (options)
04519       *options = uri ? uri : "";
04520 
04521    return error;
04522 }
04523 
04524 /*! \brief Send message with Access-URL header, if this is an HTML URL only! */
04525 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
04526 {
04527    struct sip_pvt *p = chan->tech_pvt;
04528 
04529    if (subclass != AST_HTML_URL)
04530       return -1;
04531 
04532    ast_string_field_build(p, url, "<%s>;mode=active", data);
04533 
04534    if (sip_debug_test_pvt(p))
04535       ast_debug(1, "Send URL %s, state = %d!\n", data, chan->_state);
04536 
04537    switch (chan->_state) {
04538    case AST_STATE_RING:
04539       transmit_response(p, "100 Trying", &p->initreq);
04540       break;
04541    case AST_STATE_RINGING:
04542       transmit_response(p, "180 Ringing", &p->initreq);
04543       break;
04544    case AST_STATE_UP:
04545       if (!p->pendinginvite) {      /* We are up, and have no outstanding invite */
04546          transmit_reinvite_with_sdp(p, FALSE, FALSE);
04547       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
04548          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);   
04549       }  
04550       break;
04551    default:
04552       ast_log(LOG_WARNING, "Don't know how to send URI when state is %d!\n", chan->_state);
04553    }
04554 
04555    return 0;
04556 }
04557 
04558 /*! \brief Deliver SIP call ID for the call */
04559 static const char *sip_get_callid(struct ast_channel *chan)
04560 {
04561    return chan->tech_pvt ? ((struct sip_pvt *) chan->tech_pvt)->callid : "";
04562 }
04563 
04564 /*! \brief Send SIP MESSAGE text within a call
04565    Called from PBX core sendtext() application */
04566 static int sip_sendtext(struct ast_channel *ast, const char *text)
04567 {
04568    struct sip_pvt *p = ast->tech_pvt;
04569    int debug = sip_debug_test_pvt(p);
04570 
04571    if (debug)
04572       ast_verbose("Sending text %s on %s\n", text, ast->name);
04573    if (!p)
04574       return -1;
04575    /* NOT ast_strlen_zero, because a zero-length message is specifically
04576     * allowed by RFC 3428 (See section 10, Examples) */
04577    if (!text)
04578       return 0;
04579    if (debug)
04580       ast_verbose("Really sending text %s on %s\n", text, ast->name);
04581    transmit_message_with_text(p, text);
04582    return 0;   
04583 }
04584 
04585 /*! \brief Update peer object in realtime storage 
04586    If the Asterisk system name is set in asterisk.conf, we will use
04587    that name and store that in the "regserver" field in the sippeers
04588    table to facilitate multi-server setups.
04589 */
04590 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)
04591 {
04592    char port[10];
04593    char ipaddr[INET_ADDRSTRLEN];
04594    char regseconds[20];
04595    char *tablename = NULL;
04596    char str_lastms[20];
04597 
04598    const char *sysname = ast_config_AST_SYSTEM_NAME;
04599    char *syslabel = NULL;
04600 
04601    time_t nowtime = time(NULL) + expirey;
04602    const char *fc = fullcontact ? "fullcontact" : NULL;
04603 
04604    int realtimeregs = ast_check_realtime("sipregs");
04605 
04606    tablename = realtimeregs ? "sipregs" : "sippeers";
04607    
04608 
04609    snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
04610    snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);  /* Expiration time */
04611    ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
04612    snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
04613    
04614    if (ast_strlen_zero(sysname)) /* No system name, disable this */
04615       sysname = NULL;
04616    else if (sip_cfg.rtsave_sysname)
04617       syslabel = "regserver";
04618 
04619    if (fc) {
04620       ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04621          "port", port, "regseconds", regseconds,
04622          deprecated_username ? "username" : "defaultuser", defaultuser,
04623          "useragent", useragent, "lastms", str_lastms,
04624          fc, fullcontact, syslabel, sysname, SENTINEL); /* note fc and syslabel _can_ be NULL */
04625    } else {
04626       ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04627          "port", port, "regseconds", regseconds,
04628          "useragent", useragent, "lastms", str_lastms,
04629          deprecated_username ? "username" : "defaultuser", defaultuser,
04630          syslabel, sysname, SENTINEL); /* note syslabel _can_ be NULL */
04631    }
04632 }
04633 
04634 /*! \brief Automatically add peer extension to dial plan */
04635 static void register_peer_exten(struct sip_peer *peer, int onoff)
04636 {
04637    char multi[256];
04638    char *stringp, *ext, *context;
04639    struct pbx_find_info q = { .stacklen = 0 };
04640 
04641    /* XXX note that global_regcontext is both a global 'enable' flag and
04642     * the name of the global regexten context, if not specified
04643     * individually.
04644     */
04645    if (ast_strlen_zero(global_regcontext))
04646       return;
04647 
04648    ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
04649    stringp = multi;
04650    while ((ext = strsep(&stringp, "&"))) {
04651       if ((context = strchr(ext, '@'))) {
04652          *context++ = '\0';   /* split ext@context */
04653          if (!ast_context_find(context)) {
04654             ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
04655             continue;
04656          }
04657       } else {
04658          context = global_regcontext;
04659       }
04660       if (onoff) {
04661          if (!ast_exists_extension(NULL, context, ext, 1, NULL)) {
04662             ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
04663                 ast_strdup(peer->name), ast_free_ptr, "SIP");
04664          }
04665       } else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
04666          ast_context_remove_extension(context, ext, 1, NULL);
04667       }
04668    }
04669 }
04670 
04671 /*! Destroy mailbox subscriptions */
04672 static void destroy_mailbox(struct sip_mailbox *mailbox)
04673 {
04674    if (mailbox->mailbox)
04675       ast_free(mailbox->mailbox);
04676    if (mailbox->context)
04677       ast_free(mailbox->context);
04678    if (mailbox->event_sub)
04679       ast_event_unsubscribe(mailbox->event_sub);
04680    ast_free(mailbox);
04681 }
04682 
04683 /*! Destroy all peer-related mailbox subscriptions */
04684 static void clear_peer_mailboxes(struct sip_peer *peer)
04685 {
04686    struct sip_mailbox *mailbox;
04687 
04688    while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
04689       destroy_mailbox(mailbox);
04690 }
04691 
04692 static void sip_destroy_peer_fn(void *peer)
04693 {
04694    sip_destroy_peer(peer);
04695 }
04696 
04697 /*! \brief Destroy peer object from memory */
04698 static void sip_destroy_peer(struct sip_peer *peer)
04699 {
04700    ast_debug(3, "Destroying SIP peer %s\n", peer->name);
04701    if (peer->outboundproxy)
04702       ao2_ref(peer->outboundproxy, -1);
04703    peer->outboundproxy = NULL;
04704 
04705    /* Delete it, it needs to disappear */
04706    if (peer->call) {
04707       dialog_unlink_all(peer->call, TRUE, TRUE);
04708       peer->call = dialog_unref(peer->call, "peer->call is being unset");
04709    }
04710    
04711 
04712    if (peer->mwipvt) {  /* We have an active subscription, delete it */
04713       dialog_unlink_all(peer->mwipvt, TRUE, TRUE);
04714       peer->mwipvt = dialog_unref(peer->mwipvt, "unreffing peer->mwipvt");
04715    }
04716    
04717    if (peer->chanvars) {
04718       ast_variables_destroy(peer->chanvars);
04719       peer->chanvars = NULL;
04720    }
04721    
04722    register_peer_exten(peer, FALSE);
04723    ast_free_ha(peer->ha);
04724    if (peer->selfdestruct)
04725       ast_atomic_fetchadd_int(&apeerobjs, -1);
04726    else if (peer->is_realtime) {
04727       ast_atomic_fetchadd_int(&rpeerobjs, -1);
04728       ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
04729    } else
04730       ast_atomic_fetchadd_int(&speerobjs, -1);
04731    clear_realm_authentication(peer->auth);
04732    peer->auth = NULL;
04733    if (peer->dnsmgr)
04734       ast_dnsmgr_release(peer->dnsmgr);
04735    clear_peer_mailboxes(peer);
04736 
04737    if (peer->socket.tcptls_session) {
04738       ao2_ref(peer->socket.tcptls_session, -1);
04739       peer->socket.tcptls_session = NULL;
04740    }
04741 
04742    ast_string_field_free_memory(peer);
04743 }
04744 
04745 /*! \brief Update peer data in database (if used) */
04746 static void update_peer(struct sip_peer *p, int expire)
04747 {
04748    int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
04749    if (sip_cfg.peer_rtupdate &&
04750        (p->is_realtime || rtcachefriends)) {
04751       realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, p->useragent, expire, p->deprecated_username, p->lastms);
04752    }
04753 }
04754 
04755 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *cfg)
04756 {
04757    struct ast_variable *var = NULL;
04758    struct ast_flags flags = {0};
04759    char *cat = NULL;
04760    const char *insecure;
04761    while ((cat = ast_category_browse(cfg, cat))) {
04762       insecure = ast_variable_retrieve(cfg, cat, "insecure");
04763       set_insecure_flags(&flags, insecure, -1);
04764       if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
04765          var = ast_category_root(cfg, cat);
04766          break;
04767       }
04768    }
04769    return var;
04770 }
04771 
04772 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername)
04773 {
04774    struct ast_variable *tmp;
04775    for (tmp = var; tmp; tmp = tmp->next) {
04776       if (!newpeername && !strcasecmp(tmp->name, "name"))
04777          newpeername = tmp->value;
04778    }
04779    return newpeername;
04780 }
04781 
04782 /*! \brief  realtime_peer: Get peer from realtime storage
04783  * Checks the "sippeers" realtime family from extconfig.conf 
04784  * Checks the "sipregs" realtime family from extconfig.conf if it's configured.
04785  * This returns a pointer to a peer and because we use build_peer, we can rest
04786  * assured that the refcount is bumped.
04787 */
04788 static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin, int devstate_only)
04789 {
04790    struct sip_peer *peer;
04791    struct ast_variable *var = NULL;
04792    struct ast_variable *varregs = NULL;
04793    struct ast_variable *tmp;
04794    struct ast_config *peerlist = NULL;
04795    char ipaddr[INET_ADDRSTRLEN];
04796    char portstring[6]; /*up to 5 digits plus null terminator*/
04797    char *cat = NULL;
04798    unsigned short portnum;
04799    int realtimeregs = ast_check_realtime("sipregs");
04800 
04801    /* First check on peer name */
04802    if (newpeername) {
04803       if (realtimeregs)
04804          varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04805 
04806       var = ast_load_realtime("sippeers", "name", newpeername, "host", "dynamic", SENTINEL);
04807       if (!var && sin)
04808          var = ast_load_realtime("sippeers", "name", newpeername, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
04809       if (!var) {
04810          var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04811          /*!\note
04812           * If this one loaded something, then we need to ensure that the host
04813           * field matched.  The only reason why we can't have this as a criteria
04814           * is because we only have the IP address and the host field might be
04815           * set as a name (and the reverse PTR might not match).
04816           */
04817          if (var && sin) {
04818             for (tmp = var; tmp; tmp = tmp->next) {
04819                if (!strcasecmp(tmp->name, "host")) {
04820                   struct hostent *hp;
04821                   struct ast_hostent ahp;
04822                   if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
04823                      /* No match */
04824                      ast_variables_destroy(var);
04825                      var = NULL;
04826                   }
04827                   break;
04828                }
04829             }
04830          }
04831       }
04832    }
04833 
04834    if (!var && sin) {   /* Then check on IP address for dynamic peers */
04835       ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
04836       portnum = ntohs(sin->sin_port);
04837       sprintf(portstring, "%u", portnum);
04838       var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, SENTINEL);  /* First check for fixed IP hosts */
04839       if (var) {
04840          if (realtimeregs) {
04841             newpeername = get_name_from_variable(var, newpeername);
04842             varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04843          }
04844       } else {
04845          if (realtimeregs)
04846             varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, "port", portstring, SENTINEL); /* Then check for registered hosts */
04847          else
04848             var = ast_load_realtime("sippeers", "ipaddr", ipaddr, "port", portstring, SENTINEL); /* Then check for registered hosts */
04849          if (varregs) {
04850             newpeername = get_name_from_variable(varregs, newpeername);
04851             var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04852          }
04853       }
04854       if (!var) { /*We couldn't match on ipaddress and port, so we need to check if port is insecure*/
04855          peerlist = ast_load_realtime_multientry("sippeers", "host", ipaddr, SENTINEL);
04856          if (peerlist) {
04857             var = get_insecure_variable_from_config(peerlist);
04858             if(var) {
04859                if (realtimeregs) {
04860                   newpeername = get_name_from_variable(var, newpeername);
04861                   varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04862                }
04863             } else { /*var wasn't found in the list of "hosts", so try "ipaddr"*/
04864                peerlist = NULL;
04865                cat = NULL;
04866                peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, SENTINEL);
04867                if(peerlist) {
04868                   var = get_insecure_variable_from_config(peerlist);
04869                   if(var) {
04870                      if (realtimeregs) {
04871                         newpeername = get_name_from_variable(var, newpeername);
04872                         varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04873                      }
04874                   }
04875                }
04876             }
04877          } else {
04878             if (realtimeregs) {
04879                peerlist = ast_load_realtime_multientry("sipregs", "ipaddr", ipaddr, SENTINEL);
04880                if (peerlist) {
04881                   varregs = get_insecure_variable_from_config(peerlist);
04882                   if (varregs) {
04883                      newpeername = get_name_from_variable(varregs, newpeername);
04884                      var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04885                   }
04886                }
04887             } else {
04888                peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, SENTINEL);
04889                if (peerlist) {
04890                   var = get_insecure_variable_from_config(peerlist);
04891                   if (var) {
04892                      newpeername = get_name_from_variable(var, newpeername);
04893                      varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04894                   }
04895                }
04896             }
04897          }
04898       }
04899    }
04900 
04901    if (!var) {
04902       if (peerlist)
04903          ast_config_destroy(peerlist);
04904       return NULL;
04905    }
04906 
04907    for (tmp = var; tmp; tmp = tmp->next) {
04908       if (!newpeername && !strcasecmp(tmp->name, "name")) {
04909          newpeername = tmp->value;
04910       }
04911    }
04912    
04913    if (!newpeername) {  /* Did not find peer in realtime */
04914       ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", ipaddr);
04915       if(peerlist)
04916          ast_config_destroy(peerlist);
04917       else
04918          ast_variables_destroy(var);
04919       return NULL;
04920    }
04921 
04922 
04923    /* Peer found in realtime, now build it in memory */
04924    peer = build_peer(newpeername, var, varregs, TRUE, devstate_only);
04925    if (!peer) {
04926       if(peerlist)
04927          ast_config_destroy(peerlist);
04928       else {
04929          ast_variables_destroy(var);
04930          ast_variables_destroy(varregs);
04931       }
04932       return NULL;
04933    }
04934 
04935    ast_debug(3, "-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
04936 
04937    if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && !devstate_only) {
04938       /* Cache peer */
04939       ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
04940       if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
04941          AST_SCHED_REPLACE_UNREF(peer->expire, sched, sip_cfg.rtautoclear * 1000, expire_register, peer,
04942                unref_peer(_data, "remove registration ref"),
04943                unref_peer(peer, "remove registration ref"),
04944                ref_peer(peer, "add registration ref"));
04945       }
04946       ao2_t_link(peers, peer, "link peer into peers table");
04947       if (peer->addr.sin_addr.s_addr) {
04948          ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
04949       }
04950    }
04951    peer->is_realtime = 1;
04952    if (peerlist)
04953       ast_config_destroy(peerlist);
04954    else {
04955       ast_variables_destroy(var);
04956       ast_variables_destroy(varregs);
04957    }
04958 
04959    return peer;
04960 }
04961 
04962 /* Function to assist finding peers by name only */
04963 static int find_by_name(void *obj, void *arg, void *data, int flags)
04964 {
04965    struct sip_peer *search = obj, *match = arg;
04966    int *which_objects = data;
04967 
04968    /* Usernames in SIP uri's are case sensitive. Domains are not */
04969    if (strcmp(search->name, match->name)) {
04970       return 0;
04971    }
04972 
04973    switch (*which_objects) {
04974    case FINDUSERS:
04975       if (!(search->type & SIP_TYPE_USER)) {
04976          return 0;
04977       }
04978       break;
04979    case FINDPEERS:
04980       if (!(search->type & SIP_TYPE_PEER)) {
04981          return 0;
04982       }
04983       break;
04984    case FINDALLDEVICES:
04985       break;
04986    }
04987 
04988    return CMP_MATCH | CMP_STOP;
04989 }
04990 
04991 /*! 
04992  * \brief Locate device by name or ip address 
04993  *
04994  * \param which_objects Define which objects should be matched when doing a lookup
04995  *        by name.  Valid options are FINDUSERS, FINDPEERS, or FINDALLDEVICES.
04996  *        Note that this option is not used at all when doing a lookup by IP.
04997  *
04998  * This is used on find matching device on name or ip/port.
04999  * If the device was declared as type=peer, we don't match on peer name on incoming INVITEs.
05000  *
05001  * \note Avoid using this function in new functions if there is a way to avoid it,
05002  * since it might cause a database lookup.
05003  */
05004 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int which_objects, int devstate_only, int transport)
05005 {
05006    struct sip_peer *p = NULL;
05007    struct sip_peer tmp_peer;
05008 
05009    if (peer) {
05010       ast_copy_string(tmp_peer.name, peer, sizeof(tmp_peer.name));
05011       p = ao2_t_callback_data(peers, OBJ_POINTER, find_by_name, &tmp_peer, &which_objects, "ao2_find in peers table");
05012    } else if (sin) { /* search by addr? */
05013       tmp_peer.addr.sin_addr.s_addr = sin->sin_addr.s_addr;
05014       tmp_peer.addr.sin_port = sin->sin_port;
05015       tmp_peer.flags[0].flags = 0;
05016       tmp_peer.transports = transport;
05017       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); */
05018       if (!p) {
05019          ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
05020          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); */
05021          if (p) {
05022             return p;
05023          }
05024       }
05025    }
05026 
05027    if (!p && (realtime || devstate_only)) {
05028       p = realtime_peer(peer, sin, devstate_only);
05029       if (p) {
05030          switch (which_objects) {
05031          case FINDUSERS:
05032             if (!(p->type & SIP_TYPE_USER)) {
05033                unref_peer(p, "Wrong type of realtime SIP endpoint");
05034                return NULL;
05035             }
05036             break;
05037          case FINDPEERS:
05038             if (!(p->type & SIP_TYPE_PEER)) {
05039                unref_peer(p, "Wrong type of realtime SIP endpoint");
05040                return NULL;
05041             }
05042             break;
05043          case FINDALLDEVICES:
05044             break;
05045          }
05046       }
05047    }
05048 
05049    return p;
05050 }
05051 
05052 /*! \brief Set nat mode on the various data sockets */
05053 static void do_setnat(struct sip_pvt *p, int natflags)
05054 {
05055    const char *mode = natflags ? "On" : "Off";
05056 
05057    if (p->rtp) {
05058       ast_debug(1, "Setting NAT on RTP to %s\n", mode);
05059       ast_rtp_setnat(p->rtp, natflags);
05060    }
05061    if (p->vrtp) {
05062       ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
05063       ast_rtp_setnat(p->vrtp, natflags);
05064    }
05065    if (p->udptl) {
05066       ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
05067       ast_udptl_setnat(p->udptl, natflags);
05068    }
05069    if (p->trtp) {
05070       ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
05071       ast_rtp_setnat(p->trtp, natflags);
05072    }
05073 }
05074 
05075 /*! \brief Change the T38 state on a SIP dialog */
05076 static void change_t38_state(struct sip_pvt *p, int state)
05077 {
05078    int old = p->t38.state;
05079    struct ast_channel *chan = p->owner;
05080    struct ast_control_t38_parameters parameters = { .request_response = 0 };
05081 
05082    /* Don't bother changing if we are already in the state wanted */
05083    if (old == state)
05084       return;
05085 
05086    p->t38.state = state;
05087    ast_debug(2, "T38 state changed to %d on channel %s\n", p->t38.state, chan ? chan->name : "<none>");
05088 
05089    /* If no channel was provided we can't send off a control frame */
05090    if (!chan)
05091       return;
05092 
05093    /* Given the state requested and old state determine what control frame we want to queue up */
05094    switch (state) {
05095    case T38_PEER_REINVITE:
05096       parameters = p->t38.their_parms;
05097       parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05098       parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
05099       ast_udptl_set_tag(p->udptl, "SIP/%s", p->username);
05100       break;
05101    case T38_ENABLED:
05102       parameters = p->t38.their_parms;
05103       parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05104       parameters.request_response = AST_T38_NEGOTIATED;
05105       ast_udptl_set_tag(p->udptl, "SIP/%s", p->username);
05106       break;
05107    case T38_DISABLED:
05108       if (old == T38_ENABLED) {
05109          parameters.request_response = AST_T38_TERMINATED;
05110       } else if (old == T38_LOCAL_REINVITE) {
05111          parameters.request_response = AST_T38_REFUSED;
05112       }
05113       break;
05114    case T38_LOCAL_REINVITE:
05115       /* wait until we get a peer response before responding to local reinvite */
05116       break;
05117    }
05118 
05119    /* Woot we got a message, create a control frame and send it on! */
05120    if (parameters.request_response)
05121       ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
05122 }
05123 
05124 /*! \brief Set the global T38 capabilities on a SIP dialog structure */
05125 static void set_t38_capabilities(struct sip_pvt *p)
05126 {
05127    if (p->udptl) {
05128       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY) {
05129                         ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
05130       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_FEC) {
05131          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
05132       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL) {
05133          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
05134       }
05135    }
05136 }
05137 
05138 static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
05139 {
05140    if (to_sock->tcptls_session) {
05141       ao2_ref(to_sock->tcptls_session, -1);
05142       to_sock->tcptls_session = NULL;
05143    }
05144 
05145    if (from_sock->tcptls_session) {
05146       ao2_ref(from_sock->tcptls_session, +1);
05147    }
05148 
05149    *to_sock = *from_sock;
05150 }
05151 
05152 /*! \brief Create address structure from peer reference.
05153  * This function copies data from peer to the dialog, so we don't have to look up the peer
05154  * again from memory or database during the life time of the dialog.
05155  *
05156  * \return -1 on error, 0 on success.
05157  *
05158  */
05159 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
05160 {
05161 
05162    /* this checks that the dialog is contacting the peer on a valid
05163     * transport type based on the peers transport configuration,
05164     * otherwise, this function bails out */
05165    if (dialog->socket.type && check_request_transport(peer, dialog))
05166       return -1;
05167    copy_socket_data(&dialog->socket, &peer->socket);
05168 
05169    if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
05170        (!peer->maxms || ((peer->lastms >= 0)  && (peer->lastms <= peer->maxms)))) {
05171       dialog->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
05172       dialog->recv = dialog->sa;
05173    } else 
05174       return -1;
05175 
05176    ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
05177    ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
05178    dialog->capability = peer->capability;
05179    if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) &&
05180          (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
05181             !(dialog->capability & AST_FORMAT_VIDEO_MASK)) &&
05182          dialog->vrtp) {
05183       ast_rtp_destroy(dialog->vrtp);
05184       dialog->vrtp = NULL;
05185    }
05186    if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT) && dialog->trtp) {
05187       ast_rtp_destroy(dialog->trtp);
05188       dialog->trtp = NULL;
05189    }
05190    dialog->prefs = peer->prefs;
05191    if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
05192       /* t38pt_udptl was enabled in the peer and not in [general] */
05193       if (dialog->udptl || (!dialog->udptl && (dialog->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr)))) {
05194          dialog->t38_maxdatagram = peer->t38_maxdatagram;
05195          set_t38_capabilities(dialog);
05196       } else {
05197          /* It is impossible to support T38 without udptl */
05198          ast_debug(1, "UDPTL creation failed on dialog.\n");
05199          ast_clear_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT);
05200       }
05201    } else if (dialog->udptl) {
05202       ast_udptl_destroy(dialog->udptl);
05203       dialog->udptl = NULL;
05204    }
05205    do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
05206 
05207    if (dialog->rtp) { /* Audio */
05208       ast_rtp_setdtmf(dialog->rtp, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
05209       ast_rtp_setdtmfcompensate(dialog->rtp, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
05210       ast_rtp_set_rtptimeout(dialog->rtp, peer->rtptimeout);
05211       ast_rtp_set_rtpholdtimeout(dialog->rtp, peer->rtpholdtimeout);
05212       ast_rtp_set_rtpkeepalive(dialog->rtp, peer->rtpkeepalive);
05213       /* Set Frame packetization */
05214       ast_rtp_codec_setpref(dialog->rtp, &dialog->prefs);
05215       dialog->autoframing = peer->autoframing;
05216    }
05217    if (dialog->vrtp) { /* Video */
05218       ast_rtp_setdtmf(dialog->vrtp, 0);
05219       ast_rtp_setdtmfcompensate(dialog->vrtp, 0);
05220       ast_rtp_set_rtptimeout(dialog->vrtp, peer->rtptimeout);
05221       ast_rtp_set_rtpholdtimeout(dialog->vrtp, peer->rtpholdtimeout);
05222       ast_rtp_set_rtpkeepalive(dialog->vrtp, peer->rtpkeepalive);
05223    }
05224    if (dialog->trtp) { /* Realtime text */
05225       ast_rtp_setdtmf(dialog->trtp, 0);
05226       ast_rtp_setdtmfcompensate(dialog->trtp, 0);
05227       ast_rtp_set_rtptimeout(dialog->trtp, peer->rtptimeout);
05228       ast_rtp_set_rtpholdtimeout(dialog->trtp, peer->rtpholdtimeout);
05229       ast_rtp_set_rtpkeepalive(dialog->trtp, peer->rtpkeepalive);
05230    }
05231 
05232    ast_string_field_set(dialog, peername, peer->name);
05233    ast_string_field_set(dialog, authname, peer->username);
05234    ast_string_field_set(dialog, username, peer->username);
05235    ast_string_field_set(dialog, peersecret, peer->secret);
05236    ast_string_field_set(dialog, peermd5secret, peer->md5secret);
05237    ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
05238    ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
05239    ast_string_field_set(dialog, tohost, peer->tohost);
05240    ast_string_field_set(dialog, fullcontact, peer->fullcontact);
05241    ast_string_field_set(dialog, context, peer->context);
05242    ast_string_field_set(dialog, parkinglot, peer->parkinglot);
05243    ref_proxy(dialog, obproxy_get(dialog, peer));
05244    dialog->callgroup = peer->callgroup;
05245    dialog->pickupgroup = peer->pickupgroup;
05246    dialog->allowtransfer = peer->allowtransfer;
05247    dialog->jointnoncodeccapability = dialog->noncodeccapability;
05248    dialog->rtptimeout = peer->rtptimeout;
05249    dialog->peerauth = peer->auth;
05250    dialog->maxcallbitrate = peer->maxcallbitrate;
05251    if (ast_strlen_zero(dialog->tohost))
05252       ast_string_field_set(dialog, tohost, ast_inet_ntoa(dialog->sa.sin_addr));
05253    if (!ast_strlen_zero(peer->fromdomain)) {
05254       ast_string_field_set(dialog, fromdomain, peer->fromdomain);
05255       if (!dialog->initreq.headers) {
05256          char *c;
05257          char *tmpcall = ast_strdupa(dialog->callid);
05258          /* this sure looks to me like we are going to change the callid on this dialog!! */
05259          c = strchr(tmpcall, '@');
05260          if (c) {
05261             *c = '\0';
05262             ao2_t_unlink(dialogs, dialog, "About to change the callid -- remove the old name");
05263             ast_string_field_build(dialog, callid, "%s@%s", tmpcall, peer->fromdomain);
05264             ao2_t_link(dialogs, dialog, "New dialog callid -- inserted back into table");
05265          }
05266       }
05267    }
05268    if (!ast_strlen_zero(peer->fromuser)) 
05269       ast_string_field_set(dialog, fromuser, peer->fromuser);
05270    if (!ast_strlen_zero(peer->language))
05271       ast_string_field_set(dialog, language, peer->language);
05272    /* Set timer T1 to RTT for this peer (if known by qualify=) */
05273    /* Minimum is settable or default to 100 ms */
05274    /* If there is a maxms and lastms from a qualify use that over a manual T1
05275       value. Otherwise, use the peer's T1 value. */
05276    if (peer->maxms && peer->lastms)
05277       dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
05278    else
05279       dialog->timer_t1 = peer->timer_t1;
05280 
05281    /* Set timer B to control transaction timeouts, the peer setting is the default and overrides
05282       the known timer */
05283    if (peer->timer_b)
05284       dialog->timer_b = peer->timer_b;
05285    else
05286       dialog->timer_b = 64 * dialog->timer_t1;
05287 
05288    if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
05289        (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
05290       dialog->noncodeccapability |= AST_RTP_DTMF;
05291    else
05292       dialog->noncodeccapability &= ~AST_RTP_DTMF;
05293    if (peer->call_limit)
05294       ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
05295    if (!dialog->portinuri)
05296       dialog->portinuri = peer->portinuri;
05297    
05298    dialog->chanvars = copy_vars(peer->chanvars);
05299 
05300    return 0;
05301 }
05302 
05303 /*! \brief create address structure from device name
05304  *      Or, if peer not found, find it in the global DNS 
05305  *      returns TRUE (-1) on failure, FALSE on success */
05306 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog)
05307 {
05308    struct hostent *hp;
05309    struct ast_hostent ahp;
05310    struct sip_peer *peer;
05311    char *port;
05312    int portno = 0;
05313    char host[MAXHOSTNAMELEN], *hostn;
05314    char peername[256];
05315    int srv_ret = 0;
05316 
05317    ast_copy_string(peername, opeer, sizeof(peername));
05318    port = strchr(peername, ':');
05319    if (port) {
05320       *port++ = '\0';
05321       dialog->portinuri = 1;
05322    }
05323    dialog->sa.sin_family = AF_INET;
05324    dialog->timer_t1 = global_t1; /* Default SIP retransmission timer T1 (RFC 3261) */
05325    dialog->timer_b = global_timer_b; /* Default SIP transaction timer B (RFC 3261) */
05326    peer = find_peer(peername, NULL, TRUE, FINDPEERS, FALSE, 0);
05327 
05328    if (peer) {
05329       int res;
05330       if (newdialog) {
05331          set_socket_transport(&dialog->socket, 0);
05332       }
05333       res = create_addr_from_peer(dialog, peer);
05334       if (!ast_strlen_zero(port)) {
05335          if ((portno = atoi(port))) {
05336             dialog->sa.sin_port = dialog->recv.sin_port = htons(portno);
05337          }
05338       }
05339       unref_peer(peer, "create_addr: unref peer from find_peer hashtab lookup");
05340       return res;
05341    }
05342 
05343    do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
05344 
05345    ast_string_field_set(dialog, tohost, peername);
05346 
05347    /* Get the outbound proxy information */
05348    ref_proxy(dialog, obproxy_get(dialog, NULL));
05349 
05350    if (sin) {
05351       /* This address should be updated using dnsmgr */
05352       memcpy(&dialog->sa.sin_addr, &sin->sin_addr, sizeof(dialog->sa.sin_addr));
05353       if (!sin->sin_port) {
05354          portno = port_str2int(port, (dialog->socket.type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
05355       } else {
05356          portno = ntohs(sin->sin_port);
05357       }
05358    } else {
05359 
05360       /* Let's see if we can find the host in DNS. First try DNS SRV records,
05361          then hostname lookup */
05362       /*! \todo Fix this function. When we ask for SRV, we should check all transports 
05363            In the future, we should first check NAPTR to find out transport preference
05364        */
05365       hostn = peername;
05366       /* Section 4.2 of RFC 3263 specifies that if a port number is specified, then
05367        * an A record lookup should be used instead of SRV.
05368        */
05369       if (!port && sip_cfg.srvlookup) {
05370          char service[MAXHOSTNAMELEN];
05371          int tportno;
05372          snprintf(service, sizeof(service), "_%s._%s.%s",
05373              get_srv_service(dialog->socket.type),
05374              get_srv_protocol(dialog->socket.type), peername);
05375          srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
05376          if (srv_ret > 0) {
05377             hostn = host;
05378             portno = tportno;
05379          }
05380       }
05381       if (!portno)
05382          portno = port_str2int(port, (dialog->socket.type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
05383       hp = ast_gethostbyname(hostn, &ahp);
05384       if (!hp) {
05385          ast_log(LOG_WARNING, "No such host: %s\n", peername);
05386          return -1;
05387       }
05388       memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
05389    }
05390 
05391    if (!dialog->socket.type)
05392       set_socket_transport(&dialog->socket, SIP_TRANSPORT_UDP);
05393    if (!dialog->socket.port)
05394       dialog->socket.port = bindaddr.sin_port;
05395    dialog->sa.sin_port = htons(portno);
05396    dialog->recv = dialog->sa;
05397    return 0;
05398 }
05399 
05400 /*! \brief Scheduled congestion on a call.
05401  * Only called by the scheduler, must return the reference when done.
05402  */
05403 static int auto_congest(const void *arg)
05404 {
05405    struct sip_pvt *p = (struct sip_pvt *)arg;
05406 
05407    sip_pvt_lock(p);
05408    p->initid = -1;   /* event gone, will not be rescheduled */
05409    if (p->owner) {
05410       /* XXX fails on possible deadlock */
05411       if (!ast_channel_trylock(p->owner)) {
05412          append_history(p, "Cong", "Auto-congesting (timer)");
05413          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
05414          ast_channel_unlock(p->owner);
05415       }
05416 
05417       /* Give the channel a chance to act before we proceed with destruction */
05418       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05419    }
05420    sip_pvt_unlock(p);
05421    dialog_unref(p, "unreffing arg passed into auto_congest callback (p->initid)");
05422    return 0;
05423 }
05424 
05425 
05426 /*! \brief Initiate SIP call from PBX 
05427  *      used from the dial() application      */
05428 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
05429 {
05430    int res;
05431    struct sip_pvt *p = ast->tech_pvt;  /* chan is locked, so the reference cannot go away */
05432    struct varshead *headp;
05433    struct ast_var_t *current;
05434    const char *referer = NULL;   /* SIP referrer */
05435 
05436    if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
05437       ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
05438       return -1;
05439    }
05440 
05441    /* Check whether there is vxml_url, distinctive ring variables */
05442    headp=&ast->varshead;
05443    AST_LIST_TRAVERSE(headp, current, entries) {
05444       /* Check whether there is a VXML_URL variable */
05445       if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
05446          p->options->vxml_url = ast_var_value(current);
05447       } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
05448          p->options->uri_options = ast_var_value(current);
05449       } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
05450          /* Check whether there is a variable with a name starting with SIPADDHEADER */
05451          p->options->addsipheaders = 1;
05452       } else if (!strcasecmp(ast_var_name(current), "SIPFROMDOMAIN")) {
05453          ast_string_field_set(p, fromdomain, ast_var_value(current));
05454       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
05455          /* This is a transfered call */
05456          p->options->transfer = 1;
05457       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
05458          /* This is the referrer */
05459          referer = ast_var_value(current);
05460       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
05461          /* We're replacing a call. */
05462          p->options->replaces = ast_var_value(current);
05463       }
05464    }
05465 
05466    res = 0;
05467    ast_set_flag(&p->flags[0], SIP_OUTGOING);
05468 
05469    /* T.38 re-INVITE FAX detection should never be done for outgoing calls,
05470     * so ensure it is disabled.
05471     */
05472    ast_clear_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38);
05473 
05474    if (p->options->transfer) {
05475       char buf[SIPBUFSIZE/2];
05476 
05477       if (referer) {
05478          if (sipdebug)
05479             ast_debug(3, "Call for %s transfered by %s\n", p->username, referer);
05480          snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
05481       } else 
05482          snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
05483       ast_string_field_set(p, cid_name, buf);
05484    } 
05485    ast_debug(1, "Outgoing Call for %s\n", p->username);
05486 
05487    res = update_call_counter(p, INC_CALL_RINGING);
05488 
05489    if (res == -1) {
05490       ast->hangupcause = AST_CAUSE_USER_BUSY;
05491       return res;
05492    }
05493    p->callingpres = ast->cid.cid_pres;
05494    p->jointcapability = ast_translate_available_formats(p->capability, p->prefcodec);
05495    p->jointnoncodeccapability = p->noncodeccapability;
05496 
05497    /* If there are no audio formats left to offer, punt */
05498    if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
05499       ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
05500       res = -1;
05501    } else {
05502       int xmitres;
05503 
05504       xmitres = transmit_invite(p, SIP_INVITE, 1, 2);
05505       if (xmitres == XMIT_ERROR)
05506          return -1;
05507       p->invitestate = INV_CALLING;
05508    
05509       /* Initialize auto-congest time */
05510       AST_SCHED_REPLACE_UNREF(p->initid, sched, p->timer_b, auto_congest, p, 
05511                         dialog_unref(_data, "dialog ptr dec when SCHED_REPLACE del op succeeded"), 
05512                         dialog_unref(p, "dialog ptr dec when SCHED_REPLACE add failed"),
05513                         dialog_ref(p, "dialog ptr inc when SCHED_REPLACE add succeeded") );
05514    }
05515    return res;
05516 }
05517 
05518 /*! \brief Destroy registry object
05519    Objects created with the register= statement in static configuration */
05520 static void sip_registry_destroy(struct sip_registry *reg)
05521 {
05522    /* Really delete */
05523    ast_debug(3, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
05524 
05525    if (reg->call) {
05526       /* Clear registry before destroying to ensure
05527          we don't get reentered trying to grab the registry lock */
05528       reg->call->registry = registry_unref(reg->call->registry, "destroy reg->call->registry");
05529       ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
05530       dialog_unlink_all(reg->call, TRUE, TRUE);
05531       reg->call = dialog_unref(reg->call, "unref reg->call");
05532       /* reg->call = sip_destroy(reg->call); */
05533    }
05534    AST_SCHED_DEL(sched, reg->expire);  
05535    AST_SCHED_DEL(sched, reg->timeout);
05536    
05537    ast_string_field_free_memory(reg);
05538    ast_atomic_fetchadd_int(&regobjs, -1);
05539    ast_dnsmgr_release(reg->dnsmgr);
05540    ast_free(reg);
05541 }
05542 
05543 /*! \brief Destroy MWI subscription object */
05544 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi)
05545 {
05546    if (mwi->call) {
05547       mwi->call->mwi = NULL;
05548       sip_destroy(mwi->call);
05549    }
05550    
05551    AST_SCHED_DEL(sched, mwi->resub);
05552    ast_string_field_free_memory(mwi);
05553    ast_dnsmgr_release(mwi->dnsmgr);
05554    ast_free(mwi);
05555 }
05556 
05557 /*! \brief Execute destruction of SIP dialog structure, release memory */
05558 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
05559 {
05560    struct sip_request *req;
05561 
05562    if (p->stimer) {
05563       ast_free(p->stimer);
05564       p->stimer = NULL;
05565    }
05566 
05567    if (sip_debug_test_pvt(p))
05568       ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
05569 
05570    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05571       update_call_counter(p, DEC_CALL_LIMIT);
05572       ast_debug(2, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
05573    }
05574 
05575    /* Unlink us from the owner if we have one */
05576    if (p->owner) {
05577       if (lockowner)
05578          ast_channel_lock(p->owner);
05579       if (option_debug)
05580          ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
05581       p->owner->tech_pvt = NULL;
05582       /* Make sure that the channel knows its backend is going away */
05583       p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
05584       if (lockowner)
05585          ast_channel_unlock(p->owner);
05586       /* Give the channel a chance to react before deallocation */
05587       usleep(1);
05588    }
05589 
05590    /* Remove link from peer to subscription of MWI */
05591    if (p->relatedpeer && p->relatedpeer->mwipvt)
05592       p->relatedpeer->mwipvt = dialog_unref(p->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
05593    if (p->relatedpeer && p->relatedpeer->call == p)
05594       p->relatedpeer->call = dialog_unref(p->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
05595    
05596    if (p->relatedpeer)
05597       p->relatedpeer = unref_peer(p->relatedpeer,"unsetting a dialog relatedpeer field in sip_destroy");
05598    
05599    if (p->registry) {
05600       if (p->registry->call == p)
05601          p->registry->call = dialog_unref(p->registry->call, "nulling out the registry's call dialog field in unlink_all");
05602       p->registry = registry_unref(p->registry, "delete p->registry");
05603    }
05604    
05605    if (p->mwi) {
05606       p->mwi->call = NULL;
05607    }
05608 
05609    if (dumphistory)
05610       sip_dump_history(p);
05611 
05612    if (p->options)
05613       ast_free(p->options);
05614 
05615    if (p->notify_headers) {
05616       ast_variables_destroy(p->notify_headers);
05617       p->notify_headers = NULL;
05618    }
05619    if (p->rtp) {
05620       ast_rtp_destroy(p->rtp);
05621    }
05622    if (p->vrtp) {
05623       ast_rtp_destroy(p->vrtp);
05624    }
05625    if (p->trtp) {
05626       while (ast_rtp_get_bridged(p->trtp))
05627          usleep(1);
05628       ast_rtp_destroy(p->trtp);
05629    }
05630    if (p->udptl)
05631       ast_udptl_destroy(p->udptl);
05632    if (p->refer)
05633       ast_free(p->refer);
05634    if (p->route) {
05635       free_old_route(p->route);
05636       p->route = NULL;
05637    }
05638    deinit_req(&p->initreq);
05639 
05640    /* Destroy Session-Timers if allocated */
05641    if (p->stimer) {
05642       p->stimer->quit_flag = 1;
05643       if (p->stimer->st_active == TRUE && p->stimer->st_schedid > -1) {
05644          AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
05645                dialog_unref(p, "removing session timer ref"));
05646       }
05647       ast_free(p->stimer);
05648       p->stimer = NULL;
05649    }
05650 
05651    /* Clear history */
05652    if (p->history) {
05653       struct sip_history *hist;
05654       while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
05655          ast_free(hist);
05656          p->history_entries--;
05657       }
05658       ast_free(p->history);
05659       p->history = NULL;
05660    }
05661 
05662    while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
05663       ast_free(req);
05664    }
05665 
05666    if (p->chanvars) {
05667       ast_variables_destroy(p->chanvars);
05668       p->chanvars = NULL;
05669    }
05670 
05671    ast_string_field_free_memory(p);
05672 
05673    if (p->socket.tcptls_session) {
05674       ao2_ref(p->socket.tcptls_session, -1);
05675       p->socket.tcptls_session = NULL;
05676    }
05677 }
05678 
05679 /*! \brief  update_call_counter: Handle call_limit for SIP devices
05680  * Setting a call-limit will cause calls above the limit not to be accepted.
05681  *
05682  * Remember that for a type=friend, there's one limit for the user and
05683  * another for the peer, not a combined call limit.
05684  * This will cause unexpected behaviour in subscriptions, since a "friend"
05685  * is *two* devices in Asterisk, not one.
05686  *
05687  * Thought: For realtime, we should probably update storage with inuse counter... 
05688  *
05689  * \return 0 if call is ok (no call limit, below threshold)
05690  * -1 on rejection of call
05691  *    
05692  */
05693 static int update_call_counter(struct sip_pvt *fup, int event)
05694 {
05695    char name[256];
05696    int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
05697    int outgoing = fup->outgoing_call;
05698    struct sip_peer *p = NULL;
05699 
05700    ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
05701 
05702 
05703    /* Test if we need to check call limits, in order to avoid 
05704       realtime lookups if we do not need it */
05705    if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
05706       return 0;
05707 
05708    ast_copy_string(name, fup->username, sizeof(name));
05709 
05710    /* Check the list of devices */
05711    if ((p = find_peer(ast_strlen_zero(fup->peername) ? name : fup->peername, NULL, TRUE, FINDALLDEVICES, FALSE, 0))) { 
05712       inuse = &p->inUse;
05713       call_limit = &p->call_limit;
05714       inringing = &p->inRinging;
05715       ast_copy_string(name, fup->peername, sizeof(name));
05716    }
05717    if (!p) {
05718       ast_debug(2, "%s is not a local device, no call limit\n", name);
05719       return 0;
05720    }
05721 
05722    switch(event) {
05723    /* incoming and outgoing affects the inUse counter */
05724    case DEC_CALL_LIMIT:
05725       /* Decrement inuse count if applicable */
05726       if (inuse) {
05727          sip_pvt_lock(fup);
05728          ao2_lock(p);
05729          if (*inuse > 0) {
05730             if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
05731                (*inuse)--;
05732                ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
05733             }
05734          } else {
05735             *inuse = 0;
05736          }
05737          ao2_unlock(p);
05738          sip_pvt_unlock(fup);
05739       }
05740 
05741       /* Decrement ringing count if applicable */
05742       if (inringing) {
05743          sip_pvt_lock(fup);
05744          ao2_lock(p);
05745          if (*inringing > 0) {
05746             if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05747                (*inringing)--;
05748                ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
05749             }
05750          } else {
05751             *inringing = 0;
05752          }
05753          ao2_unlock(p);
05754          sip_pvt_unlock(fup);
05755       }
05756 
05757       /* Decrement onhold count if applicable */
05758       sip_pvt_lock(fup);
05759       ao2_lock(p);
05760       if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && sip_cfg.notifyhold) {
05761          ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
05762          ao2_unlock(p);
05763          sip_pvt_unlock(fup);
05764          sip_peer_hold(fup, FALSE);
05765       } else {
05766          ao2_unlock(p);
05767          sip_pvt_unlock(fup);
05768       }
05769       if (sipdebug)
05770          ast_debug(2, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
05771       break;
05772 
05773    case INC_CALL_RINGING:
05774    case INC_CALL_LIMIT:
05775       /* If call limit is active and we have reached the limit, reject the call */
05776       if (*call_limit > 0 ) {
05777          if (*inuse >= *call_limit) {
05778             ast_log(LOG_NOTICE, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
05779             unref_peer(p, "update_call_counter: unref peer p, call limit exceeded");
05780             return -1; 
05781          }
05782       }
05783       if (inringing && (event == INC_CALL_RINGING)) {
05784          sip_pvt_lock(fup);
05785          ao2_lock(p);
05786          if (!ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05787             (*inringing)++;
05788             ast_set_flag(&fup->flags[0], SIP_INC_RINGING);
05789          }
05790          ao2_unlock(p);
05791          sip_pvt_unlock(fup);
05792       }
05793       if (inuse) {
05794          sip_pvt_lock(fup);
05795          ao2_lock(p);
05796          if (!ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
05797             (*inuse)++;
05798             ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
05799          }
05800          ao2_unlock(p);
05801          sip_pvt_unlock(fup);
05802       }
05803       if (sipdebug) {
05804          ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", "peer", name, *inuse, *call_limit);
05805       }
05806       break;
05807 
05808    case DEC_CALL_RINGING:
05809       if (inringing) {
05810          sip_pvt_lock(fup);
05811          ao2_lock(p);
05812          if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05813             if (*inringing > 0) {
05814                (*inringing)--;
05815             }
05816             ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
05817          }
05818          ao2_unlock(p);
05819          sip_pvt_unlock(fup);
05820       }
05821       break;
05822 
05823    default:
05824       ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
05825    }
05826 
05827    if (p) {
05828       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", p->name);
05829       unref_peer(p, "update_call_counter: unref_peer from call counter");
05830    } 
05831    return 0;
05832 }
05833 
05834 
05835 static void sip_destroy_fn(void *p)
05836 {
05837    sip_destroy(p);
05838 }
05839 
05840 /*! \brief Destroy SIP call structure.
05841  * Make it return NULL so the caller can do things like
05842  * foo = sip_destroy(foo);
05843  * and reduce the chance of bugs due to dangling pointers.
05844  */
05845 static struct sip_pvt * sip_destroy(struct sip_pvt *p)
05846 {
05847    ast_debug(3, "Destroying SIP dialog %s\n", p->callid);
05848    __sip_destroy(p, TRUE, TRUE);
05849    return NULL;
05850 }
05851 
05852 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
05853 static int hangup_sip2cause(int cause)
05854 {
05855    /* Possible values taken from causes.h */
05856 
05857    switch(cause) {
05858       case 401:   /* Unauthorized */
05859          return AST_CAUSE_CALL_REJECTED;
05860       case 403:   /* Not found */
05861          return AST_CAUSE_CALL_REJECTED;
05862       case 404:   /* Not found */
05863          return AST_CAUSE_UNALLOCATED;
05864       case 405:   /* Method not allowed */
05865          return AST_CAUSE_INTERWORKING;
05866       case 407:   /* Proxy authentication required */
05867          return AST_CAUSE_CALL_REJECTED;
05868       case 408:   /* No reaction */
05869          return AST_CAUSE_NO_USER_RESPONSE;
05870       case 409:   /* Conflict */
05871          return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
05872       case 410:   /* Gone */
05873          return AST_CAUSE_NUMBER_CHANGED;
05874       case 411:   /* Length required */
05875          return AST_CAUSE_INTERWORKING;
05876       case 413:   /* Request entity too large */
05877          return AST_CAUSE_INTERWORKING;
05878       case 414:   /* Request URI too large */
05879          return AST_CAUSE_INTERWORKING;
05880       case 415:   /* Unsupported media type */
05881          return AST_CAUSE_INTERWORKING;
05882       case 420:   /* Bad extension */
05883          return AST_CAUSE_NO_ROUTE_DESTINATION;
05884       case 480:   /* No answer */
05885          return AST_CAUSE_NO_ANSWER;
05886       case 481:   /* No answer */
05887          return AST_CAUSE_INTERWORKING;
05888       case 482:   /* Loop detected */
05889          return AST_CAUSE_INTERWORKING;
05890       case 483:   /* Too many hops */
05891          return AST_CAUSE_NO_ANSWER;
05892       case 484:   /* Address incomplete */
05893          return AST_CAUSE_INVALID_NUMBER_FORMAT;
05894       case 485:   /* Ambiguous */
05895          return AST_CAUSE_UNALLOCATED;
05896       case 486:   /* Busy everywhere */
05897          return AST_CAUSE_BUSY;
05898       case 487:   /* Request terminated */
05899          return AST_CAUSE_INTERWORKING;
05900       case 488:   /* No codecs approved */
05901          return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05902       case 491:   /* Request pending */
05903          return AST_CAUSE_INTERWORKING;
05904       case 493:   /* Undecipherable */
05905          return AST_CAUSE_INTERWORKING;
05906       case 500:   /* Server internal failure */
05907          return AST_CAUSE_FAILURE;
05908       case 501:   /* Call rejected */
05909          return AST_CAUSE_FACILITY_REJECTED;
05910       case 502:   
05911          return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
05912       case 503:   /* Service unavailable */
05913          return AST_CAUSE_CONGESTION;
05914       case 504:   /* Gateway timeout */
05915          return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
05916       case 505:   /* SIP version not supported */
05917          return AST_CAUSE_INTERWORKING;
05918       case 600:   /* Busy everywhere */
05919          return AST_CAUSE_USER_BUSY;
05920       case 603:   /* Decline */
05921          return AST_CAUSE_CALL_REJECTED;
05922       case 604:   /* Does not exist anywhere */
05923          return AST_CAUSE_UNALLOCATED;
05924       case 606:   /* Not acceptable */
05925          return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05926       default:
05927          return AST_CAUSE_NORMAL;
05928    }
05929    /* Never reached */
05930    return 0;
05931 }
05932 
05933 /*! \brief Convert Asterisk hangup causes to SIP codes 
05934 \verbatim
05935  Possible values from causes.h
05936         AST_CAUSE_NOTDEFINED    AST_CAUSE_NORMAL        AST_CAUSE_BUSY
05937         AST_CAUSE_FAILURE       AST_CAUSE_CONGESTION    AST_CAUSE_UNALLOCATED
05938 
05939    In addition to these, a lot of PRI codes is defined in causes.h 
05940    ...should we take care of them too ?
05941    
05942    Quote RFC 3398
05943 
05944    ISUP Cause value                        SIP response
05945    ----------------                        ------------
05946    1  unallocated number                   404 Not Found
05947    2  no route to network                  404 Not found
05948    3  no route to destination              404 Not found
05949    16 normal call clearing                 --- (*)
05950    17 user busy                            486 Busy here
05951    18 no user responding                   408 Request Timeout
05952    19 no answer from the user              480 Temporarily unavailable
05953    20 subscriber absent                    480 Temporarily unavailable
05954    21 call rejected                        403 Forbidden (+)
05955    22 number changed (w/o diagnostic)      410 Gone
05956    22 number changed (w/ diagnostic)       301 Moved Permanently
05957    23 redirection to new destination       410 Gone
05958    26 non-selected user clearing           404 Not Found (=)
05959    27 destination out of order             502 Bad Gateway
05960    28 address incomplete                   484 Address incomplete
05961    29 facility rejected                    501 Not implemented
05962    31 normal unspecified                   480 Temporarily unavailable
05963 \endverbatim
05964 */
05965 static const char *hangup_cause2sip(int cause)
05966 {
05967    switch (cause) {
05968       case AST_CAUSE_UNALLOCATED:      /* 1 */
05969       case AST_CAUSE_NO_ROUTE_DESTINATION:   /* 3 IAX2: Can't find extension in context */
05970       case AST_CAUSE_NO_ROUTE_TRANSIT_NET:   /* 2 */
05971          return "404 Not Found";
05972       case AST_CAUSE_CONGESTION:    /* 34 */
05973       case AST_CAUSE_SWITCH_CONGESTION:   /* 42 */
05974          return "503 Service Unavailable";
05975       case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
05976          return "408 Request Timeout";
05977       case AST_CAUSE_NO_ANSWER:     /* 19 */
05978       case AST_CAUSE_UNREGISTERED:        /* 20 */
05979          return "480 Temporarily unavailable";
05980       case AST_CAUSE_CALL_REJECTED:    /* 21 */
05981          return "403 Forbidden";
05982       case AST_CAUSE_NUMBER_CHANGED:      /* 22 */
05983          return "410 Gone";
05984       case AST_CAUSE_NORMAL_UNSPECIFIED:  /* 31 */
05985          return "480 Temporarily unavailable";
05986       case AST_CAUSE_INVALID_NUMBER_FORMAT:
05987          return "484 Address incomplete";
05988       case AST_CAUSE_USER_BUSY:
05989          return "486 Busy here";
05990       case AST_CAUSE_FAILURE:
05991          return "500 Server internal failure";
05992       case AST_CAUSE_FACILITY_REJECTED:   /* 29 */
05993          return "501 Not Implemented";
05994       case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
05995          return "503 Service Unavailable";
05996       /* Used in chan_iax2 */
05997       case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
05998          return "502 Bad Gateway";
05999       case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
06000          return "488 Not Acceptable Here";
06001          
06002       case AST_CAUSE_NOTDEFINED:
06003       default:
06004          ast_debug(1, "AST hangup cause %d (no match found in SIP)\n", cause);
06005          return NULL;
06006    }
06007 
06008    /* Never reached */
06009    return 0;
06010 }
06011 
06012 
06013 /*! \brief  sip_hangup: Hangup SIP call
06014  * Part of PBX interface, called from ast_hangup */
06015 static int sip_hangup(struct ast_channel *ast)
06016 {
06017    struct sip_pvt *p = ast->tech_pvt;
06018    int needcancel = FALSE;
06019    int needdestroy = 0;
06020    struct ast_channel *oldowner = ast;
06021 
06022    if (!p) {
06023       ast_debug(1, "Asked to hangup channel that was not connected\n");
06024       return 0;
06025    }
06026    if (ast_test_flag(ast, AST_FLAG_ANSWERED_ELSEWHERE) || ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
06027       ast_debug(1, "This call was answered elsewhere");
06028       if (ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
06029          ast_debug(1, "####### It's the cause code, buddy. The cause code!!!\n");
06030       }
06031       append_history(p, "Cancel", "Call answered elsewhere");
06032       p->answered_elsewhere = TRUE;
06033    }
06034 
06035    /* Store hangupcause locally in PVT so we still have it before disconnect */
06036    if (p->owner)
06037       p->hangupcause = p->owner->hangupcause;
06038 
06039    if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
06040       if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06041          if (sipdebug)
06042             ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
06043          update_call_counter(p, DEC_CALL_LIMIT);
06044       }
06045       ast_debug(4, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
06046       if (p->autokillid > -1 && sip_cancel_destroy(p))
06047          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
06048       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06049       ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Really hang up next time */
06050       p->needdestroy = 0;
06051       p->owner->tech_pvt = dialog_unref(p->owner->tech_pvt, "unref p->owner->tech_pvt");
06052       sip_pvt_lock(p);
06053       p->owner = NULL;  /* Owner will be gone after we return, so take it away */
06054       sip_pvt_unlock(p);
06055       ast_module_unref(ast_module_info->self);
06056       return 0;
06057    }
06058 
06059    if (ast_test_flag(ast, AST_FLAG_ZOMBIE)) {
06060       if (p->refer)
06061          ast_debug(1, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast->name, p->callid);
06062       else
06063          ast_debug(1, "Hanging up zombie call. Be scared.\n");
06064    } else
06065       ast_debug(1, "Hangup call %s, SIP callid %s\n", ast->name, p->callid);
06066 
06067    sip_pvt_lock(p);
06068    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06069       if (sipdebug)
06070          ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
06071       update_call_counter(p, DEC_CALL_LIMIT);
06072    }
06073 
06074    /* Determine how to disconnect */
06075    if (p->owner != ast) {
06076       ast_log(LOG_WARNING, "Huh?  We aren't the owner? Can't hangup call.\n");
06077       sip_pvt_unlock(p);
06078       return 0;
06079    }
06080    /* If the call is not UP, we need to send CANCEL instead of BYE */
06081    /* In case of re-invites, the call might be UP even though we have an incomplete invite transaction */
06082    if (p->invitestate < INV_COMPLETED && p->owner->_state != AST_STATE_UP) {
06083       needcancel = TRUE;
06084       ast_debug(4, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
06085    }
06086 
06087    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
06088 
06089    append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", p->owner ? ast_cause2str(p->hangupcause) : "Unknown");
06090 
06091    /* Disconnect */
06092    if (p->dsp)
06093       ast_dsp_free(p->dsp);
06094 
06095    p->owner = NULL;
06096    ast->tech_pvt = dialog_unref(ast->tech_pvt, "unref ast->tech_pvt");
06097 
06098    ast_module_unref(ast_module_info->self);
06099    /* Do not destroy this pvt until we have timeout or
06100       get an answer to the BYE or INVITE/CANCEL 
06101       If we get no answer during retransmit period, drop the call anyway.
06102       (Sorry, mother-in-law, you can't deny a hangup by sending
06103       603 declined to BYE...)
06104    */
06105    if (p->alreadygone)
06106       needdestroy = 1;  /* Set destroy flag at end of this function */
06107    else if (p->invitestate != INV_CALLING)
06108       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06109 
06110    /* Start the process if it's not already started */
06111    if (!p->alreadygone && p->initreq.data && !ast_strlen_zero(p->initreq.data->str)) {
06112       if (needcancel) { /* Outgoing call, not up */
06113          if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06114             /* stop retransmitting an INVITE that has not received a response */
06115             /* if we can't send right now, mark it pending */
06116             if (p->invitestate == INV_CALLING) {
06117                /* We can't send anything in CALLING state */
06118                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
06119                __sip_pretend_ack(p);
06120                /* 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. */
06121                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06122                append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
06123             } else {
06124                struct sip_pkt *cur;
06125 
06126                for (cur = p->packets; cur; cur = cur->next) {
06127                   __sip_semi_ack(p, cur->seqno, cur->is_resp, cur->method ? cur->method : find_sip_method(cur->data->str));
06128                }
06129                p->invitestate = INV_CANCELLED;
06130                /* Send a new request: CANCEL */
06131                transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
06132                /* Actually don't destroy us yet, wait for the 487 on our original 
06133                   INVITE, but do set an autodestruct just in case we never get it. */
06134                needdestroy = 0;
06135                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06136             }
06137          } else { /* Incoming call, not up */
06138             const char *res;
06139             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"));
06140             if (p->hangupcause && (res = hangup_cause2sip(p->hangupcause)))
06141                transmit_response_reliable(p, res, &p->initreq);
06142             else 
06143                transmit_response_reliable(p, "603 Declined", &p->initreq);
06144             p->invitestate = INV_TERMINATED;
06145          }
06146       } else { /* Call is in UP state, send BYE */
06147          if (p->stimer->st_active == TRUE) {
06148             stop_session_timer(p);
06149          }
06150 
06151          if (!p->pendinginvite) {
06152             struct ast_channel *bridge = ast_bridged_channel(oldowner);
06153             char *audioqos = "";
06154             char *videoqos = "";
06155             char *textqos = "";
06156 
06157             /* We need to get the lock on bridge because ast_rtp_set_vars will attempt
06158              * to lock the bridge. This may get hairy...
06159              */
06160             while (bridge && ast_channel_trylock(bridge)) {
06161                sip_pvt_unlock(p);
06162                do {
06163                   /* Use oldowner since p->owner is already NULL */
06164                   CHANNEL_DEADLOCK_AVOIDANCE(oldowner);
06165                } while (sip_pvt_trylock(p));
06166                bridge = ast_bridged_channel(oldowner);
06167             }
06168 
06169             if (p->rtp)
06170                ast_rtp_set_vars(oldowner, p->rtp);
06171 
06172             if (bridge) {
06173                struct sip_pvt *q = bridge->tech_pvt;
06174 
06175                if (IS_SIP_TECH(bridge->tech) && q && q->rtp)
06176                   ast_rtp_set_vars(bridge, q->rtp);
06177                ast_channel_unlock(bridge);
06178             }
06179 
06180             if (p->vrtp)
06181                videoqos = ast_rtp_get_quality(p->vrtp, NULL, RTPQOS_SUMMARY);
06182             if (p->trtp)
06183                textqos = ast_rtp_get_quality(p->trtp, NULL, RTPQOS_SUMMARY);
06184             /* Send a hangup */
06185             if (oldowner->_state == AST_STATE_UP) {
06186                transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
06187             }
06188 
06189             /* Get RTCP quality before end of call */
06190             if (p->do_history) {
06191                if (p->rtp)
06192                   append_history(p, "RTCPaudio", "Quality:%s", audioqos);
06193                if (p->vrtp)
06194                   append_history(p, "RTCPvideo", "Quality:%s", videoqos);
06195                if (p->trtp)
06196                   append_history(p, "RTCPtext", "Quality:%s", textqos);
06197             }
06198             if (p->rtp && oldowner)
06199                pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", audioqos);
06200             if (p->vrtp && oldowner)
06201                pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", videoqos);
06202             if (p->trtp && oldowner)
06203                pbx_builtin_setvar_helper(oldowner, "RTPTEXTQOS", textqos);
06204          } else {
06205             /* Note we will need a BYE when this all settles out
06206                but we can't send one while we have "INVITE" outstanding. */
06207             ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
06208             ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE); 
06209             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"));
06210             if (sip_cancel_destroy(p))
06211                ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
06212          }
06213       }
06214    }
06215    if (needdestroy) {
06216       pvt_set_needdestroy(p, "hangup");
06217    }
06218    sip_pvt_unlock(p);
06219    return 0;
06220 }
06221 
06222 /*! \brief Try setting codec suggested by the SIP_CODEC channel variable */
06223 static void try_suggested_sip_codec(struct sip_pvt *p)
06224 {
06225    int fmt;
06226    const char *codec;
06227 
06228    codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
06229    if (!codec) 
06230       return;
06231 
06232    fmt = ast_getformatbyname(codec);
06233    if (fmt) {
06234       ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
06235       if (p->jointcapability & fmt) {
06236          p->jointcapability &= fmt;
06237          p->capability &= fmt;
06238       } else
06239          ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
06240    } else
06241       ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
06242    return;  
06243 }
06244 
06245 /*! \brief  sip_answer: Answer SIP call , send 200 OK on Invite 
06246  * Part of PBX interface */
06247 static int sip_answer(struct ast_channel *ast)
06248 {
06249    int res = 0;
06250    struct sip_pvt *p = ast->tech_pvt;
06251 
06252    sip_pvt_lock(p);
06253    if (ast->_state != AST_STATE_UP) {
06254       try_suggested_sip_codec(p);   
06255 
06256       ast_setstate(ast, AST_STATE_UP);
06257       ast_debug(1, "SIP answering channel: %s\n", ast->name);
06258       ast_rtp_new_source(p->rtp);
06259       res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL, FALSE);
06260       ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
06261    }
06262    sip_pvt_unlock(p);
06263    return res;
06264 }
06265 
06266 /*! \brief Send frame to media channel (rtp) */
06267 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
06268 {
06269    struct sip_pvt *p = ast->tech_pvt;
06270    int res = 0;
06271 
06272    switch (frame->frametype) {
06273    case AST_FRAME_VOICE:
06274       if (!(frame->subclass & ast->nativeformats)) {
06275          char s1[512], s2[512], s3[512];
06276          ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %s(%d) read/write = %s(%d)/%s(%d)\n",
06277             frame->subclass, 
06278             ast_getformatname_multiple(s1, sizeof(s1) - 1, ast->nativeformats & AST_FORMAT_AUDIO_MASK),
06279             ast->nativeformats & AST_FORMAT_AUDIO_MASK,
06280             ast_getformatname_multiple(s2, sizeof(s2) - 1, ast->readformat),
06281             ast->readformat,
06282             ast_getformatname_multiple(s3, sizeof(s3) - 1, ast->writeformat),
06283             ast->writeformat);
06284          return 0;
06285       }
06286       if (p) {
06287          sip_pvt_lock(p);
06288          if (p->rtp) {
06289             /* If channel is not up, activate early media session */
06290             if ((ast->_state != AST_STATE_UP) &&
06291                 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06292                 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06293                ast_rtp_new_source(p->rtp);
06294                if (!global_prematuremediafilter) {
06295                   p->invitestate = INV_EARLY_MEDIA;
06296                   transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06297                   ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06298                }
06299             } else if (p->t38.state == T38_ENABLED) {
06300                /* drop frame, can't sent VOICE frames while in T.38 mode */
06301             } else {
06302                p->lastrtptx = time(NULL);
06303                res = ast_rtp_write(p->rtp, frame);
06304             }
06305          }
06306          sip_pvt_unlock(p);
06307       }
06308       break;
06309    case AST_FRAME_VIDEO:
06310       if (p) {
06311          sip_pvt_lock(p);
06312          if (p->vrtp) {
06313             /* Activate video early media */
06314             if ((ast->_state != AST_STATE_UP) &&
06315                 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06316                 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06317                p->invitestate = INV_EARLY_MEDIA;
06318                transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06319                ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06320             }
06321             p->lastrtptx = time(NULL);
06322             res = ast_rtp_write(p->vrtp, frame);
06323          }
06324          sip_pvt_unlock(p);
06325       }
06326       break;
06327    case AST_FRAME_TEXT:
06328       if (p) {
06329          sip_pvt_lock(p);
06330          if (p->red) {
06331             red_buffer_t140(p->trtp, frame);
06332          } else {
06333             if (p->trtp) {
06334                /* Activate text early media */
06335                if ((ast->_state != AST_STATE_UP) &&
06336                    !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06337                    !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06338                   p->invitestate = INV_EARLY_MEDIA;
06339                   transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06340                   ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06341                }
06342                p->lastrtptx = time(NULL);
06343                res = ast_rtp_write(p->trtp, frame);
06344             }
06345          }
06346          sip_pvt_unlock(p);
06347       }
06348       break;
06349    case AST_FRAME_IMAGE:
06350       return 0;
06351       break;
06352    case AST_FRAME_MODEM:
06353       if (p) {
06354          sip_pvt_lock(p);
06355          /* UDPTL requires two-way communication, so early media is not needed here.
06356             we simply forget the frames if we get modem frames before the bridge is up.
06357             Fax will re-transmit.
06358          */
06359          if ((ast->_state == AST_STATE_UP) &&
06360              p->udptl &&
06361              (p->t38.state == T38_ENABLED)) {
06362             res = ast_udptl_write(p->udptl, frame);
06363          }
06364          sip_pvt_unlock(p);
06365       }
06366       break;
06367    default: 
06368       ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
06369       return 0;
06370    }
06371 
06372    return res;
06373 }
06374 
06375 /*! \brief  sip_fixup: Fix up a channel:  If a channel is consumed, this is called.
06376         Basically update any ->owner links */
06377 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
06378 {
06379    int ret = -1;
06380    struct sip_pvt *p;
06381 
06382    if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE))
06383       ast_debug(1, "New channel is zombie\n");
06384    if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE))
06385       ast_debug(1, "Old channel is zombie\n");
06386 
06387    if (!newchan || !newchan->tech_pvt) {
06388       if (!newchan)
06389          ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
06390       else
06391          ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
06392       return -1;
06393    }
06394    p = newchan->tech_pvt;
06395 
06396    sip_pvt_lock(p);
06397    append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
06398    append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
06399    if (p->owner != oldchan)
06400       ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
06401    else {
06402       p->owner = newchan;
06403       /* Re-invite RTP back to Asterisk. Needed if channel is masqueraded out of a native
06404          RTP bridge (i.e., RTP not going through Asterisk): RTP bridge code might not be
06405          able to do this if the masquerade happens before the bridge breaks (e.g., AMI
06406          redirect of both channels). Note that a channel can not be masqueraded *into*
06407          a native bridge. So there is no danger that this breaks a native bridge that
06408          should stay up. */
06409       sip_set_rtp_peer(newchan, NULL, NULL, 0, 0, 0);
06410       ret = 0;
06411    }
06412    ast_debug(3, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);
06413 
06414    sip_pvt_unlock(p);
06415    return ret;
06416 }
06417 
06418 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
06419 {
06420    struct sip_pvt *p = ast->tech_pvt;
06421    int res = 0;
06422 
06423    sip_pvt_lock(p);
06424    switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06425    case SIP_DTMF_INBAND:
06426       res = -1; /* Tell Asterisk to generate inband indications */
06427       break;
06428    case SIP_DTMF_RFC2833:
06429       if (p->rtp)
06430          ast_rtp_senddigit_begin(p->rtp, digit);
06431       break;
06432    default:
06433       break;
06434    }
06435    sip_pvt_unlock(p);
06436 
06437    return res;
06438 }
06439 
06440 /*! \brief Send DTMF character on SIP channel
06441    within one call, we're able to transmit in many methods simultaneously */
06442 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
06443 {
06444    struct sip_pvt *p = ast->tech_pvt;
06445    int res = 0;
06446 
06447    sip_pvt_lock(p);
06448    switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06449    case SIP_DTMF_INFO:
06450    case SIP_DTMF_SHORTINFO:
06451       transmit_info_with_digit(p, digit, duration);
06452       break;
06453    case SIP_DTMF_RFC2833:
06454       if (p->rtp)
06455          ast_rtp_senddigit_end(p->rtp, digit);
06456       break;
06457    case SIP_DTMF_INBAND:
06458       res = -1; /* Tell Asterisk to stop inband indications */
06459       break;
06460    }
06461    sip_pvt_unlock(p);
06462 
06463    return res;
06464 }
06465 
06466 /*! \brief Transfer SIP call */
06467 static int sip_transfer(struct ast_channel *ast, const char *dest)
06468 {
06469    struct sip_pvt *p = ast->tech_pvt;
06470    int res;
06471 
06472    if (dest == NULL) /* functions below do not take a NULL */
06473       dest = "";
06474    sip_pvt_lock(p);
06475    if (ast->_state == AST_STATE_RING)
06476       res = sip_sipredirect(p, dest);
06477    else
06478       res = transmit_refer(p, dest);
06479    sip_pvt_unlock(p);
06480    return res;
06481 }
06482 
06483 /*! \brief Helper function which updates T.38 capability information and triggers a reinvite */
06484 static int interpret_t38_parameters(struct sip_pvt *p, const struct ast_control_t38_parameters *parameters)
06485 {
06486    int res = 0;
06487 
06488    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) || !p->udptl) {
06489       return -1;
06490    }
06491    switch (parameters->request_response) {
06492    case AST_T38_NEGOTIATED:
06493    case AST_T38_REQUEST_NEGOTIATE:         /* Request T38 */
06494       /* Negotiation can not take place without a valid max_ifp value. */
06495       if (!parameters->max_ifp) {
06496          change_t38_state(p, T38_DISABLED);
06497          if (p->t38.state == T38_PEER_REINVITE) {
06498             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"));
06499             transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06500          }
06501          break;
06502       } else if (p->t38.state == T38_PEER_REINVITE) {
06503          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"));
06504          p->t38.our_parms = *parameters;
06505          /* modify our parameters to conform to the peer's parameters,
06506           * based on the rules in the ITU T.38 recommendation
06507           */
06508          if (!p->t38.their_parms.fill_bit_removal) {
06509             p->t38.our_parms.fill_bit_removal = FALSE;
06510          }
06511          if (!p->t38.their_parms.transcoding_mmr) {
06512             p->t38.our_parms.transcoding_mmr = FALSE;
06513          }
06514          if (!p->t38.their_parms.transcoding_jbig) {
06515             p->t38.our_parms.transcoding_jbig = FALSE;
06516          }
06517          p->t38.our_parms.version = MIN(p->t38.our_parms.version, p->t38.their_parms.version);
06518          p->t38.our_parms.rate_management = p->t38.their_parms.rate_management;
06519          ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06520          change_t38_state(p, T38_ENABLED);
06521          transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
06522       } else if (p->t38.state != T38_ENABLED) {
06523          p->t38.our_parms = *parameters;
06524          ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06525          change_t38_state(p, T38_LOCAL_REINVITE);
06526          if (!p->pendinginvite) {
06527             transmit_reinvite_with_sdp(p, TRUE, FALSE);
06528          } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
06529             ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
06530          }
06531       }
06532       break;
06533    case AST_T38_TERMINATED:
06534    case AST_T38_REFUSED:
06535    case AST_T38_REQUEST_TERMINATE:         /* Shutdown T38 */
06536       if (p->t38.state == T38_PEER_REINVITE) {
06537          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"));
06538          change_t38_state(p, T38_DISABLED);
06539          transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06540       } else if (p->t38.state == T38_ENABLED)
06541          transmit_reinvite_with_sdp(p, FALSE, FALSE);
06542       break;
06543    case AST_T38_REQUEST_PARMS: {    /* Application wants remote's parameters re-sent */
06544       struct ast_control_t38_parameters parameters = p->t38.their_parms;
06545 
06546       if (p->t38.state == T38_PEER_REINVITE) {
06547          AST_SCHED_DEL(sched, p->t38id);
06548          parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
06549          parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
06550          ast_queue_control_data(p->owner, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
06551          /* we need to return a positive value here, so that applications that
06552           * send this request can determine conclusively whether it was accepted or not...
06553           * older versions of chan_sip would just silently accept it and return zero.
06554           */
06555          res = AST_T38_REQUEST_PARMS;
06556       }
06557       break;
06558    }
06559    default:
06560       res = -1;
06561       break;
06562    }
06563 
06564    return res;
06565 }
06566 
06567 /*! \brief Play indication to user 
06568  * With SIP a lot of indications is sent as messages, letting the device play
06569    the indication - busy signal, congestion etc 
06570    \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
06571 */
06572 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
06573 {
06574    struct sip_pvt *p = ast->tech_pvt;
06575    int res = 0;
06576 
06577    sip_pvt_lock(p);
06578    switch(condition) {
06579    case AST_CONTROL_RINGING:
06580       if (ast->_state == AST_STATE_RING) {
06581          p->invitestate = INV_EARLY_MEDIA;
06582          if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
06583              (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {            
06584             /* Send 180 ringing if out-of-band seems reasonable */
06585             transmit_provisional_response(p, "180 Ringing", &p->initreq, 0);
06586             ast_set_flag(&p->flags[0], SIP_RINGING);
06587             if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
06588                break;
06589          } else {
06590             /* Well, if it's not reasonable, just send in-band */
06591          }
06592       }
06593       res = -1;
06594       break;
06595    case AST_CONTROL_BUSY:
06596       if (ast->_state != AST_STATE_UP) {
06597          transmit_response_reliable(p, "486 Busy Here", &p->initreq);
06598          p->invitestate = INV_COMPLETED;
06599          sip_alreadygone(p);
06600          ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06601          break;
06602       }
06603       res = -1;
06604       break;
06605    case AST_CONTROL_CONGESTION:
06606       if (ast->_state != AST_STATE_UP) {
06607          transmit_response_reliable(p, "503 Service Unavailable", &p->initreq);
06608          p->invitestate = INV_COMPLETED;
06609          sip_alreadygone(p);
06610          ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06611          break;
06612       }
06613       res = -1;
06614       break;
06615    case AST_CONTROL_PROCEEDING:
06616       if ((ast->_state != AST_STATE_UP) &&
06617           !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06618           !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06619          transmit_response(p, "100 Trying", &p->initreq);
06620          p->invitestate = INV_PROCEEDING;  
06621          break;
06622       }
06623       res = -1;
06624       break;
06625    case AST_CONTROL_PROGRESS:
06626       if ((ast->_state != AST_STATE_UP) &&
06627           !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06628           !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06629          p->invitestate = INV_EARLY_MEDIA;
06630          transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06631          ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06632          break;
06633       }
06634       res = -1;
06635       break;
06636    case AST_CONTROL_HOLD:
06637       ast_rtp_new_source(p->rtp);
06638       ast_moh_start(ast, data, p->mohinterpret);
06639       break;
06640    case AST_CONTROL_UNHOLD:
06641       ast_rtp_new_source(p->rtp);
06642       ast_moh_stop(ast);
06643       break;
06644    case AST_CONTROL_VIDUPDATE:   /* Request a video frame update */
06645       if (p->vrtp && !p->novideo) {
06646          transmit_info_with_vidupdate(p);
06647          /* ast_rtcp_send_h261fur(p->vrtp); */
06648       } else
06649          res = -1;
06650       break;
06651    case AST_CONTROL_T38_PARAMETERS:
06652       if (datalen != sizeof(struct ast_control_t38_parameters)) {
06653          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);
06654          res = -1;
06655       } else {
06656          const struct ast_control_t38_parameters *parameters = data;
06657          res = interpret_t38_parameters(p, parameters);
06658       }
06659       break;
06660    case AST_CONTROL_SRCUPDATE:
06661       ast_rtp_new_source(p->rtp);
06662       break;
06663    case AST_CONTROL_SRCCHANGE:
06664       ast_rtp_change_source(p->rtp);
06665       break;
06666    case -1:
06667       res = -1;
06668       break;
06669    default:
06670       ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
06671       res = -1;
06672       break;
06673    }
06674    sip_pvt_unlock(p);
06675    return res;
06676 }
06677 
06678 
06679 /*! \brief Initiate a call in the SIP channel
06680    called from sip_request_call (calls from the pbx ) for outbound channels
06681    and from handle_request_invite for inbound channels
06682    
06683 */
06684 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title)
06685 {
06686    struct ast_channel *tmp;
06687    struct ast_variable *v = NULL;
06688    int fmt;
06689    int what;
06690    int video;
06691    int text;
06692    int needvideo = 0;
06693    int needtext = 0;
06694    char buf[SIPBUFSIZE];
06695    char *decoded_exten;
06696 
06697    {
06698       const char *my_name; /* pick a good name */
06699    
06700       if (title) {
06701          my_name = title;
06702       } else {
06703          char *port = NULL;
06704          my_name = ast_strdupa(i->fromdomain);
06705          if ((port = strchr(i->fromdomain, ':'))) {
06706             *port = '\0';
06707          }
06708       }
06709 
06710       sip_pvt_unlock(i);
06711       /* Don't hold a sip pvt lock while we allocate a channel */
06712       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));
06713 
06714    }
06715    if (!tmp) {
06716       ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
06717       sip_pvt_lock(i);
06718       return NULL;
06719    }
06720    sip_pvt_lock(i);
06721 
06722    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;
06723 
06724    /* Select our native format based on codec preference until we receive
06725       something from another device to the contrary. */
06726    if (i->jointcapability) {  /* The joint capabilities of us and peer */
06727       what = i->jointcapability;
06728       video = i->jointcapability & AST_FORMAT_VIDEO_MASK;
06729       text = i->jointcapability & AST_FORMAT_TEXT_MASK;
06730    } else if (i->capability) {      /* Our configured capability for this peer */
06731       what = i->capability;
06732       video = i->capability & AST_FORMAT_VIDEO_MASK;
06733       text = i->capability & AST_FORMAT_TEXT_MASK;
06734    } else {
06735       what = global_capability;  /* Global codec support */
06736       video = global_capability & AST_FORMAT_VIDEO_MASK;
06737       text = global_capability & AST_FORMAT_TEXT_MASK;
06738    }
06739 
06740    /* Set the native formats for audio  and merge in video */
06741    tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | video | text;
06742    ast_debug(3, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmp->nativeformats));
06743    ast_debug(3, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcapability));
06744    ast_debug(3, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->capability));
06745    ast_debug(3, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, ast_codec_choose(&i->prefs, what, 1)));
06746    if (i->prefcodec)
06747       ast_debug(3, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcodec));
06748 
06749    /* XXX Why are we choosing a codec from the native formats?? */
06750    fmt = ast_best_codec(tmp->nativeformats);
06751 
06752    /* If we have a prefcodec setting, we have an inbound channel that set a 
06753       preferred format for this call. Otherwise, we check the jointcapability
06754       We also check for vrtp. If it's not there, we are not allowed do any video anyway.
06755     */
06756    if (i->vrtp) {
06757       if (ast_test_flag(&i->flags[1], SIP_PAGE2_VIDEOSUPPORT))
06758          needvideo = AST_FORMAT_VIDEO_MASK;
06759       else if (i->prefcodec)
06760          needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK;  /* Outbound call */
06761       else
06762          needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK;  /* Inbound call */
06763    }
06764 
06765    if (i->trtp) {
06766       if (i->prefcodec)
06767          needtext = i->prefcodec & AST_FORMAT_TEXT_MASK; /* Outbound call */
06768       else
06769          needtext = i->jointcapability & AST_FORMAT_TEXT_MASK; /* Inbound call */
06770    }
06771 
06772    if (needvideo) 
06773       ast_debug(3, "This channel can handle video! HOLLYWOOD next!\n");
06774    else
06775       ast_debug(3, "This channel will not be able to handle video.\n");
06776 
06777    if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) || (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) ||
06778        (ast_test_flag(&i->flags[1], SIP_PAGE2_FAX_DETECT))) {
06779       int features = 0;
06780 
06781       if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) || (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
06782          features |= DSP_FEATURE_DIGIT_DETECT;
06783       }
06784 
06785       if (ast_test_flag(&i->flags[1], SIP_PAGE2_FAX_DETECT)) {
06786          features |= DSP_FEATURE_FAX_DETECT;
06787       }
06788 
06789       i->dsp = ast_dsp_new();
06790       ast_dsp_set_features(i->dsp, features);
06791       if (global_relaxdtmf)
06792          ast_dsp_set_digitmode(i->dsp, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
06793          }
06794 
06795    /* Set file descriptors for audio, video, realtime text and UDPTL as needed */
06796    if (i->rtp) {
06797       ast_channel_set_fd(tmp, 0, ast_rtp_fd(i->rtp));
06798       ast_channel_set_fd(tmp, 1, ast_rtcp_fd(i->rtp));
06799    }
06800    if (needvideo && i->vrtp) {
06801       ast_channel_set_fd(tmp, 2, ast_rtp_fd(i->vrtp));
06802       ast_channel_set_fd(tmp, 3, ast_rtcp_fd(i->vrtp));
06803    }
06804    if (needtext && i->trtp) 
06805       ast_channel_set_fd(tmp, 4, ast_rtp_fd(i->trtp));
06806    if (i->udptl)
06807       ast_channel_set_fd(tmp, 5, ast_udptl_fd(i->udptl));
06808 
06809    if (state == AST_STATE_RING)
06810       tmp->rings = 1;
06811    tmp->adsicpe = AST_ADSI_UNAVAILABLE;
06812    tmp->writeformat = fmt;
06813    tmp->rawwriteformat = fmt;
06814    tmp->readformat = fmt;
06815    tmp->rawreadformat = fmt;
06816    tmp->tech_pvt = dialog_ref(i, "sip_new: set chan->tech_pvt to i");
06817 
06818    tmp->callgroup = i->callgroup;
06819    tmp->pickupgroup = i->pickupgroup;
06820    tmp->cid.cid_pres = i->callingpres;
06821    if (!ast_strlen_zero(i->parkinglot))
06822       ast_string_field_set(tmp, parkinglot, i->parkinglot);
06823    if (!ast_strlen_zero(i->accountcode))
06824       ast_string_field_set(tmp, accountcode, i->accountcode);
06825    if (i->amaflags)
06826       tmp->amaflags = i->amaflags;
06827    if (!ast_strlen_zero(i->language))
06828       ast_string_field_set(tmp, language, i->language);
06829    i->owner = tmp;
06830    ast_module_ref(ast_module_info->self);
06831    ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
06832    /*Since it is valid to have extensions in the dialplan that have unescaped characters in them
06833     * we should decode the uri before storing it in the channel, but leave it encoded in the sip_pvt
06834     * structure so that there aren't issues when forming URI's
06835     */
06836    decoded_exten = ast_strdupa(i->exten);
06837    ast_uri_decode(decoded_exten);
06838    ast_copy_string(tmp->exten, decoded_exten, sizeof(tmp->exten));
06839 
06840    /* Don't use ast_set_callerid() here because it will
06841     * generate an unnecessary NewCallerID event  */
06842    tmp->cid.cid_ani = ast_strdup(i->cid_num);
06843    if (!ast_strlen_zero(i->rdnis))
06844       tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
06845    
06846    if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
06847       tmp->cid.cid_dnid = ast_strdup(i->exten);
06848 
06849    tmp->priority = 1;
06850    if (!ast_strlen_zero(i->uri))
06851       pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
06852    if (!ast_strlen_zero(i->domain))
06853       pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
06854    if (!ast_strlen_zero(i->callid))
06855       pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
06856    if (i->rtp)
06857       ast_jb_configure(tmp, &global_jbconf);
06858 
06859    /* Set channel variables for this call from configuration */
06860    for (v = i->chanvars ; v ; v = v->next) {
06861       char valuebuf[1024];
06862       pbx_builtin_setvar_helper(tmp, v->name, ast_get_encoded_str(v->value, valuebuf, sizeof(valuebuf)));
06863    }
06864 
06865    if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
06866       ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
06867       tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
06868       ast_hangup(tmp);
06869       tmp = NULL;
06870    }
06871 
06872    if (i->do_history)
06873       append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);
06874 
06875    /* Inform manager user about new channel and their SIP call ID */
06876    if (sip_cfg.callevents)
06877       manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
06878          "Channel: %s\r\nUniqueid: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\n",
06879          tmp->name, tmp->uniqueid, "SIP", i->callid, i->fullcontact);
06880 
06881    return tmp;
06882 }
06883 
06884 /*! \brief Reads one line of SIP message body */
06885 static char *get_body_by_line(const char *line, const char *name, int nameLen, char delimiter)
06886 {
06887    if (!strncasecmp(line, name, nameLen) && line[nameLen] == delimiter)
06888       return ast_skip_blanks(line + nameLen + 1);
06889 
06890    return "";
06891 }
06892 
06893 /*! \brief Lookup 'name' in the SDP starting
06894  * at the 'start' line. Returns the matching line, and 'start'
06895  * is updated with the next line number.
06896  */
06897 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
06898 {
06899    int len = strlen(name);
06900 
06901    while (*start < (req->sdp_start + req->sdp_count)) {
06902       const char *r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[(*start)++]), name, len, '=');
06903       if (r[0] != '\0')
06904          return r;
06905    }
06906 
06907    /* if the line was not found, ensure that *start points past the SDP */
06908    (*start)++;
06909 
06910    return "";
06911 }
06912 
06913 /*! \brief Fetches the next valid SDP line between the 'start' line
06914  * (inclusive) and the 'stop' line (exclusive). Returns the type
06915  * ('a', 'c', ...) and matching line in reference 'start' is updated
06916  * with the next line number.
06917  */
06918 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value)
06919 {
06920    char type = '\0';
06921    const char *line = NULL;
06922 
06923    if (stop > (req->sdp_start + req->sdp_count)) {
06924       stop = req->sdp_start + req->sdp_count;
06925    }
06926 
06927    while (*start < stop) {
06928       line = REQ_OFFSET_TO_STR(req, line[(*start)++]);
06929       if (line[1] == '=') {
06930          type = line[0];
06931          *value = ast_skip_blanks(line + 2);
06932          break;
06933       }
06934    }
06935 
06936    return type;
06937 }
06938 
06939 /*! \brief Get a specific line from the message body */
06940 static char *get_body(struct sip_request *req, char *name, char delimiter) 
06941 {
06942    int x;
06943    int len = strlen(name);
06944    char *r;
06945 
06946    for (x = 0; x < req->lines; x++) {
06947       r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[x]), name, len, delimiter);
06948       if (r[0] != '\0')
06949          return r;
06950    }
06951 
06952    return "";
06953 }
06954 
06955 /*! \brief Find compressed SIP alias */
06956 static const char *find_alias(const char *name, const char *_default)
06957 {
06958    /*! \brief Structure for conversion between compressed SIP and "normal" SIP */
06959    static const struct cfalias {
06960       char * const fullname;
06961       char * const shortname;
06962    } aliases[] = {
06963       { "Content-Type",  "c" },
06964       { "Content-Encoding",    "e" },
06965       { "From",       "f" },
06966       { "Call-ID",       "i" },
06967       { "Contact",       "m" },
06968       { "Content-Length",   "l" },
06969       { "Subject",       "s" },
06970       { "To",         "t" },
06971       { "Supported",     "k" },
06972       { "Refer-To",      "r" },
06973       { "Referred-By",   "b" },
06974       { "Allow-Events",  "u" },
06975       { "Event",      "o" },
06976       { "Via",     "v" },
06977       { "Accept-Contact",      "a" },
06978       { "Reject-Contact",      "j" },
06979       { "Request-Disposition", "d" },
06980       { "Session-Expires",     "x" },
06981       { "Identity",            "y" },
06982       { "Identity-Info",       "n" },
06983    };
06984    int x;
06985 
06986    for (x = 0; x < ARRAY_LEN(aliases); x++) {
06987       if (!strcasecmp(aliases[x].fullname, name))
06988          return aliases[x].shortname;
06989    }
06990 
06991    return _default;
06992 }
06993 
06994 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
06995 {
06996    int pass;
06997 
06998    /*
06999     * Technically you can place arbitrary whitespace both before and after the ':' in
07000     * a header, although RFC3261 clearly says you shouldn't before, and place just
07001     * one afterwards.  If you shouldn't do it, what absolute idiot decided it was 
07002     * a good idea to say you can do it, and if you can do it, why in the hell would.
07003     * you say you shouldn't.
07004     * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
07005     * and we always allow spaces after that for compatibility.
07006     */
07007    for (pass = 0; name && pass < 2;pass++) {
07008       int x, len = strlen(name);
07009       for (x = *start; x < req->headers; x++) {
07010          char *header = REQ_OFFSET_TO_STR(req, header[x]);
07011          if (!strncasecmp(header, name, len)) {
07012             char *r = header + len; /* skip name */
07013             if (sip_cfg.pedanticsipchecking)
07014                r = ast_skip_blanks(r);
07015 
07016             if (*r == ':') {
07017                *start = x+1;
07018                return ast_skip_blanks(r+1);
07019             }
07020          }
07021       }
07022       if (pass == 0) /* Try aliases */
07023          name = find_alias(name, NULL);
07024    }
07025 
07026    /* Don't return NULL, so get_header is always a valid pointer */
07027    return "";
07028 }
07029 
07030 /*! \brief Get header from SIP request 
07031    \return Always return something, so don't check for NULL because it won't happen :-)
07032 */
07033 static const char *get_header(const struct sip_request *req, const char *name)
07034 {
07035    int start = 0;
07036    return __get_header(req, name, &start);
07037 }
07038 
07039 /*! \brief Read RTP from network */
07040 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
07041 {
07042    /* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
07043    struct ast_frame *f;
07044    
07045    if (!p->rtp) {
07046       /* We have no RTP allocated for this channel */
07047       return &ast_null_frame;
07048    }
07049 
07050    switch(ast->fdno) {
07051    case 0:
07052       f = ast_rtp_read(p->rtp);  /* RTP Audio */
07053       break;
07054    case 1:
07055       f = ast_rtcp_read(p->rtp); /* RTCP Control Channel */
07056       break;
07057    case 2:
07058       f = ast_rtp_read(p->vrtp); /* RTP Video */
07059       break;
07060    case 3:
07061       f = ast_rtcp_read(p->vrtp);   /* RTCP Control Channel for video */
07062       break;
07063    case 4:
07064       f = ast_rtp_read(p->trtp); /* RTP Text */
07065       if (sipdebug_text) {
07066          int i;
07067          unsigned char* arr = f->data.ptr;
07068          for (i=0; i < f->datalen; i++)
07069             ast_verbose("%c", (arr[i] > ' ' && arr[i] < '}') ? arr[i] : '.');
07070          ast_verbose(" -> ");
07071          for (i=0; i < f->datalen; i++)
07072             ast_verbose("%02X ", arr[i]);
07073          ast_verbose("\n");
07074       }
07075       break;
07076    case 5:
07077       f = ast_udptl_read(p->udptl); /* UDPTL for T.38 */
07078       break;
07079    default:
07080       f = &ast_null_frame;
07081    }
07082    /* Don't forward RFC2833 if we're not supposed to */
07083    if (f && (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) &&
07084        (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833)) {
07085       ast_debug(1, "Ignoring DTMF (%c) RTP frame because dtmfmode is not RFC2833\n", f->subclass);
07086       return &ast_null_frame;
07087    }
07088 
07089    /* We already hold the channel lock */
07090    if (!p->owner || (f && f->frametype != AST_FRAME_VOICE))
07091       return f;
07092 
07093    if (f && f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
07094       if (!(f->subclass & p->jointcapability)) {
07095          ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
07096             ast_getformatname(f->subclass), p->owner->name);
07097          return &ast_null_frame;
07098       }
07099       ast_debug(1, "Oooh, format changed to %d %s\n",
07100          f->subclass, ast_getformatname(f->subclass));
07101       p->owner->nativeformats = (p->owner->nativeformats & (AST_FORMAT_VIDEO_MASK | AST_FORMAT_TEXT_MASK)) | f->subclass;
07102       ast_set_read_format(p->owner, p->owner->readformat);
07103       ast_set_write_format(p->owner, p->owner->writeformat);
07104    }
07105 
07106    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) {
07107       f = ast_dsp_process(p->owner, p->dsp, f);
07108                 if (f && f->frametype == AST_FRAME_DTMF) {
07109          if (f->subclass == 'f') {
07110                                 if (option_debug)
07111                                         ast_log(LOG_DEBUG, "Fax CNG detected on %s\n", ast->name);
07112                                 *faxdetect = 1;
07113             /* If we only needed this DSP for fax detection purposes we can just drop it now */
07114             if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
07115                ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
07116             } else {
07117                ast_dsp_free(p->dsp);
07118                p->dsp = NULL;
07119             }
07120          } else {
07121             ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass);
07122          }
07123       }
07124    }
07125    
07126    return f;
07127 }
07128 
07129 /*! \brief Read SIP RTP from channel */
07130 static struct ast_frame *sip_read(struct ast_channel *ast)
07131 {
07132    struct ast_frame *fr;
07133    struct sip_pvt *p = ast->tech_pvt;
07134    int faxdetected = FALSE;
07135 
07136    sip_pvt_lock(p);
07137    fr = sip_rtp_read(ast, p, &faxdetected);
07138    p->lastrtprx = time(NULL);
07139 
07140    /* If we detect a CNG tone and fax detection is enabled then send us off to the fax extension */
07141    if (faxdetected && ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
07142       ast_channel_lock(ast);
07143       if (strcmp(ast->exten, "fax")) {
07144          const char *target_context = S_OR(ast->macrocontext, ast->context);
07145          ast_channel_unlock(ast);
07146          if (ast_exists_extension(ast, target_context, "fax", 1, ast->cid.cid_num)) {
07147             ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to CNG detection\n", ast->name);
07148             pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
07149             if (ast_async_goto(ast, target_context, "fax", 1)) {
07150                ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast->name, target_context);
07151             }
07152             fr = &ast_null_frame;
07153          } else {
07154             ast_log(LOG_NOTICE, "FAX CNG detected but no fax extension\n");
07155                         }
07156       } else {
07157          ast_channel_unlock(ast);
07158                 }
07159         }
07160 
07161    /* Only allow audio through if they sent progress with SDP, or if the channel is actually answered */
07162    if (fr && fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast->_state != AST_STATE_UP) {
07163       fr = &ast_null_frame;
07164    }
07165 
07166    sip_pvt_unlock(p);
07167 
07168    return fr;
07169 }
07170 
07171 
07172 /*! \brief Generate 32 byte random string for callid's etc */
07173 static char *generate_random_string(char *buf, size_t size)
07174 {
07175    long val[4];
07176    int x;
07177 
07178    for (x=0; x<4; x++)
07179       val[x] = ast_random();
07180    snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
07181 
07182    return buf;
07183 }
07184 
07185 /*! \brief Build SIP Call-ID value for a non-REGISTER transaction */
07186 static void build_callid_pvt(struct sip_pvt *pvt)
07187 {
07188    char buf[33];
07189 
07190    const char *host = S_OR(pvt->fromdomain, ast_inet_ntoa(pvt->ourip.sin_addr));
07191    
07192    ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07193 
07194 }
07195 
07196 /*! \brief Build SIP Call-ID value for a REGISTER transaction */
07197 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain)
07198 {
07199    char buf[33];
07200 
07201    const char *host = S_OR(fromdomain, ast_inet_ntoa(ourip));
07202 
07203    ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07204 }
07205 
07206 /*! \brief Make our SIP dialog tag */
07207 static void make_our_tag(char *tagbuf, size_t len)
07208 {
07209    snprintf(tagbuf, len, "as%08lx", ast_random());
07210 }
07211 
07212 /*! \brief Allocate Session-Timers struct w/in dialog */
07213 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
07214 {
07215    struct sip_st_dlg *stp;
07216 
07217    if (p->stimer) {
07218       ast_log(LOG_ERROR, "Session-Timer struct already allocated\n");
07219       return p->stimer;
07220    }
07221 
07222    if (!(stp = ast_calloc(1, sizeof(struct sip_st_dlg))))
07223       return NULL;
07224 
07225    p->stimer = stp;
07226 
07227    stp->st_schedid = -1;           /* Session-Timers ast_sched scheduler id */
07228 
07229    return p->stimer;
07230 }
07231 
07232 /*! \brief Allocate sip_pvt structure, set defaults and link in the container.
07233  * Returns a reference to the object so whoever uses it later must
07234  * remember to release the reference.
07235  */
07236 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
07237              int useglobal_nat, const int intended_method, struct sip_request *req)
07238 {
07239    struct sip_pvt *p;
07240 
07241    if (!(p = ao2_t_alloc(sizeof(*p), sip_destroy_fn, "allocate a dialog(pvt) struct")))
07242       return NULL;
07243 
07244    if (ast_string_field_init(p, 512)) {
07245       ao2_t_ref(p, -1, "failed to string_field_init, drop p");
07246       return NULL;
07247    }
07248 
07249    if (req) {
07250       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 */
07251    } else {
07252       set_socket_transport(&p->socket, SIP_TRANSPORT_UDP);
07253    }
07254 
07255    p->socket.fd = -1;
07256    p->method = intended_method;
07257    p->initid = -1;
07258    p->waitid = -1;
07259    p->autokillid = -1;
07260    p->request_queue_sched_id = -1;
07261    p->provisional_keepalive_sched_id = -1;
07262    p->t38id = -1;
07263    p->subscribed = NONE;
07264    p->stateid = -1;
07265    p->sessionversion_remote = -1;
07266    p->session_modify = TRUE;
07267    p->stimer = NULL;
07268    p->prefs = default_prefs;     /* Set default codecs for this call */
07269 
07270    if (intended_method != SIP_OPTIONS) {  /* Peerpoke has it's own system */
07271       p->timer_t1 = global_t1;   /* Default SIP retransmission timer T1 (RFC 3261) */
07272       p->timer_b = global_timer_b;  /* Default SIP transaction timer B (RFC 3261) */
07273    }
07274 
07275    if (!sin)
07276       p->ourip = internip;
07277    else {
07278       p->sa = *sin;
07279       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
07280    }
07281 
07282    /* Copy global flags to this PVT at setup. */
07283    ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
07284    ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
07285 
07286    p->do_history = recordhistory;
07287 
07288    p->branch = ast_random();  
07289    make_our_tag(p->tag, sizeof(p->tag));
07290    p->ocseq = INITIAL_CSEQ;
07291 
07292    if (sip_methods[intended_method].need_rtp) {
07293       p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
07294       /* If the global videosupport flag is on, we always create a RTP interface for video */
07295       if (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
07296             ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS))
07297          p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
07298       if (ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT))
07299          p->trtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
07300       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
07301          if (!(p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr))) {
07302             /* udptl creation failed, T38 can not be supported on this dialog */
07303             ast_log(LOG_ERROR, "UDPTL creation failed\n");
07304             ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
07305          }
07306       }
07307       if (!p->rtp|| (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) && !p->vrtp) 
07308             || (ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) && !p->trtp)) {
07309          ast_log(LOG_WARNING, "Unable to create RTP audio %s%ssession: %s\n",
07310             ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "and video " : "",
07311             ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "and text " : "", strerror(errno));
07312          if (p->chanvars) {
07313             ast_variables_destroy(p->chanvars);
07314             p->chanvars = NULL;
07315          }
07316          ao2_t_ref(p, -1, "failed to create RTP audio session, drop p");
07317          return NULL;
07318          p->t38_maxdatagram = global_t38_maxdatagram;
07319       }
07320       ast_rtp_setqos(p->rtp, global_tos_audio, global_cos_audio, "SIP RTP");
07321       ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
07322       ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
07323       ast_rtp_set_rtptimeout(p->rtp, global_rtptimeout);
07324       ast_rtp_set_rtpholdtimeout(p->rtp, global_rtpholdtimeout);
07325       ast_rtp_set_rtpkeepalive(p->rtp, global_rtpkeepalive);
07326       if (p->vrtp) {
07327          ast_rtp_setqos(p->vrtp, global_tos_video, global_cos_video, "SIP VRTP");
07328          ast_rtp_setdtmf(p->vrtp, 0);
07329          ast_rtp_setdtmfcompensate(p->vrtp, 0);
07330          ast_rtp_set_rtptimeout(p->vrtp, global_rtptimeout);
07331          ast_rtp_set_rtpholdtimeout(p->vrtp, global_rtpholdtimeout);
07332          ast_rtp_set_rtpkeepalive(p->vrtp, global_rtpkeepalive);
07333       }
07334       if (p->trtp) {
07335          ast_rtp_setqos(p->trtp, global_tos_text, global_cos_text, "SIP TRTP");
07336          ast_rtp_setdtmf(p->trtp, 0);
07337          ast_rtp_setdtmfcompensate(p->trtp, 0);
07338       }
07339       if (p->udptl)
07340          ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
07341       p->maxcallbitrate = default_maxcallbitrate;
07342       p->autoframing = global_autoframing;
07343       ast_rtp_codec_setpref(p->rtp, &p->prefs);
07344    }
07345 
07346    if (useglobal_nat && sin) {
07347       /* Setup NAT structure according to global settings if we have an address */
07348       ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
07349       p->recv = *sin;
07350       do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
07351    }
07352 
07353    if (p->method != SIP_REGISTER)
07354       ast_string_field_set(p, fromdomain, default_fromdomain);
07355    build_via(p);
07356    if (!callid)
07357       build_callid_pvt(p);
07358    else
07359       ast_string_field_set(p, callid, callid);
07360    /* Assign default music on hold class */
07361    ast_string_field_set(p, mohinterpret, default_mohinterpret);
07362    ast_string_field_set(p, mohsuggest, default_mohsuggest);
07363    p->capability = global_capability;
07364    p->allowtransfer = sip_cfg.allowtransfer;
07365    if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
07366        (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
07367       p->noncodeccapability |= AST_RTP_DTMF;
07368    if (p->udptl) {
07369       p->t38_maxdatagram = global_t38_maxdatagram;
07370       set_t38_capabilities(p);
07371    }
07372    ast_string_field_set(p, context, sip_cfg.default_context);
07373    ast_string_field_set(p, parkinglot, default_parkinglot);
07374 
07375    AST_LIST_HEAD_INIT_NOLOCK(&p->request_queue);
07376 
07377    /* Add to active dialog list */
07378 
07379    ao2_t_link(dialogs, p, "link pvt into dialogs table");
07380    
07381    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");
07382    return p;
07383 }
07384 
07385 /*! \brief argument to the helper function to identify a call */
07386 struct find_call_cb_arg {
07387    enum sipmethod method;
07388    const char *callid;
07389    const char *fromtag;
07390    const char *totag;
07391    const char *tag;
07392 };
07393 
07394 /*!
07395  * code to determine whether this is the pvt that we are looking for.
07396  * Return FALSE if not found, true otherwise. p is unlocked.
07397  */
07398 static int find_call_cb(void *__pvt, void *__arg, int flags)
07399 {
07400    struct sip_pvt *p = __pvt;
07401    struct find_call_cb_arg *arg = __arg;
07402    /* In pedantic, we do not want packets with bad syntax to be connected to a PVT */
07403    int found = FALSE;
07404    
07405    if (!ast_strlen_zero(p->callid)) { /* XXX double check, do we allow match on empty p->callid ? */
07406       if (arg->method == SIP_REGISTER)
07407          found = (!strcmp(p->callid, arg->callid));
07408       else {
07409          found = !strcmp(p->callid, arg->callid);
07410          if (sip_cfg.pedanticsipchecking && found) {
07411             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);
07412          } 
07413       }
07414       
07415       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);
07416       
07417       /* If we get a new request within an existing to-tag - check the to tag as well */
07418       if (sip_cfg.pedanticsipchecking && found && arg->method != SIP_RESPONSE) { /* SIP Request */
07419          if (p->tag[0] == '\0' && arg->totag[0]) {
07420             /* We have no to tag, but they have. Wrong dialog */
07421             found = FALSE;
07422          } else if (arg->totag[0]) { /* Both have tags, compare them */
07423             if (strcmp(arg->totag, p->tag)) {
07424                found = FALSE; /* This is not our packet */
07425             }
07426          }
07427          if (!found)
07428             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);
07429       }
07430    }
07431    return found;
07432 }
07433 
07434 /*! \brief find or create a dialog structure for an incoming SIP message.
07435  * Connect incoming SIP message to current dialog or create new dialog structure
07436  * Returns a reference to the sip_pvt object, remember to give it back once done.
07437  *     Called by handle_incoming(), sipsock_read
07438  */
07439 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
07440 {
07441    struct sip_pvt *p = NULL;
07442    char *tag = "";   /* note, tag is never NULL */
07443    char totag[128];
07444    char fromtag[128];
07445    struct find_call_cb_arg arg;
07446    const char *callid = get_header(req, "Call-ID");
07447    const char *from = get_header(req, "From");
07448    const char *to = get_header(req, "To");
07449    const char *cseq = get_header(req, "Cseq");
07450    struct sip_pvt *sip_pvt_ptr;
07451 
07452    /* Call-ID, to, from and Cseq are required by RFC 3261. (Max-forwards and via too - ignored now) */
07453    /* get_header always returns non-NULL so we must use ast_strlen_zero() */
07454    if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
07455          ast_strlen_zero(from) || ast_strlen_zero(cseq))
07456       return NULL;   /* Invalid packet */
07457 
07458    arg.method = req->method;
07459    arg.callid = callid;
07460    arg.fromtag = fromtag;
07461    arg.totag = totag;
07462    arg.tag = ""; /* make sure tag is never NULL */
07463 
07464    if (sip_cfg.pedanticsipchecking) {
07465       /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
07466          we need more to identify a branch - so we have to check branch, from
07467          and to tags to identify a call leg.
07468          For Asterisk to behave correctly, you need to turn on pedanticsipchecking
07469          in sip.conf
07470          */
07471       if (gettag(req, "To", totag, sizeof(totag)))
07472          req->has_to_tag = 1; /* Used in handle_request/response */
07473       gettag(req, "From", fromtag, sizeof(fromtag));
07474 
07475       tag = (req->method == SIP_RESPONSE) ? totag : fromtag;
07476 
07477       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);
07478 
07479       /* All messages must always have From: tag */
07480       if (ast_strlen_zero(fromtag)) {
07481          ast_debug(5, "%s request has no from tag, dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
07482          return NULL;
07483       }
07484       /* reject requests that must always have a To: tag */
07485       if (ast_strlen_zero(totag) && (req->method == SIP_ACK || req->method == SIP_BYE || req->method == SIP_INFO )) {
07486          ast_debug(5, "%s must have a to tag. dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
07487          return NULL;
07488       }
07489    }
07490 
07491 restartsearch:
07492    if (!sip_cfg.pedanticsipchecking) {
07493       struct sip_pvt tmp_dialog = {
07494          .callid = callid,
07495       };       
07496       sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find in dialogs");
07497       if (sip_pvt_ptr) {  /* well, if we don't find it-- what IS in there? */
07498          /* Found the call */
07499          sip_pvt_lock(sip_pvt_ptr);
07500          return sip_pvt_ptr;
07501       }
07502    } else { /* in pedantic mode! -- do the fancy linear search */
07503       ao2_lock(dialogs);
07504       p = ao2_t_callback(dialogs, 0 /* single, data */, find_call_cb, &arg, "pedantic linear search for dialog");
07505       if (p) {
07506          if (sip_pvt_trylock(p)) {
07507             ao2_unlock(dialogs);
07508             usleep(1);
07509             goto restartsearch;
07510          }
07511          ao2_unlock(dialogs);
07512          return p;
07513       }
07514       ao2_unlock(dialogs);
07515    }
07516  
07517    /* See if the method is capable of creating a dialog */
07518    if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
07519       if (intended_method == SIP_REFER) {
07520          /* We do support REFER, but not outside of a dialog yet */
07521          transmit_response_using_temp(callid, sin, 1, intended_method, req, "603 Declined (no dialog)");
07522       } else if (intended_method == SIP_NOTIFY) {
07523          /* We do not support out-of-dialog NOTIFY either,
07524             like voicemail notification, so cancel that early */
07525          transmit_response_using_temp(callid, sin, 1, intended_method, req, "489 Bad event");
07526       } else {
07527          /* Ok, time to create a new SIP dialog object, a pvt */
07528          if ((p = sip_alloc(callid, sin, 1, intended_method, req)))  {
07529             /* Ok, we've created a dialog, let's go and process it */
07530             sip_pvt_lock(p);
07531          } else {
07532             /* We have a memory or file/socket error (can't allocate RTP sockets or something) so we're not
07533                getting a dialog from sip_alloc. 
07534    
07535                Without a dialog we can't retransmit and handle ACKs and all that, but at least
07536                send an error message.
07537    
07538                Sorry, we apologize for the inconvienience
07539             */
07540             transmit_response_using_temp(callid, sin, 1, intended_method, req, "500 Server internal error");
07541             ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
07542          }
07543       }
07544       return p; /* can be NULL */
07545    } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
07546       /* A method we do not support, let's take it on the volley */
07547       transmit_response_using_temp(callid, sin, 1, intended_method, req, "501 Method Not Implemented");
07548       ast_debug(2, "Got a request with unsupported SIP method.\n");
07549    } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
07550       /* This is a request outside of a dialog that we don't know about */
07551       transmit_response_using_temp(callid, sin, 1, intended_method, req, "481 Call leg/transaction does not exist");
07552       ast_debug(2, "That's odd...  Got a request in unknown dialog. Callid %s\n", callid ? callid : "<unknown>");
07553    }
07554    /* We do not respond to responses for dialogs that we don't know about, we just drop
07555       the session quickly */
07556    if (intended_method == SIP_RESPONSE)
07557       ast_debug(2, "That's odd...  Got a response on a call we don't know about. Callid %s\n", callid ? callid : "<unknown>");
07558 
07559    return NULL;
07560 }
07561 
07562 /*! \brief Parse register=> line in sip.conf and add to registry */
07563 static int sip_register(const char *value, int lineno)
07564 {
07565    struct sip_registry *reg;
07566    int portnum = 0;
07567    enum sip_transport transport = SIP_TRANSPORT_UDP;
07568    char buf[256] = "";
07569    char *userpart = NULL, *hostpart = NULL;
07570    /* register => [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] */
07571    AST_DECLARE_APP_ARGS(pre1,
07572       AST_APP_ARG(peer);
07573       AST_APP_ARG(userpart);
07574    );
07575    AST_DECLARE_APP_ARGS(pre2,
07576       AST_APP_ARG(transport);
07577       AST_APP_ARG(blank);
07578       AST_APP_ARG(userpart);
07579    );
07580    AST_DECLARE_APP_ARGS(user1,
07581       AST_APP_ARG(userpart);
07582       AST_APP_ARG(secret);
07583       AST_APP_ARG(authuser);
07584    );
07585    AST_DECLARE_APP_ARGS(host1,
07586       AST_APP_ARG(hostpart);
07587       AST_APP_ARG(expiry);
07588    );
07589    AST_DECLARE_APP_ARGS(host2,
07590       AST_APP_ARG(hostpart);
07591       AST_APP_ARG(extension);
07592    );
07593    AST_DECLARE_APP_ARGS(host3,
07594       AST_APP_ARG(host);
07595       AST_APP_ARG(port);
07596    );
07597 
07598    if (!value)
07599       return -1;
07600    ast_copy_string(buf, value, sizeof(buf));
07601 
07602    /*! register => [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry]
07603     * becomes
07604     *   userpart => [peer?][transport://]user[@domain][:secret[:authuser]]
07605     *   hostpart => host[:port][/extension][~expiry]
07606     */
07607    if ((hostpart = strrchr(buf, '@'))) {
07608       *hostpart++ = '\0';
07609       userpart = buf;
07610    }
07611 
07612    if (ast_strlen_zero(userpart) || ast_strlen_zero(hostpart)) {
07613       ast_log(LOG_WARNING, "Format for registration is [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] at line %d\n", lineno);
07614       return -1;
07615    }
07616 
07617    /*!
07618     * pre1.peer => peer
07619     * pre1.userpart => [transport://]user[@domain][:secret[:authuser]]
07620     * hostpart => host[:port][/extension][~expiry]
07621     */
07622    AST_NONSTANDARD_RAW_ARGS(pre1, userpart, '?');
07623    if (ast_strlen_zero(pre1.userpart)) {
07624       pre1.userpart = pre1.peer;
07625       pre1.peer = NULL;
07626    }
07627 
07628    /*!
07629     * pre1.peer => peer
07630     * pre2.transport = transport
07631     * pre2.userpart => user[@domain][:secret[:authuser]]
07632     * hostpart => host[:port][/extension][~expiry]
07633     */
07634    AST_NONSTANDARD_RAW_ARGS(pre2, pre1.userpart, '/');
07635    if (ast_strlen_zero(pre2.userpart)) {
07636       pre2.userpart = pre2.transport;
07637       pre2.transport = NULL;
07638    } else {
07639       pre2.transport[strlen(pre2.transport) - 1] = '\0'; /* Remove trailing : */
07640    }
07641 
07642    if (!ast_strlen_zero(pre2.blank)) {
07643       ast_log(LOG_WARNING, "Format for registration is [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] at line %d\n", lineno);
07644       return -1;
07645    }
07646 
07647    /*!
07648     * pre1.peer => peer
07649     * pre2.transport = transport
07650     * user1.userpart => user[@domain]
07651     * user1.secret => secret
07652     * user1.authuser => authuser
07653     * hostpart => host[:port][/extension][~expiry]
07654     */
07655    AST_NONSTANDARD_RAW_ARGS(user1, pre2.userpart, ':');
07656 
07657    /*!
07658     * pre1.peer => peer
07659     * pre2.transport = transport
07660     * user1.userpart => user[@domain]
07661     * user1.secret => secret
07662     * user1.authuser => authuser
07663     * host1.hostpart => host[:port][/extension]
07664     * host1.expiry => [expiry]
07665     */
07666    AST_NONSTANDARD_RAW_ARGS(host1, hostpart, '~');
07667 
07668    /*!
07669     * pre1.peer => peer
07670     * pre2.transport = transport
07671     * user1.userpart => user[@domain]
07672     * user1.secret => secret
07673     * user1.authuser => authuser
07674     * host2.hostpart => host[:port]
07675     * host2.extension => [extension]
07676     * host1.expiry => [expiry]
07677     */
07678    AST_NONSTANDARD_RAW_ARGS(host2, host1.hostpart, '/');
07679 
07680    /*!
07681     * pre1.peer => peer
07682     * pre2.transport = transport
07683     * user1.userpart => user[@domain]
07684     * user1.secret => secret
07685     * user1.authuser => authuser
07686     * host3.host => host
07687     * host3.port => port
07688     * host2.extension => extension
07689     * host1.expiry => expiry
07690     */
07691    AST_NONSTANDARD_RAW_ARGS(host3, host2.hostpart, ':');
07692 
07693    if (host3.port) {
07694       if (!(portnum = port_str2int(host3.port, 0))) {
07695          ast_log(LOG_NOTICE, "'%s' is not a valid port number on line %d of sip.conf. using default.\n", host3.port, lineno);
07696       }
07697    }
07698 
07699    /* set transport type */
07700    if (!pre2.transport) {
07701       transport = SIP_TRANSPORT_UDP;
07702    } else if (!strncasecmp(pre2.transport, "tcp", 3)) {
07703       transport = SIP_TRANSPORT_TCP;
07704    } else if (!strncasecmp(pre2.transport, "tls", 3)) {
07705       transport = SIP_TRANSPORT_TLS;
07706    } else if (!strncasecmp(pre2.transport, "udp", 3)) {
07707       transport = SIP_TRANSPORT_UDP;
07708    } else {
07709       transport = SIP_TRANSPORT_UDP;
07710       ast_log(LOG_NOTICE, "'%.3s' is not a valid transport type on line %d of sip.conf. defaulting to udp.\n", pre2.transport, lineno);
07711    }
07712 
07713    /* if no portnum specified, set default for transport */
07714    if (!portnum) {
07715       if (transport == SIP_TRANSPORT_TLS) {
07716          portnum = STANDARD_TLS_PORT;
07717       } else {
07718          portnum = STANDARD_SIP_PORT;
07719       }
07720    }
07721 
07722    if (!(reg = ast_calloc(1, sizeof(*reg)))) {
07723       ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
07724       return -1;
07725    }
07726 
07727    if (ast_string_field_init(reg, 256)) {
07728       ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry strings\n");
07729       ast_free(reg);
07730       return -1;
07731    }
07732 
07733    ast_atomic_fetchadd_int(&regobjs, 1);
07734    ASTOBJ_INIT(reg);
07735    ast_string_field_set(reg, callback, ast_strip_quoted(S_OR(host2.extension, "s"), "\"", "\""));
07736    ast_string_field_set(reg, username, ast_strip_quoted(S_OR(user1.userpart, ""), "\"", "\""));
07737    ast_string_field_set(reg, hostname, ast_strip_quoted(S_OR(host3.host, ""), "\"", "\""));
07738    ast_string_field_set(reg, authuser, ast_strip_quoted(S_OR(user1.authuser, ""), "\"", "\""));
07739    ast_string_field_set(reg, secret, ast_strip_quoted(S_OR(user1.secret, ""), "\"", "\""));
07740    ast_string_field_set(reg, peername, ast_strip_quoted(S_OR(pre1.peer, ""), "\"", "\""));
07741 
07742    reg->transport = transport;
07743    reg->timeout = reg->expire = -1;
07744    reg->refresh = reg->expiry = reg->configured_expiry = (host1.expiry ? atoi(ast_strip_quoted(host1.expiry, "\"", "\"")) : default_expiry);
07745    reg->portno = portnum;
07746    reg->callid_valid = FALSE;
07747    reg->ocseq = INITIAL_CSEQ;
07748    ASTOBJ_CONTAINER_LINK(&regl, reg); /* Add the new registry entry to the list */
07749    registry_unref(reg, "unref the reg pointer");   /* release the reference given by ASTOBJ_INIT. The container has another reference */
07750    return 0;
07751 }
07752 
07753 /*! \brief Parse mwi=> line in sip.conf and add to list */
07754 static int sip_subscribe_mwi(const char *value, int lineno)
07755 {
07756    struct sip_subscription_mwi *mwi;
07757    int portnum = 0;
07758    enum sip_transport transport = SIP_TRANSPORT_UDP;
07759    char buf[256] = "";
07760    char *username = NULL, *hostname = NULL, *secret = NULL, *authuser = NULL, *porta = NULL, *mailbox = NULL;
07761    
07762    if (!value) {
07763       return -1;
07764    }
07765    
07766    ast_copy_string(buf, value, sizeof(buf));
07767 
07768    sip_parse_host(buf, lineno, &username, &portnum, &transport);
07769    
07770    if ((hostname = strrchr(username, '@'))) {
07771       *hostname++ = '\0';
07772    }
07773    
07774    if ((secret = strchr(username, ':'))) {
07775       *secret++ = '\0';
07776       if ((authuser = strchr(secret, ':'))) {
07777          *authuser++ = '\0';
07778       }
07779    }
07780    
07781    if ((mailbox = strchr(hostname, '/'))) {
07782       *mailbox++ = '\0';
07783    }
07784 
07785    if (ast_strlen_zero(username) || ast_strlen_zero(hostname) || ast_strlen_zero(mailbox)) {
07786       ast_log(LOG_WARNING, "Format for MWI subscription is user[:secret[:authuser]]@host[:port][/mailbox] at line %d\n", lineno);
07787       return -1;
07788    }
07789    
07790    if ((porta = strchr(hostname, ':'))) {
07791       *porta++ = '\0';
07792       if (!(portnum = atoi(porta))) {
07793          ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
07794          return -1;
07795       }
07796    }
07797    
07798    if (!(mwi = ast_calloc(1, sizeof(*mwi)))) {
07799       return -1;
07800    }
07801    
07802    if (ast_string_field_init(mwi, 256)) {
07803       ast_free(mwi);
07804       return -1;
07805    }
07806    
07807    ASTOBJ_INIT(mwi);
07808    ast_string_field_set(mwi, username, username);
07809    if (secret) {
07810       ast_string_field_set(mwi, secret, secret);
07811    }
07812    if (authuser) {
07813       ast_string_field_set(mwi, authuser, authuser);
07814    }
07815    ast_string_field_set(mwi, hostname, hostname);
07816    ast_string_field_set(mwi, mailbox, mailbox);
07817    mwi->resub = -1;
07818    mwi->portno = portnum;
07819    mwi->transport = transport;
07820    
07821    ASTOBJ_CONTAINER_LINK(&submwil, mwi);
07822    ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
07823    
07824    return 0;
07825 }
07826 
07827 /*! \brief  Parse multiline SIP headers into one header
07828    This is enabled if pedanticsipchecking is enabled */
07829 static int lws2sws(char *msgbuf, int len) 
07830 {
07831    int h = 0, t = 0; 
07832    int lws = 0; 
07833 
07834    for (; h < len;) { 
07835       /* Eliminate all CRs */ 
07836       if (msgbuf[h] == '\r') { 
07837          h++; 
07838          continue; 
07839       } 
07840       /* Check for end-of-line */ 
07841       if (msgbuf[h] == '\n') { 
07842          /* Check for end-of-message */ 
07843          if (h + 1 == len) 
07844             break; 
07845          /* Check for a continuation line */ 
07846          if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') { 
07847             /* Merge continuation line */ 
07848             h++; 
07849             continue; 
07850          } 
07851          /* Propagate LF and start new line */ 
07852          msgbuf[t++] = msgbuf[h++]; 
07853          lws = 0;
07854          continue; 
07855       } 
07856       if (msgbuf[h] == ' ' || msgbuf[h] == '\t') { 
07857          if (lws) { 
07858             h++; 
07859             continue; 
07860          } 
07861          msgbuf[t++] = msgbuf[h++]; 
07862          lws = 1; 
07863          continue; 
07864       } 
07865       msgbuf[t++] = msgbuf[h++]; 
07866       if (lws) 
07867          lws = 0; 
07868    } 
07869    msgbuf[t] = '\0'; 
07870    return t; 
07871 }
07872 
07873 /*! \brief Parse a SIP message 
07874    \note this function is used both on incoming and outgoing packets
07875 */
07876 static int parse_request(struct sip_request *req)
07877 {
07878    char *c = req->data->str;
07879    ptrdiff_t *dst = req->header;
07880    int i = 0, lim = SIP_MAX_HEADERS - 1;
07881    unsigned int skipping_headers = 0;
07882    ptrdiff_t current_header_offset = 0;
07883    char *previous_header = "";
07884 
07885    req->header[0] = 0;
07886    req->headers = -1;   /* mark that we are working on the header */
07887    for (; *c; c++) {
07888       if (*c == '\r') {    /* remove \r */
07889          *c = '\0';
07890       } else if (*c == '\n') {   /* end of this line */
07891          *c = '\0';
07892          current_header_offset = (c + 1) - req->data->str;
07893          previous_header = req->data->str + dst[i];
07894          if (skipping_headers) {
07895             /* check to see if this line is blank; if so, turn off
07896                the skipping flag, so the next line will be processed
07897                as a body line */
07898             if (ast_strlen_zero(previous_header)) {
07899                skipping_headers = 0;
07900             }
07901             dst[i] = current_header_offset; /* record start of next line */
07902             continue;
07903          }
07904          if (sipdebug) {
07905             ast_debug(4, "%7s %2d [%3d]: %s\n",
07906                  req->headers < 0 ? "Header" : "Body",
07907                  i, (int) strlen(previous_header), previous_header);
07908          }
07909          if (ast_strlen_zero(previous_header) && req->headers < 0) {
07910             req->headers = i; /* record number of header lines */
07911             dst = req->line;  /* start working on the body */
07912             i = 0;
07913             lim = SIP_MAX_LINES - 1;
07914          } else { /* move to next line, check for overflows */
07915             if (i++ == lim) {
07916                /* if we're processing headers, then skip any remaining
07917                   headers and move on to processing the body, otherwise
07918                   we're done */
07919                if (req->headers != -1) {
07920                   break;
07921                } else {
07922                   req->headers = i;
07923                   dst = req->line;
07924                   i = 0;
07925                   lim = SIP_MAX_LINES - 1;
07926                   skipping_headers = 1;
07927                }
07928             }
07929          }
07930          dst[i] = current_header_offset; /* record start of next line */
07931       }
07932    }
07933 
07934    /* Check for last header or body line without CRLF. The RFC for SDP requires CRLF,
07935       but since some devices send without, we'll be generous in what we accept. However,
07936       if we've already reached the maximum number of lines for portion of the message
07937       we were parsing, we can't accept any more, so just ignore it.
07938    */
07939    previous_header = req->data->str + dst[i];
07940    if ((i < lim) && !ast_strlen_zero(previous_header)) {
07941       if (sipdebug) {
07942          ast_debug(4, "%7s %2d [%3d]: %s\n",
07943               req->headers < 0 ? "Header" : "Body",
07944               i, (int) strlen(previous_header), previous_header );
07945       }
07946       i++;
07947    }
07948 
07949    /* update count of header or body lines */
07950    if (req->headers >= 0) {   /* we are in the body */
07951       req->lines = i;
07952    } else {       /* no body */
07953       req->headers = i;
07954       req->lines = 0;
07955       /* req->data->used will be a NULL byte */
07956       req->line[0] = ast_str_strlen(req->data);
07957    }
07958 
07959    if (*c) {
07960       ast_log(LOG_WARNING, "Too many lines, skipping <%s>\n", c);
07961    }
07962 
07963    /* Split up the first line parts */
07964    return determine_firstline_parts(req);
07965 }
07966 
07967 /*!
07968   \brief Determine whether a SIP message contains an SDP in its body
07969   \param req the SIP request to process
07970   \return 1 if SDP found, 0 if not found
07971 
07972   Also updates req->sdp_start and req->sdp_count to indicate where the SDP
07973   lives in the message body.
07974 */
07975 static int find_sdp(struct sip_request *req)
07976 {
07977    const char *content_type;
07978    const char *content_length;
07979    const char *search;
07980    char *boundary;
07981    unsigned int x;
07982    int boundaryisquoted = FALSE;
07983    int found_application_sdp = FALSE;
07984    int found_end_of_headers = FALSE;
07985 
07986    content_length = get_header(req, "Content-Length");
07987 
07988    if (!ast_strlen_zero(content_length)) {
07989       if (sscanf(content_length, "%30u", &x) != 1) {
07990          ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
07991          return 0;
07992       }
07993 
07994       /* Content-Length of zero means there can't possibly be an
07995          SDP here, even if the Content-Type says there is */
07996       if (x == 0)
07997          return 0;
07998    }
07999 
08000    content_type = get_header(req, "Content-Type");
08001 
08002    /* if the body contains only SDP, this is easy */
08003    if (!strncasecmp(content_type, "application/sdp", 15)) {
08004       req->sdp_start = 0;
08005       req->sdp_count = req->lines;
08006       return req->lines ? 1 : 0;
08007    }
08008 
08009    /* if it's not multipart/mixed, there cannot be an SDP */
08010    if (strncasecmp(content_type, "multipart/mixed", 15))
08011       return 0;
08012 
08013    /* if there is no boundary marker, it's invalid */
08014    if ((search = strcasestr(content_type, ";boundary=")))
08015       search += 10;
08016    else if ((search = strcasestr(content_type, "; boundary=")))
08017       search += 11;
08018    else
08019       return 0;
08020 
08021    if (ast_strlen_zero(search))
08022       return 0;
08023 
08024    /* If the boundary is quoted with ", remove quote */
08025    if (*search == '\"')  {
08026       search++;
08027       boundaryisquoted = TRUE;
08028    }
08029 
08030    /* make a duplicate of the string, with two extra characters
08031       at the beginning */
08032    boundary = ast_strdupa(search - 2);
08033    boundary[0] = boundary[1] = '-';
08034    /* Remove final quote */
08035    if (boundaryisquoted)
08036       boundary[strlen(boundary) - 1] = '\0';
08037 
08038    /* search for the boundary marker, the empty line delimiting headers from
08039       sdp part and the end boundry if it exists */
08040 
08041    for (x = 0; x < (req->lines); x++) {
08042       char *line = REQ_OFFSET_TO_STR(req, line[x]);
08043       if (!strncasecmp(line, boundary, strlen(boundary))){
08044          if (found_application_sdp && found_end_of_headers) {
08045             req->sdp_count = (x - 1) - req->sdp_start;
08046             return 1;
08047          }
08048          found_application_sdp = FALSE;
08049       }
08050       if (!strcasecmp(line, "Content-Type: application/sdp"))
08051          found_application_sdp = TRUE;
08052       
08053       if (ast_strlen_zero(line)) {
08054          if (found_application_sdp && !found_end_of_headers){
08055             req->sdp_start = x;
08056             found_end_of_headers = TRUE;
08057          }
08058       }
08059    }
08060    if (found_application_sdp && found_end_of_headers) {
08061       req->sdp_count = x - req->sdp_start;
08062       return TRUE;
08063    }
08064    return FALSE;
08065 }
08066 
08067 enum media_type {
08068    SDP_AUDIO,
08069    SDP_VIDEO,
08070    SDP_IMAGE,
08071    SDP_TEXT,
08072 };
08073 
08074 static int get_ip_and_port_from_sdp(struct sip_request *req, const enum media_type media, struct sockaddr_in *sin)
08075 {
08076    const char *m;
08077    const char *c;
08078    int miterator = req->sdp_start;
08079    int citerator = req->sdp_start;
08080    int x = 0;
08081    int numberofports;
08082    int len;
08083    char host[258] = ""; /*Initialize to empty so we will know if we have any input */
08084    struct ast_hostent audiohp;
08085    struct hostent *hp;
08086 
08087    c = get_sdp_iterate(&citerator, req, "c");
08088    if (sscanf(c, "IN IP4 %256s", host) != 1) {
08089       ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
08090       /* Continue since there may be a valid host in a c= line specific to the audio stream */
08091    }
08092    /* We only want the m and c lines for audio */
08093    for (m = get_sdp_iterate(&miterator, req, "m"); !ast_strlen_zero(m); m = get_sdp_iterate(&miterator, req, "m")) {
08094       if ((media == SDP_AUDIO && ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08095           (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0))) ||
08096          (media == SDP_VIDEO && ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08097           (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len > 0)))) {
08098          /* See if there's a c= line for this media stream.
08099           * XXX There is no guarantee that we'll be grabbing the c= line for this
08100           * particular media stream here. However, this is the same logic used in process_sdp.
08101           */
08102          c = get_sdp_iterate(&citerator, req, "c");
08103          if (!ast_strlen_zero(c)) {
08104             sscanf(c, "IN IP4 %256s", host);
08105          }
08106          break;
08107       }
08108    }
08109 
08110    if (ast_strlen_zero(host) || x == 0) {
08111       ast_log(LOG_WARNING, "Failed to read an alternate host or port in SDP. Expect %s problems\n", media == SDP_AUDIO ? "audio" : "video");
08112       return -1;
08113    }
08114 
08115    hp = ast_gethostbyname(host, &audiohp);
08116    if (!hp) {
08117       ast_log(LOG_WARNING, "Could not look up IP address of alternate hostname. Expect %s problems\n", media == SDP_AUDIO? "audio" : "video");
08118       return -1;
08119    }
08120 
08121    memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
08122    sin->sin_port = htons(x);
08123    return 0;
08124 }
08125 
08126 /*! \brief Process SIP SDP offer, select formats and activate RTP channels
08127    If offer is rejected, we will not change any properties of the call
08128    Return 0 on success, a negative value on errors.
08129    Must be called after find_sdp().
08130 */
08131 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
08132 {
08133    /* Iterators for SDP parsing */
08134    int start = req->sdp_start;
08135    int next = start;
08136    int iterator = start;
08137 
08138    /* Temporary vars for SDP parsing */
08139    char type = '\0';
08140    const char *value = NULL;
08141    const char *m = NULL;           /* SDP media offer */
08142    const char *nextm = NULL;
08143    int len = -1;
08144 
08145    /* Host information */
08146    struct ast_hostent sessionhp;
08147    struct ast_hostent audiohp;
08148    struct ast_hostent videohp;
08149    struct ast_hostent texthp;
08150    struct ast_hostent imagehp;
08151    struct hostent *hp = NULL; /*!< RTP Audio host IP */
08152    struct hostent *vhp = NULL;   /*!< RTP video host IP */
08153    struct hostent *thp = NULL;   /*!< RTP text host IP */
08154    struct hostent *ihp = NULL;     /*!< UDPTL host ip */
08155    int portno = -1;     /*!< RTP Audio port number */
08156    int vportno = -1;    /*!< RTP Video port number */
08157    int tportno = -1;    /*!< RTP Text port number */
08158    int udptlportno = -1;      /*!< UDPTL Image port number */
08159    struct sockaddr_in sin = { 0, }; /*!< media socket address */
08160    struct sockaddr_in vsin = { 0, };   /*!< video socket address */
08161    struct sockaddr_in isin = { 0, };   /*!< image socket address */
08162    struct sockaddr_in tsin = { 0, };   /*!< text socket address */
08163 
08164    /* Peer capability is the capability in the SDP, non codec is RFC2833 DTMF (101) */ 
08165    int peercapability = 0, peernoncodeccapability = 0;
08166    int vpeercapability = 0, vpeernoncodeccapability = 0;
08167    int tpeercapability = 0, tpeernoncodeccapability = 0;
08168 
08169    struct ast_rtp *newaudiortp, *newvideortp, *newtextrtp;
08170    int newjointcapability;          /* Negotiated capability */
08171    int newpeercapability;
08172    int newnoncodeccapability;
08173 
08174    const char *codecs;
08175    int codec;
08176 
08177    /* Others */
08178    int sendonly = -1;
08179    int vsendonly = -1;
08180    int numberofports;
08181    int numberofmediastreams = 0;
08182    int last_rtpmap_codec = 0;
08183    int red_data_pt[10];    /* For T.140 red */
08184    int red_num_gen = 0;    /* For T.140 red */
08185    char red_fmtp[100] = "empty"; /* For T.140 red */
08186    int debug = sip_debug_test_pvt(p);
08187 
08188    /* START UNKNOWN */
08189    char buf[SIPBUFSIZE];
08190    /* END UNKNOWN */
08191 
08192    /* Initial check */
08193    if (!p->rtp) {
08194       ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
08195       return -1;
08196    }
08197 
08198    /* Initialize the temporary RTP structures we use to evaluate the offer from the peer */
08199 #ifdef LOW_MEMORY
08200    newaudiortp = ast_threadstorage_get(&ts_audio_rtp, ast_rtp_alloc_size());
08201 #else
08202    newaudiortp = alloca(ast_rtp_alloc_size());
08203 #endif
08204    memset(newaudiortp, 0, ast_rtp_alloc_size());
08205    ast_rtp_new_init(newaudiortp);
08206    ast_rtp_pt_clear(newaudiortp);
08207 
08208 #ifdef LOW_MEMORY
08209    newvideortp = ast_threadstorage_get(&ts_video_rtp, ast_rtp_alloc_size());
08210 #else
08211    newvideortp = alloca(ast_rtp_alloc_size());
08212 #endif
08213    memset(newvideortp, 0, ast_rtp_alloc_size());
08214    ast_rtp_new_init(newvideortp);
08215    ast_rtp_pt_clear(newvideortp);
08216 
08217 #ifdef LOW_MEMORY
08218    newtextrtp = ast_threadstorage_get(&ts_text_rtp, ast_rtp_alloc_size());
08219 #else
08220    newtextrtp = alloca(ast_rtp_alloc_size());
08221 #endif
08222    memset(newtextrtp, 0, ast_rtp_alloc_size());
08223    ast_rtp_new_init(newtextrtp);
08224    ast_rtp_pt_clear(newtextrtp);
08225 
08226    /* Update our last rtprx when we receive an SDP, too */
08227    p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
08228 
08229    memset(p->offered_media, 0, sizeof(p->offered_media));
08230 
08231 
08232    /* default: novideo and notext set */
08233    p->novideo = TRUE;
08234    p->notext = TRUE;
08235 
08236    if (p->vrtp)
08237       ast_rtp_pt_clear(newvideortp);  /* Must be cleared in case no m=video line exists */
08238  
08239    if (p->trtp)
08240       ast_rtp_pt_clear(newtextrtp);  /* Must be cleared in case no m=text line exists */
08241    
08242    /* Scan for the first media stream (m=) line to limit scanning of globals */
08243    nextm = get_sdp_iterate(&next, req, "m");
08244    if (ast_strlen_zero(nextm)) {
08245       ast_log(LOG_WARNING, "Insufficient information for SDP (m= not found)\n");
08246       return -1;
08247    }
08248 
08249    /* Scan session level SDP parameters (lines before first media stream) */
08250    while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
08251       int processed = FALSE;
08252       switch (type) {
08253       case 'o':
08254          /* If we end up receiving SDP that doesn't actually modify the session we don't want to treat this as a fatal
08255           * error. We just want to ignore the SDP and let the rest of the packet be handled as normal.
08256           */
08257          if (!process_sdp_o(value, p))
08258             return (p->session_modify == FALSE) ? 0 : -1;
08259          break;
08260       case 'c':
08261          if (process_sdp_c(value, &sessionhp)) {
08262             processed = TRUE;
08263             hp = &sessionhp.hp;
08264             vhp = hp;
08265             thp = hp;
08266             ihp = hp;
08267          }
08268          break;
08269       case 'a':
08270          if (process_sdp_a_sendonly(value, &sendonly)) {
08271             processed = TRUE;
08272             vsendonly = sendonly;
08273          }
08274          else if (process_sdp_a_audio(value, p, newaudiortp, &last_rtpmap_codec))
08275             processed = TRUE;
08276          else if (process_sdp_a_video(value, p, newvideortp, &last_rtpmap_codec))
08277             processed = TRUE;
08278          else if (process_sdp_a_text(value, p, newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
08279             processed = TRUE;
08280          else if (process_sdp_a_image(value, p))
08281             processed = TRUE;
08282          break;
08283       }
08284 
08285       if (option_debug > 2)
08286          ast_log(LOG_DEBUG, "Processing session-level SDP %c=%s... %s\n", type, value, (processed == TRUE)? "OK." : "UNSUPPORTED.");
08287    }
08288 
08289 
08290 
08291    /* Scan media stream (m=) specific parameters loop */
08292    while (!ast_strlen_zero(nextm)) {
08293       int audio = FALSE;
08294       int video = FALSE;
08295       int image = FALSE;
08296       int text = FALSE;
08297       int x;
08298 
08299       numberofports = 1;
08300       len = -1;
08301       start = next;
08302       m = nextm;
08303       iterator = next;
08304       nextm = get_sdp_iterate(&next, req, "m");
08305 
08306       /* Search for audio media definition */
08307       if ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08308           (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
08309          audio = TRUE;
08310          p->offered_media[SDP_AUDIO].offered = TRUE;
08311          numberofmediastreams++;
08312          portno = x;
08313 
08314          /* Scan through the RTP payload types specified in a "m=" line: */
08315          codecs = m + len;
08316          ast_copy_string(p->offered_media[SDP_AUDIO].text, codecs, sizeof(p->offered_media[SDP_AUDIO].text));
08317          for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08318             if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08319                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08320                return -1;
08321             }
08322             if (debug)
08323                ast_verbose("Found RTP audio format %d\n", codec);
08324 
08325             ast_rtp_set_m_type(newaudiortp, codec);
08326          }
08327       /* Search for video media definition */
08328       } else if ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08329             (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len >= 0)) {
08330          video = TRUE;
08331          p->novideo = FALSE;
08332          p->offered_media[SDP_VIDEO].offered = TRUE;
08333          numberofmediastreams++;
08334          vportno = x;
08335 
08336          /* Scan through the RTP payload types specified in a "m=" line: */
08337          codecs = m + len;
08338          ast_copy_string(p->offered_media[SDP_VIDEO].text, codecs, sizeof(p->offered_media[SDP_VIDEO].text));
08339          for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08340             if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08341                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08342                return -1;
08343             }
08344             if (debug)
08345                ast_verbose("Found RTP video format %d\n", codec);
08346             ast_rtp_set_m_type(newvideortp, codec);
08347          }
08348       /* Search for text media definition */
08349       } else if ((sscanf(m, "text %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08350             (sscanf(m, "text %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
08351          text = TRUE;
08352          p->notext = FALSE;
08353          p->offered_media[SDP_TEXT].offered = TRUE;
08354          numberofmediastreams++;
08355          tportno = x;
08356 
08357          /* Scan through the RTP payload types specified in a "m=" line: */
08358          codecs = m + len;
08359          ast_copy_string(p->offered_media[SDP_TEXT].text, codecs, sizeof(p->offered_media[SDP_TEXT].text));
08360          for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08361             if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08362                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08363                return -1;
08364             }
08365             if (debug)
08366                ast_verbose("Found RTP text format %d\n", codec);
08367             ast_rtp_set_m_type(newtextrtp, codec);
08368          }
08369       /* Search for image media definition */
08370       } else if (p->udptl && ((sscanf(m, "image %30u udptl t38%n", &x, &len) == 1 && len > 0) ||
08371                (sscanf(m, "image %30u UDPTL t38%n", &x, &len) == 1 && len > 0) )) {
08372          image = TRUE;
08373          if (debug)
08374             ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
08375          p->offered_media[SDP_IMAGE].offered = TRUE;
08376          udptlportno = x;
08377          numberofmediastreams++;
08378 
08379          if (p->t38.state != T38_ENABLED) {
08380             memset(&p->t38.their_parms, 0, sizeof(p->t38.their_parms));
08381 
08382             /* default EC to none, the remote end should
08383              * respond with the EC they want to use */
08384             ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
08385          }
08386       } else {
08387          ast_log(LOG_WARNING, "Unsupported SDP media type in offer: %s\n", m);
08388          continue;
08389       }
08390 
08391       /* Check for number of ports */
08392       if (numberofports > 1)
08393          ast_log(LOG_WARNING, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports);
08394       
08395 
08396 
08397       /* Media stream specific parameters */
08398       while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
08399          int processed = FALSE;
08400 
08401          switch (type) {
08402          case 'c':
08403             if (audio) {
08404                if (process_sdp_c(value, &audiohp)) {
08405                   processed = TRUE;
08406                   hp = &audiohp.hp;
08407                }
08408             } else if (video) {
08409                if (process_sdp_c(value, &videohp)) {
08410                   processed = TRUE;
08411                   vhp = &videohp.hp;
08412                }
08413             } else if (text) {
08414                if (process_sdp_c(value, &texthp)) {
08415                   processed = TRUE;
08416                   thp = &texthp.hp;
08417                }
08418             } else if (image) {
08419                if (process_sdp_c(value, &imagehp)) {
08420                   processed = TRUE;
08421                   ihp = &imagehp.hp;
08422                }
08423             }
08424             break;
08425          case 'a':
08426             /* Audio specific scanning */
08427             if (audio) {
08428                if (process_sdp_a_sendonly(value, &sendonly))
08429                   processed = TRUE;
08430                else if (process_sdp_a_audio(value, p, newaudiortp, &last_rtpmap_codec))
08431                   processed = TRUE;
08432             }
08433             /* Video specific scanning */
08434             else if (video) {
08435                if (process_sdp_a_sendonly(value, &vsendonly))
08436                   processed = TRUE;
08437                else if (process_sdp_a_video(value, p, newvideortp, &last_rtpmap_codec))
08438                   processed = TRUE;
08439             }
08440             /* Text (T.140) specific scanning */
08441             else if (text) {
08442                if (process_sdp_a_text(value, p, newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
08443                   processed = TRUE;
08444             }
08445             /* Image (T.38 FAX) specific scanning */
08446             else if (image) {
08447                if (process_sdp_a_image(value, p))
08448                   processed = TRUE;
08449             }
08450             break;
08451          }
08452 
08453          if (option_debug > 2)
08454             ast_log(LOG_DEBUG, "Processing media-level (%s) SDP %c=%s... %s\n",
08455                   (audio == TRUE)? "audio" : (video == TRUE)? "video" : "image",
08456                   type, value,
08457                   (processed == TRUE)? "OK." : "UNSUPPORTED.");
08458       }
08459    }
08460 
08461 
08462    /* Sanity checks */
08463    if (!hp && !vhp && !thp && !ihp) {
08464       ast_log(LOG_WARNING, "Insufficient information in SDP (c=)...\n");
08465       return -1;
08466    }
08467 
08468    if (portno == -1 && vportno == -1 && udptlportno == -1  && tportno == -1)
08469       /* No acceptable offer found in SDP  - we have no ports */
08470       /* Do not change RTP or VRTP if this is a re-invite */
08471       return -2;
08472 
08473    if (numberofmediastreams > 3)
08474       /* We have too many fax, audio and/or video and/or text media streams, fail this offer */
08475       return -3;
08476 
08477    if (udptlportno == -1) {
08478       change_t38_state(p, T38_DISABLED);
08479    }
08480 
08481 
08482    /* Now gather all of the codecs that we are asked for: */
08483    ast_rtp_get_current_formats(newaudiortp, &peercapability, &peernoncodeccapability);
08484    ast_rtp_get_current_formats(newvideortp, &vpeercapability, &vpeernoncodeccapability);
08485    ast_rtp_get_current_formats(newtextrtp, &tpeercapability, &tpeernoncodeccapability);
08486 
08487    newjointcapability = p->capability & (peercapability | vpeercapability | tpeercapability);
08488    newpeercapability = (peercapability | vpeercapability | tpeercapability);
08489    newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
08490 
08491    if (debug) {
08492       /* shame on whoever coded this.... */
08493       char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE], s5[SIPBUFSIZE];
08494 
08495       ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s/text=%s, combined - %s\n",
08496              ast_getformatname_multiple(s1, SIPBUFSIZE, p->capability),
08497              ast_getformatname_multiple(s2, SIPBUFSIZE, peercapability),
08498              ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
08499              ast_getformatname_multiple(s4, SIPBUFSIZE, tpeercapability),
08500              ast_getformatname_multiple(s5, SIPBUFSIZE, newjointcapability));
08501 
08502       ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
08503              ast_rtp_lookup_mime_multiple(s1, SIPBUFSIZE, p->noncodeccapability, 0, 0),
08504              ast_rtp_lookup_mime_multiple(s2, SIPBUFSIZE, peernoncodeccapability, 0, 0),
08505              ast_rtp_lookup_mime_multiple(s3, SIPBUFSIZE, newnoncodeccapability, 0, 0));
08506    }
08507    if (!newjointcapability && (portno != -1)) {
08508       ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
08509       /* Do NOT Change current setting */
08510       return -1;
08511    }
08512 
08513    /* Setup audio address and port */
08514    if (p->rtp) {
08515       if (portno > 0) {
08516          sin.sin_family = AF_INET;
08517          sin.sin_port = htons(portno);
08518          memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
08519          ast_rtp_set_peer(p->rtp, &sin);
08520          if (debug)
08521             ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
08522          /* We are now ready to change the sip session and p->rtp and p->vrtp with the offered codecs, since                                                                                                    
08523             they are acceptable */
08524          p->jointcapability = newjointcapability;                /* Our joint codec profile for this call */
08525          p->peercapability = newpeercapability;                  /* The other sides capability in latest offer */
08526          p->jointnoncodeccapability = newnoncodeccapability;     /* DTMF capabilities */
08527 
08528          ast_rtp_pt_copy(p->rtp, newaudiortp);
08529 
08530          if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
08531             ast_clear_flag(&p->flags[0], SIP_DTMF);
08532             if (newnoncodeccapability & AST_RTP_DTMF) {
08533                /* XXX Would it be reasonable to drop the DSP at this point? XXX */
08534                ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
08535                /* Since RFC2833 is now negotiated we need to change some properties of the RTP stream */
08536                ast_rtp_setdtmf(p->rtp, 1);
08537                ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
08538             } else {
08539                ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
08540             }
08541          }
08542       } else if (udptlportno > 0) {
08543          if (debug)
08544             ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session.\n");
08545       } else {
08546          ast_rtp_stop(p->rtp);
08547          if (debug)
08548             ast_verbose("Peer doesn't provide audio\n");
08549       }
08550    }
08551 
08552    /* Setup video address and port */
08553    if (p->vrtp) {
08554       if (vportno > 0) {
08555          vsin.sin_family = AF_INET;
08556          vsin.sin_port = htons(vportno);
08557          memcpy(&vsin.sin_addr, vhp->h_addr, sizeof(vsin.sin_addr));
08558          ast_rtp_set_peer(p->vrtp, &vsin);
08559          if (debug) 
08560             ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(vsin.sin_addr), ntohs(vsin.sin_port));
08561          ast_rtp_pt_copy(p->vrtp, newvideortp);
08562       } else {
08563          ast_rtp_stop(p->vrtp);
08564          if (debug)
08565             ast_verbose("Peer doesn't provide video\n");
08566       }
08567    }
08568 
08569    /* Setup text address and port */
08570    if (p->trtp) {
08571       if (tportno > 0) {
08572          tsin.sin_family = AF_INET;
08573          tsin.sin_port = htons(tportno);
08574          memcpy(&tsin.sin_addr, thp->h_addr, sizeof(tsin.sin_addr));
08575          ast_rtp_set_peer(p->trtp, &tsin);
08576          if (debug) 
08577             ast_verbose("Peer T.140 RTP is at port %s:%d\n", ast_inet_ntoa(tsin.sin_addr), ntohs(tsin.sin_port));
08578          if ((p->jointcapability & AST_FORMAT_T140RED)) {
08579             p->red = 1;
08580             rtp_red_init(p->trtp, 300, red_data_pt, 2);
08581          } else {
08582             p->red = 0;
08583          }
08584          ast_rtp_pt_copy(p->trtp, newtextrtp);
08585       } else {
08586          ast_rtp_stop(p->trtp);
08587          if (debug)
08588             ast_verbose("Peer doesn't provide T.140\n");
08589       }
08590    }
08591    /* Setup image address and port */
08592    if (p->udptl) {
08593       if (udptlportno > 0) {
08594          isin.sin_family = AF_INET;
08595          isin.sin_port = htons(udptlportno);
08596          if (ast_test_flag(&p->flags[0], SIP_NAT) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
08597             struct sockaddr_in remote_address = { 0, };
08598             ast_rtp_get_peer(p->rtp, &remote_address);
08599             if (remote_address.sin_addr.s_addr) {
08600                memcpy(&isin, &remote_address, sizeof(isin));
08601                if (debug) {
08602                   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));
08603                }
08604             }
08605          } else {
08606             memcpy(&isin.sin_addr, ihp->h_addr, sizeof(isin.sin_addr));
08607          }
08608          ast_udptl_set_peer(p->udptl, &isin);
08609          if (debug)
08610             ast_debug(1,"Peer T.38 UDPTL is at port %s:%d\n", ast_inet_ntoa(isin.sin_addr), ntohs(isin.sin_port));
08611 
08612          /* verify the far max ifp can be calculated. this requires far max datagram to be set. */
08613          if (!ast_udptl_get_far_max_datagram(p->udptl)) {
08614             /* setting to zero will force a default if none was provided by the SDP */
08615             ast_udptl_set_far_max_datagram(p->udptl, 0);
08616          }
08617 
08618          /* Remote party offers T38, we need to update state */
08619          if ((t38action == SDP_T38_ACCEPT) &&
08620              (p->t38.state == T38_LOCAL_REINVITE)) {
08621             change_t38_state(p, T38_ENABLED);
08622          } else if ((t38action == SDP_T38_INITIATE) &&
08623                p->owner && p->lastinvite) {
08624             change_t38_state(p, T38_PEER_REINVITE); /* T38 Offered in re-invite from remote party */
08625             /* If fax detection is enabled then send us off to the fax extension */
08626             if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38)) {
08627                ast_channel_lock(p->owner);
08628                if (strcmp(p->owner->exten, "fax")) {
08629                   const char *target_context = S_OR(p->owner->macrocontext, p->owner->context);
08630                   ast_channel_unlock(p->owner);
08631                   if (ast_exists_extension(p->owner, target_context, "fax", 1, p->owner->cid.cid_num)) {
08632                      ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to peer T.38 re-INVITE\n", p->owner->name);
08633                      pbx_builtin_setvar_helper(p->owner, "FAXEXTEN", p->owner->exten);
08634                      if (ast_async_goto(p->owner, target_context, "fax", 1)) {
08635                         ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", p->owner->name, target_context);
08636                      }
08637                   } else {
08638                      ast_log(LOG_NOTICE, "T.38 re-INVITE detected but no fax extension\n");
08639                   }
08640                } else {
08641                   ast_channel_unlock(p->owner);
08642                }
08643             }
08644          }
08645       } else {
08646          ast_udptl_stop(p->udptl);
08647          if (debug)
08648             ast_debug(1, "Peer doesn't provide T.38 UDPTL\n");
08649       }
08650    }
08651 
08652    if ((portno == -1) && (p->t38.state != T38_DISABLED)) {
08653       ast_debug(3, "Have T.38 but no audio, accepting offer anyway\n");
08654                 return 0;
08655         }
08656 
08657    /* Ok, we're going with this offer */
08658    ast_debug(2, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcapability));
08659 
08660    if (!p->owner)    /* There's no open channel owning us so we can return here. For a re-invite or so, we proceed */
08661       return 0;
08662 
08663    ast_debug(4, "We have an owner, now see if we need to change this call\n");
08664 
08665    if (!(p->owner->nativeformats & p->jointcapability) && (p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
08666       if (debug) {
08667          char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
08668          ast_debug(1, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n", 
08669             ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcapability),
08670             ast_getformatname_multiple(s2, SIPBUFSIZE, p->owner->nativeformats));
08671       }
08672       p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability) | (p->capability & tpeercapability);
08673       ast_set_read_format(p->owner, p->owner->readformat);
08674       ast_set_write_format(p->owner, p->owner->writeformat);
08675    }
08676    
08677    if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)
08678          && (sin.sin_addr.s_addr || vsin.sin_addr.s_addr ||
08679          isin.sin_addr.s_addr || tsin.sin_addr.s_addr)
08680          && (!sendonly || sendonly == -1)) {
08681       ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
08682       /* Activate a re-invite */
08683       ast_queue_frame(p->owner, &ast_null_frame);
08684       /* Queue Manager Unhold event */
08685       append_history(p, "Unhold", "%s", req->data->str);
08686       if (sip_cfg.callevents)
08687          manager_event(EVENT_FLAG_CALL, "Hold",
08688                   "Status: Off\r\n"
08689                   "Channel: %s\r\n"
08690                   "Uniqueid: %s\r\n",
08691                   p->owner->name,
08692                   p->owner->uniqueid);
08693       if (sip_cfg.notifyhold)
08694          sip_peer_hold(p, FALSE);
08695       ast_clear_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD); /* Clear both flags */
08696    } else if (!(sin.sin_addr.s_addr || vsin.sin_addr.s_addr ||
08697          isin.sin_addr.s_addr || tsin.sin_addr.s_addr)
08698          || (sendonly && sendonly != -1)) {
08699       int already_on_hold = ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD);
08700       ast_queue_control_data(p->owner, AST_CONTROL_HOLD, 
08701                    S_OR(p->mohsuggest, NULL),
08702                    !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
08703       if (sendonly)
08704          ast_rtp_stop(p->rtp);
08705       /* RTCP needs to go ahead, even if we're on hold!!! */
08706       /* Activate a re-invite */
08707       ast_queue_frame(p->owner, &ast_null_frame);
08708       /* Queue Manager Hold event */
08709       append_history(p, "Hold", "%s", req->data->str);
08710       if (sip_cfg.callevents && !ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
08711          manager_event(EVENT_FLAG_CALL, "Hold",
08712                   "Status: On\r\n"
08713                   "Channel: %s\r\n"
08714                   "Uniqueid: %s\r\n",
08715                   p->owner->name, 
08716                   p->owner->uniqueid);
08717       }
08718       if (sendonly == 1)   /* One directional hold (sendonly/recvonly) */
08719          ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
08720       else if (sendonly == 2) /* Inactive stream */
08721          ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
08722       else
08723          ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
08724       if (sip_cfg.notifyhold && !already_on_hold)
08725          sip_peer_hold(p, TRUE);
08726    }
08727    
08728    return 0;
08729 }
08730 
08731 static int process_sdp_o(const char *o, struct sip_pvt *p)
08732 {
08733    char *o_copy;
08734    char *token;
08735    int64_t rua_version;
08736 
08737    /* Store the SDP version number of remote UA. This will allow us to
08738    distinguish between session modifications and session refreshes. If
08739    the remote UA does not send an incremented SDP version number in a
08740    subsequent RE-INVITE then that means its not changing media session.
08741    The RE-INVITE may have been sent to update connected party, remote
08742    target or to refresh the session (Session-Timers).  Asterisk must not
08743    change media session and increment its own version number in answer
08744    SDP in this case. */
08745 
08746    p->session_modify = TRUE;
08747 
08748    if (ast_strlen_zero(o)) {
08749       ast_log(LOG_WARNING, "SDP syntax error. SDP without an o= line\n");
08750       return FALSE;
08751    }
08752 
08753    o_copy = ast_strdupa(o);
08754    token = strsep(&o_copy, " ");  /* Skip username   */
08755    if (!o_copy) {
08756       ast_log(LOG_WARNING, "SDP syntax error in o= line username\n");
08757       return FALSE;
08758    }
08759    token = strsep(&o_copy, " ");  /* Skip session-id */
08760    if (!o_copy) {
08761       ast_log(LOG_WARNING, "SDP syntax error in o= line session-id\n");
08762       return FALSE;
08763    }
08764    token = strsep(&o_copy, " ");  /* Version         */
08765    if (!o_copy) {
08766       ast_log(LOG_WARNING, "SDP syntax error in o= line\n");
08767       return FALSE;
08768    }
08769    if (!sscanf(token, "%30" SCNd64, &rua_version)) {
08770       ast_log(LOG_WARNING, "SDP syntax error in o= line version\n");
08771       return FALSE;
08772    }
08773 
08774    /* we need to check the SDP version number the other end sent us;
08775     * our rules for deciding what to accept are a bit complex.
08776     *
08777     * 1) if 'ignoresdpversion' has been set for this dialog, then
08778     *    we will just accept whatever they sent and assume it is
08779     *    a modification of the session, even if it is not
08780     * 2) otherwise, if this is the first SDP we've seen from them
08781     *    we accept it
08782     * 3) otherwise, if the new SDP version number is higher than the
08783     *    old one, we accept it
08784     * 4) otherwise, if this SDP is in response to us requesting a switch
08785     *    to T.38, we accept the SDP, but also generate a warning message
08786     *    that this peer should have the 'ignoresdpversion' option set,
08787     *    because it is not following the SDP offer/answer RFC; if we did
08788     *    not request a switch to T.38, then we stop parsing the SDP, as it
08789     *    has not changed from the previous version
08790     */
08791 
08792    if (ast_test_flag(&p->flags[1], SIP_PAGE2_IGNORESDPVERSION) ||
08793        (p->sessionversion_remote < 0) ||
08794        (p->sessionversion_remote < rua_version)) {
08795       p->sessionversion_remote = rua_version;
08796    } else {
08797       if (p->t38.state == T38_LOCAL_REINVITE) {
08798          p->sessionversion_remote = rua_version;
08799          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);
08800       } else {
08801          p->session_modify = FALSE;
08802          ast_debug(2, "Call %s responded to our reinvite without changing SDP version; ignoring SDP.\n", p->callid);
08803          return FALSE;
08804       }
08805    }
08806 
08807    return TRUE;
08808 }
08809 
08810 static int process_sdp_c(const char *c, struct ast_hostent *ast_hp)
08811 {
08812    char host[258];
08813    struct hostent *hp;
08814 
08815    /* Check for Media-description-level-address */
08816    if (sscanf(c, "IN IP4 %255s", host) != 1) {
08817       ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
08818       return FALSE;
08819    } else {
08820       if (!(hp = ast_gethostbyname(host, ast_hp))) {
08821          ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in c= line, '%s'\n", c);
08822          return FALSE;
08823       }
08824       return TRUE;
08825    }
08826    return FALSE;
08827 }
08828 
08829 static int process_sdp_a_sendonly(const char *a, int *sendonly)
08830 {
08831    int found = FALSE;
08832 
08833    if (!strcasecmp(a, "sendonly")) {
08834       if (*sendonly == -1)
08835          *sendonly = 1;
08836       found = TRUE;
08837    } else if (!strcasecmp(a, "inactive")) {
08838       if (*sendonly == -1)
08839          *sendonly = 2;
08840       found = TRUE;
08841    }  else if (!strcasecmp(a, "sendrecv")) {
08842       if (*sendonly == -1)
08843          *sendonly = 0;
08844       found = TRUE;
08845    }
08846    return found;
08847 }
08848 
08849 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp *newaudiortp, int *last_rtpmap_codec)
08850 {
08851    int found = FALSE;
08852    int codec;
08853    char mimeSubtype[128];
08854    char fmtp_string[64];
08855    unsigned int sample_rate;
08856    int debug = sip_debug_test_pvt(p);
08857 
08858    if (!strncasecmp(a, "ptime", 5)) {
08859       char *tmp = strrchr(a, ':');
08860       long int framing = 0;
08861       if (tmp) {
08862          tmp++;
08863          framing = strtol(tmp, NULL, 10);
08864          if (framing == LONG_MIN || framing == LONG_MAX) {
08865             framing = 0;
08866             ast_debug(1, "Can't read framing from SDP: %s\n", a);
08867          }
08868       }
08869       if (framing && p->autoframing) {
08870          struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
08871          int codec_n;
08872          int format = 0;
08873          for (codec_n = 0; codec_n < MAX_RTP_PT; codec_n++) {
08874             format = ast_rtp_codec_getformat(codec_n);
08875             if (!format)   /* non-codec or not found */
08876                continue;
08877             if (option_debug)
08878                ast_log(LOG_DEBUG, "Setting framing for %d to %ld\n", format, framing);
08879             ast_codec_pref_setsize(pref, format, framing);
08880          }
08881          ast_rtp_codec_setpref(p->rtp, pref);
08882       }
08883       found = TRUE;
08884    } else if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
08885       /* We have a rtpmap to handle */
08886       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
08887          if (ast_rtp_set_rtpmap_type_rate(newaudiortp, codec, "audio", mimeSubtype,
08888              ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0, sample_rate) != -1) {
08889             if (debug)
08890                ast_verbose("Found audio description format %s for ID %d\n", mimeSubtype, codec);
08891             //found_rtpmap_codecs[last_rtpmap_codec] = codec;
08892             (*last_rtpmap_codec)++;
08893             found = TRUE;
08894          } else {
08895             ast_rtp_unset_m_type(newaudiortp, codec);
08896             if (debug)
08897                ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
08898          }
08899       } else {
08900          if (debug)
08901             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
08902       }
08903    } else if (sscanf(a, "fmtp: %30u %63s", &codec, fmtp_string) == 2) {
08904       struct rtpPayloadType payload;
08905 
08906       payload = ast_rtp_lookup_pt(newaudiortp, codec);
08907       if (payload.code && payload.isAstFormat) {
08908          unsigned int bit_rate;
08909 
08910          switch (payload.code) {
08911          case AST_FORMAT_SIREN7:
08912             if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
08913                if (bit_rate != 32000) {
08914                   ast_log(LOG_WARNING, "Got Siren7 offer at %d bps, but only 32000 bps supported; ignoring.\n", bit_rate);
08915                   ast_rtp_unset_m_type(newaudiortp, codec);
08916                } else {
08917                   found = TRUE;
08918                }
08919             }
08920             break;
08921          case AST_FORMAT_SIREN14:
08922             if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
08923                if (bit_rate != 48000) {
08924                   ast_log(LOG_WARNING, "Got Siren14 offer at %d bps, but only 48000 bps supported; ignoring.\n", bit_rate);
08925                   ast_rtp_unset_m_type(newaudiortp, codec);
08926                } else {
08927                   found = TRUE;
08928                }
08929             }
08930             break;
08931          }
08932       }
08933    }
08934 
08935    return found;
08936 }
08937 
08938 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp *newvideortp, int *last_rtpmap_codec)
08939 {
08940    int found = FALSE;
08941    int codec;
08942    char mimeSubtype[128];
08943    unsigned int sample_rate;
08944    int debug = sip_debug_test_pvt(p);
08945 
08946    if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
08947       /* We have a rtpmap to handle */
08948       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
08949          /* Note: should really look at the '#chans' params too */
08950          if (!strncasecmp(mimeSubtype, "H26", 3) || !strncasecmp(mimeSubtype, "MP4", 3)) {
08951             if (ast_rtp_set_rtpmap_type_rate(newvideortp, codec, "video", mimeSubtype, 0, sample_rate) != -1) {
08952                if (debug)
08953                   ast_verbose("Found video description format %s for ID %d\n", mimeSubtype, codec);
08954                //found_rtpmap_codecs[last_rtpmap_codec] = codec;
08955                (*last_rtpmap_codec)++;
08956                found = TRUE;
08957             } else {
08958                ast_rtp_unset_m_type(newvideortp, codec);
08959                if (debug) 
08960                   ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
08961             }
08962          }
08963       } else {
08964          if (debug)
08965             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
08966       }
08967    }
08968 
08969    return found;
08970 }
08971 
08972 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)
08973 {
08974    int found = FALSE;
08975    int codec;
08976    char mimeSubtype[128];
08977    unsigned int sample_rate;
08978    char *red_cp;
08979    int debug = sip_debug_test_pvt(p);
08980 
08981    if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
08982       /* We have a rtpmap to handle */
08983       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
08984          if (!strncasecmp(mimeSubtype, "T140", 4)) { /* Text */
08985             if (p->trtp) {
08986                /* ast_verbose("Adding t140 mimeSubtype to textrtp struct\n"); */
08987                ast_rtp_set_rtpmap_type(newtextrtp, codec, "text", mimeSubtype, 0);
08988                found = TRUE;
08989             }
08990          } else if (!strncasecmp(mimeSubtype, "RED", 3)) { /* Text with Redudancy */
08991             if (p->trtp) {
08992                ast_rtp_set_rtpmap_type(newtextrtp, codec, "text", mimeSubtype, 0);
08993                sprintf(red_fmtp, "fmtp:%d ", codec); 
08994                if (debug)
08995                   ast_verbose("RED submimetype has payload type: %d\n", codec);
08996                found = TRUE;
08997             }
08998          }
08999       } else {
09000          if (debug)
09001             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
09002       }
09003    } else if (!strncmp(a, red_fmtp, strlen(red_fmtp))) {
09004       /* count numbers of generations in fmtp */
09005       red_cp = &red_fmtp[strlen(red_fmtp)];
09006       strncpy(red_fmtp, a, 100);
09007 
09008       sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
09009       red_cp = strtok(red_cp, "/");
09010       while (red_cp && (*red_num_gen)++ < RED_MAX_GENERATION) {
09011          sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
09012          red_cp = strtok(NULL, "/");
09013       }
09014       red_cp = red_fmtp;
09015       found = TRUE;
09016    }
09017 
09018    return found;
09019 }
09020 
09021 static int process_sdp_a_image(const char *a, struct sip_pvt *p)
09022 {
09023    int found = FALSE;
09024    char s[256];
09025    unsigned int x;
09026 
09027    if ((sscanf(a, "T38FaxMaxBuffer:%30u", &x) == 1)) {
09028       ast_debug(3, "MaxBufferSize:%d\n", x);
09029       found = TRUE;
09030    } else if ((sscanf(a, "T38MaxBitRate:%30u", &x) == 1) || (sscanf(a, "T38FaxMaxRate:%30u", &x) == 1)) {
09031       ast_debug(3, "T38MaxBitRate: %d\n", x);
09032       switch (x) {
09033       case 14400:
09034          p->t38.their_parms.rate = AST_T38_RATE_14400;
09035          break;
09036       case 12000:
09037          p->t38.their_parms.rate = AST_T38_RATE_12000;
09038          break;
09039       case 9600:
09040          p->t38.their_parms.rate = AST_T38_RATE_9600;
09041          break;
09042       case 7200:
09043          p->t38.their_parms.rate = AST_T38_RATE_7200;
09044          break;
09045       case 4800:
09046          p->t38.their_parms.rate = AST_T38_RATE_4800;
09047          break;
09048       case 2400:
09049          p->t38.their_parms.rate = AST_T38_RATE_2400;
09050          break;
09051       }
09052       found = TRUE;
09053    } else if ((sscanf(a, "T38FaxVersion:%30u", &x) == 1)) {
09054       ast_debug(3, "FaxVersion: %u\n", x);
09055       p->t38.their_parms.version = x;
09056       found = TRUE;
09057    } else if ((sscanf(a, "T38FaxMaxDatagram:%30u", &x) == 1) || (sscanf(a, "T38MaxDatagram:%30u", &x) == 1)) {
09058       /* override the supplied value if the configuration requests it */
09059       if (((signed int) p->t38_maxdatagram >= 0) && ((unsigned int) p->t38_maxdatagram > x)) {
09060          ast_debug(1, "Overriding T38FaxMaxDatagram '%d' with '%d'\n", x, p->t38_maxdatagram);
09061          x = p->t38_maxdatagram;
09062       }
09063       ast_debug(3, "FaxMaxDatagram: %u\n", x);
09064       ast_udptl_set_far_max_datagram(p->udptl, x);
09065       found = TRUE;
09066    } else if ((strncmp(a, "T38FaxFillBitRemoval", 20) == 0)) {
09067       if (sscanf(a, "T38FaxFillBitRemoval:%30u", &x) == 1) {
09068          ast_debug(3, "FillBitRemoval: %d\n", x);
09069          if (x == 1) {
09070             p->t38.their_parms.fill_bit_removal = TRUE;
09071          }
09072       } else {
09073          ast_debug(3, "FillBitRemoval\n");
09074          p->t38.their_parms.fill_bit_removal = TRUE;
09075       }
09076       found = TRUE;
09077    } else if ((strncmp(a, "T38FaxTranscodingMMR", 20) == 0)) {
09078       if (sscanf(a, "T38FaxTranscodingMMR:%30u", &x) == 1) {
09079          ast_debug(3, "Transcoding MMR: %d\n", x);
09080          if (x == 1) {
09081             p->t38.their_parms.transcoding_mmr = TRUE;
09082          }
09083       } else {
09084          ast_debug(3, "Transcoding MMR\n");
09085          p->t38.their_parms.transcoding_mmr = TRUE;
09086       }
09087       found = TRUE;
09088    } else if ((strncmp(a, "T38FaxTranscodingJBIG", 21) == 0)) {
09089       if (sscanf(a, "T38FaxTranscodingJBIG:%30u", &x) == 1) {
09090          ast_debug(3, "Transcoding JBIG: %d\n", x);
09091          if (x == 1) {
09092             p->t38.their_parms.transcoding_jbig = TRUE;
09093          }
09094       } else {
09095          ast_debug(3, "Transcoding JBIG\n");
09096          p->t38.their_parms.transcoding_jbig = TRUE;
09097       }
09098       found = TRUE;
09099    } else if ((sscanf(a, "T38FaxRateManagement:%255s", s) == 1)) {
09100       ast_debug(3, "RateManagement: %s\n", s);
09101       if (!strcasecmp(s, "localTCF"))
09102          p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_LOCAL_TCF;
09103       else if (!strcasecmp(s, "transferredTCF"))
09104          p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF;
09105       found = TRUE;
09106    } else if ((sscanf(a, "T38FaxUdpEC:%255s", s) == 1)) {
09107       ast_debug(3, "UDP EC: %s\n", s);
09108       if (!strcasecmp(s, "t38UDPRedundancy")) {
09109          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
09110       } else if (!strcasecmp(s, "t38UDPFEC")) {
09111          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
09112       } else {
09113          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
09114       }
09115       found = TRUE;
09116    }
09117 
09118    return found;
09119 }
09120 
09121 
09122 #ifdef LOW_MEMORY
09123 static void ts_ast_rtp_destroy(void *data)
09124 {
09125     struct ast_rtp *tmp = data;
09126     ast_rtp_destroy(tmp);
09127 }
09128 #endif
09129 
09130 /*! \brief Add header to SIP message */
09131 static int add_header(struct sip_request *req, const char *var, const char *value)
09132 {
09133    if (req->headers == SIP_MAX_HEADERS) {
09134       ast_log(LOG_WARNING, "Out of SIP header space\n");
09135       return -1;
09136    }
09137 
09138    if (req->lines) {
09139       ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
09140       return -1;
09141    }
09142 
09143    if (sip_cfg.compactheaders) {
09144       var = find_alias(var, var);
09145    }
09146 
09147    ast_str_append(&req->data, 0, "%s: %s\r\n", var, value);
09148    req->header[req->headers] = req->len;
09149 
09150    req->len = ast_str_strlen(req->data);
09151    req->headers++;
09152 
09153    return 0;   
09154 }
09155 
09156 /*! \brief Add 'Content-Length' header and content to SIP message */
09157 static int finalize_content(struct sip_request *req)
09158 {
09159    char clen[10];
09160 
09161    if (req->lines) {
09162       ast_log(LOG_WARNING, "finalize_content() called on a message that has already been finalized\n");
09163       return -1;
09164    }
09165 
09166    snprintf(clen, sizeof(clen), "%zd", ast_str_strlen(req->content));
09167    add_header(req, "Content-Length", clen);
09168 
09169    if (ast_str_strlen(req->content)) {
09170       ast_str_append(&req->data, 0, "\r\n%s", ast_str_buffer(req->content));
09171       req->len = ast_str_strlen(req->data);
09172    }
09173    req->lines = ast_str_strlen(req->content) ? 1 : 0;
09174    return 0;
09175 }
09176 
09177 /*! \brief Add content (not header) to SIP message */
09178 static int add_content(struct sip_request *req, const char *line)
09179 {
09180    if (req->lines) {
09181       ast_log(LOG_WARNING, "Can't add more content when the content has been finalized\n");
09182       return -1;
09183    }
09184 
09185    ast_str_append(&req->content, 0, "%s", line);
09186    return 0;
09187 }
09188 
09189 /*! \brief Copy one header field from one request to another */
09190 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
09191 {
09192    const char *tmp = get_header(orig, field);
09193 
09194    if (!ast_strlen_zero(tmp)) /* Add what we're responding to */
09195       return add_header(req, field, tmp);
09196    ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
09197    return -1;
09198 }
09199 
09200 /*! \brief Copy all headers from one request to another */
09201 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
09202 {
09203    int start = 0;
09204    int copied = 0;
09205    for (;;) {
09206       const char *tmp = __get_header(orig, field, &start);
09207 
09208       if (ast_strlen_zero(tmp))
09209          break;
09210       /* Add what we're responding to */
09211       add_header(req, field, tmp);
09212       copied++;
09213    }
09214    return copied ? 0 : -1;
09215 }
09216 
09217 /*! \brief Copy SIP VIA Headers from the request to the response
09218 \note If the client indicates that it wishes to know the port we received from,
09219    it adds ;rport without an argument to the topmost via header. We need to
09220    add the port number (from our point of view) to that parameter.
09221 \verbatim
09222    We always add ;received=<ip address> to the topmost via header.
09223 \endverbatim
09224    Received: RFC 3261, rport RFC 3581 */
09225 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
09226 {
09227    int copied = 0;
09228    int start = 0;
09229 
09230    for (;;) {
09231       char new[512];
09232       const char *oh = __get_header(orig, field, &start);
09233 
09234       if (ast_strlen_zero(oh))
09235          break;
09236 
09237       if (!copied) { /* Only check for empty rport in topmost via header */
09238          char leftmost[512], *others, *rport;
09239 
09240          /* Only work on leftmost value */
09241          ast_copy_string(leftmost, oh, sizeof(leftmost));
09242          others = strchr(leftmost, ',');
09243          if (others)
09244              *others++ = '\0';
09245 
09246          /* Find ;rport;  (empty request) */
09247          rport = strstr(leftmost, ";rport");
09248          if (rport && *(rport+6) == '=') 
09249             rport = NULL;     /* We already have a parameter to rport */
09250 
09251          /* Check rport if NAT=yes or NAT=rfc3581 (which is the default setting)  */
09252          if (rport && ((ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_ALWAYS) || (ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_RFC3581))) {
09253             /* We need to add received port - rport */
09254             char *end;
09255 
09256             rport = strstr(leftmost, ";rport");
09257 
09258             if (rport) {
09259                end = strchr(rport + 1, ';');
09260                if (end)
09261                   memmove(rport, end, strlen(end) + 1);
09262                else
09263                   *rport = '\0';
09264             }
09265 
09266             /* Add rport to first VIA header if requested */
09267             snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
09268                leftmost, ast_inet_ntoa(p->recv.sin_addr),
09269                ntohs(p->recv.sin_port),
09270                others ? "," : "", others ? others : "");
09271          } else {
09272             /* We should *always* add a received to the topmost via */
09273             snprintf(new, sizeof(new), "%s;received=%s%s%s",
09274                leftmost, ast_inet_ntoa(p->recv.sin_addr),
09275                others ? "," : "", others ? others : "");
09276          }
09277          oh = new;   /* the header to copy */
09278       }  /* else add the following via headers untouched */
09279       add_header(req, field, oh);
09280       copied++;
09281    }
09282    if (!copied) {
09283       ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
09284       return -1;
09285    }
09286    return 0;
09287 }
09288 
09289 /*! \brief Add route header into request per learned route */
09290 static void add_route(struct sip_request *req, struct sip_route *route)
09291 {
09292    char r[SIPBUFSIZE*2], *p;
09293    int n, rem = sizeof(r);
09294 
09295    if (!route)
09296       return;
09297 
09298    p = r;
09299    for (;route ; route = route->next) {
09300       n = strlen(route->hop);
09301       if (rem < n+3) /* we need room for ",<route>" */
09302          break;
09303       if (p != r) {  /* add a separator after fist route */
09304          *p++ = ',';
09305          --rem;
09306       }
09307       *p++ = '<';
09308       ast_copy_string(p, route->hop, rem); /* cannot fail */
09309       p += n;
09310       *p++ = '>';
09311       rem -= (n+2);
09312    }
09313    *p = '\0';
09314    add_header(req, "Route", r);
09315 }
09316 
09317 /*! \brief Set destination from SIP URI 
09318  *
09319  * Parse uri to h (host) and port - uri is already just the part inside the <> 
09320  * general form we are expecting is sip[s]:username[:password][;parameter]@host[:port][;...] 
09321  * If there's a port given, turn NAPTR/SRV off. NAPTR might indicate SIPS preference even
09322  * for SIP: uri's
09323  *
09324  * If there's a sips: uri scheme, TLS will be required. 
09325  */
09326 static void set_destination(struct sip_pvt *p, char *uri)
09327 {
09328    char *h, *maddr, hostname[256];
09329    int port, hn;
09330    struct hostent *hp;
09331    struct ast_hostent ahp;
09332    int debug=sip_debug_test_pvt(p);
09333    int tls_on = FALSE;
09334    int use_dns = sip_cfg.srvlookup;
09335 
09336    if (debug)
09337       ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
09338 
09339    /* Find and parse hostname */
09340    h = strchr(uri, '@');
09341    if (h)
09342       ++h;
09343    else {
09344       h = uri;
09345       if (!strncasecmp(h, "sip:", 4)) {
09346          h += 4;
09347       } else if (!strncasecmp(h, "sips:", 5)) {
09348          h += 5;
09349          tls_on = TRUE;
09350       }
09351    }
09352    hn = strcspn(h, ":;>") + 1;
09353    if (hn > sizeof(hostname)) 
09354       hn = sizeof(hostname);
09355    ast_copy_string(hostname, h, hn);
09356    /* XXX bug here if string has been trimmed to sizeof(hostname) */
09357    h += hn - 1;
09358 
09359    /* Is "port" present? if not default to STANDARD_SIP_PORT */
09360    if (*h == ':') {
09361       /* Parse port */
09362       ++h;
09363       port = strtol(h, &h, 10);
09364       use_dns = FALSE;
09365    } else
09366       port = tls_on ? STANDARD_TLS_PORT : STANDARD_SIP_PORT;
09367 
09368    /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
09369    maddr = strstr(h, "maddr=");
09370    if (maddr) {
09371       maddr += 6;
09372       hn = strspn(maddr, "0123456789.") + 1;
09373       if (hn > sizeof(hostname))
09374          hn = sizeof(hostname);
09375       ast_copy_string(hostname, maddr, hn);
09376    }
09377 
09378    /*! \todo XXX If we have use_dns on, then look for NAPTR/SRV, otherwise, just look for A records */
09379    
09380    hp = ast_gethostbyname(hostname, &ahp);
09381    if (hp == NULL)  {
09382       ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
09383       return;
09384    }
09385    p->sa.sin_family = AF_INET;
09386    memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
09387    p->sa.sin_port = htons(port);
09388    if (debug)
09389       ast_verbose("set_destination: set destination to %s, port %d\n", ast_inet_ntoa(p->sa.sin_addr), port);
09390 }
09391 
09392 /*! \brief Initialize SIP response, based on SIP request */
09393 static int init_resp(struct sip_request *resp, const char *msg)
09394 {
09395    /* Initialize a response */
09396    memset(resp, 0, sizeof(*resp));
09397    resp->method = SIP_RESPONSE;
09398    if (!(resp->data = ast_str_create(SIP_MIN_PACKET)))
09399       goto e_return;
09400    if (!(resp->content = ast_str_create(SIP_MIN_PACKET)))
09401       goto e_free_data;
09402    resp->header[0] = 0;
09403    ast_str_set(&resp->data, 0, "SIP/2.0 %s\r\n", msg);
09404    resp->len = resp->data->used;
09405    resp->headers++;
09406    return 0;
09407 
09408 e_free_data:
09409    ast_free(resp->data);
09410    resp->data = NULL;
09411 e_return:
09412    return -1;
09413 }
09414 
09415 /*! \brief Initialize SIP request */
09416 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
09417 {
09418    /* Initialize a request */
09419    memset(req, 0, sizeof(*req));
09420    if (!(req->data = ast_str_create(SIP_MIN_PACKET)))
09421       goto e_return;
09422    if (!(req->content = ast_str_create(SIP_MIN_PACKET)))
09423       goto e_free_data;
09424    req->method = sipmethod;
09425    req->header[0] = 0;
09426    ast_str_set(&req->data, 0, "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
09427    req->len = ast_str_strlen(req->data);
09428    req->headers++;
09429    return 0;
09430 
09431 e_free_data:
09432    ast_free(req->data);
09433    req->data = NULL;
09434 e_return:
09435    return -1;
09436 }
09437 
09438 /*! \brief Deinitialize SIP response/request */
09439 static void deinit_req(struct sip_request *req)
09440 {
09441    if (req->data) {
09442       ast_free(req->data);
09443       req->data = NULL;
09444    }
09445    if (req->content) {
09446       ast_free(req->content);
09447       req->content = NULL;
09448    }
09449 }
09450 
09451 
09452 /*! \brief Test if this response needs a contact header */
09453 static inline int resp_needs_contact(const char *msg, enum sipmethod method) {
09454    /* Requirements for Contact header inclusion in responses generated
09455     * from the header tables found in the following RFCs.  Where the
09456     * Contact header was marked mandatory (m) or optional (o) this
09457     * function returns 1.
09458     *
09459     * - RFC 3261 (ACK, BYE, CANCEL, INVITE, OPTIONS, REGISTER)
09460     * - RFC 2976 (INFO)
09461     * - RFC 3262 (PRACK)
09462     * - RFC 3265 (SUBSCRIBE, NOTIFY)
09463     * - RFC 3311 (UPDATE)
09464     * - RFC 3428 (MESSAGE)
09465     * - RFC 3515 (REFER)
09466     * - RFC 3903 (PUBLISH)
09467     */
09468 
09469    switch (method) {
09470       /* 1xx, 2xx, 3xx, 485 */
09471       case SIP_INVITE:
09472       case SIP_UPDATE:
09473       case SIP_SUBSCRIBE:
09474       case SIP_NOTIFY:
09475          if ((msg[0] >= '1' && msg[0] <= '3') || !strncmp(msg, "485", 3))
09476             return 1;
09477          break;
09478 
09479       /* 2xx, 3xx, 485 */
09480       case SIP_REGISTER:
09481       case SIP_OPTIONS:
09482          if (msg[0] == '2' || msg[0] == '3' || !strncmp(msg, "485", 3))
09483             return 1;
09484          break;
09485 
09486       /* 3xx, 485 */
09487       case SIP_BYE:
09488       case SIP_PRACK:
09489       case SIP_MESSAGE:
09490       case SIP_PUBLISH:
09491          if (msg[0] == '3' || !strncmp(msg, "485", 3))
09492             return 1;
09493          break;
09494 
09495       /* 2xx, 3xx, 4xx, 5xx, 6xx */
09496       case SIP_REFER:
09497          if (msg[0] >= '2' && msg[0] <= '6')
09498             return 1;
09499          break;
09500 
09501       /* contact will not be included for everything else */
09502       case SIP_ACK:
09503       case SIP_CANCEL:
09504       case SIP_INFO:
09505       case SIP_PING:
09506       default:
09507          return 0;
09508    }
09509    return 0;
09510 }
09511 
09512 /*! \brief Prepare SIP response packet */
09513 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
09514 {
09515    char newto[256];
09516    const char *ot;
09517 
09518    init_resp(resp, msg);
09519    copy_via_headers(p, resp, req, "Via");
09520    if (msg[0] == '1' || msg[0] == '2')
09521       copy_all_header(resp, req, "Record-Route");
09522    copy_header(resp, req, "From");
09523    ot = get_header(req, "To");
09524    if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
09525       /* Add the proper tag if we don't have it already.  If they have specified
09526          their tag, use it.  Otherwise, use our own tag */
09527       if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
09528          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
09529       else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
09530          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
09531       else
09532          ast_copy_string(newto, ot, sizeof(newto));
09533       ot = newto;
09534    }
09535    add_header(resp, "To", ot);
09536    copy_header(resp, req, "Call-ID");
09537    copy_header(resp, req, "CSeq");
09538    if (!ast_strlen_zero(global_useragent))
09539       add_header(resp, "Server", global_useragent);
09540    add_header(resp, "Allow", ALLOWED_METHODS);
09541    add_header(resp, "Supported", SUPPORTED_EXTENSIONS);
09542 
09543    /* If this is an invite, add Session-Timers related headers if the feature is active for this session */
09544    if (p->method == SIP_INVITE && p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE) {
09545       char se_hdr[256];
09546       snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval, 
09547          strefresher2str(p->stimer->st_ref));
09548       add_header(resp, "Require", "timer");
09549       add_header(resp, "Session-Expires", se_hdr);
09550    }
09551 
09552    if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
09553       /* For registration responses, we also need expiry and
09554          contact info */
09555       char tmp[256];
09556 
09557       snprintf(tmp, sizeof(tmp), "%d", p->expiry);
09558       add_header(resp, "Expires", tmp);
09559       if (p->expiry) {  /* Only add contact if we have an expiry time */
09560          char contact[SIPBUFSIZE];
09561          const char *contact_uri = p->method == SIP_SUBSCRIBE ? p->our_contact : p->fullcontact;
09562          char *brackets = strchr(contact_uri, '<');
09563          snprintf(contact, sizeof(contact), "%s%s%s;expires=%d", brackets ? "" : "<", contact_uri, brackets ? "" : ">", p->expiry);
09564          add_header(resp, "Contact", contact);  /* Not when we unregister */
09565       }
09566    } else if (!ast_strlen_zero(p->our_contact) && resp_needs_contact(msg, p->method)) {
09567       add_header(resp, "Contact", p->our_contact);
09568    }
09569 
09570    if (!ast_strlen_zero(p->url)) {
09571       add_header(resp, "Access-URL", p->url);
09572       ast_string_field_set(p, url, NULL);
09573    }
09574 
09575    return 0;
09576 }
09577 
09578 /*! \brief Initialize a SIP request message (not the initial one in a dialog) */
09579 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch)
09580 {
09581    struct sip_request *orig = &p->initreq;
09582    char stripped[80];
09583    char tmp[80];
09584    char newto[256];
09585    const char *c;
09586    const char *ot, *of;
09587    int is_strict = FALSE;     /*!< Strict routing flag */
09588    int is_outbound = ast_test_flag(&p->flags[0], SIP_OUTGOING);   /* Session direction */
09589 
09590    memset(req, 0, sizeof(struct sip_request));
09591    
09592    snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
09593    
09594    if (!seqno) {
09595       p->ocseq++;
09596       seqno = p->ocseq;
09597    }
09598    
09599    /* A CANCEL must have the same branch as the INVITE that it is canceling. */
09600    if (sipmethod == SIP_CANCEL) {
09601       p->branch = p->invite_branch;
09602       build_via(p);
09603    } else if (newbranch && (sipmethod == SIP_INVITE)) {
09604       p->branch ^= ast_random();
09605       p->invite_branch = p->branch;
09606       build_via(p);
09607    } else if (newbranch) {
09608       p->branch ^= ast_random();
09609       build_via(p);
09610    }
09611 
09612    /* Check for strict or loose router */
09613    if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop, ";lr") == NULL) {
09614       is_strict = TRUE;
09615       if (sipdebug)
09616          ast_debug(1, "Strict routing enforced for session %s\n", p->callid);
09617    }
09618    
09619    if (sipmethod == SIP_CANCEL)
09620       c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2); /* Use original URI */
09621    else if (sipmethod == SIP_ACK) {
09622       /* Use URI from Contact: in 200 OK (if INVITE) 
09623       (we only have the contacturi on INVITEs) */
09624       if (!ast_strlen_zero(p->okcontacturi))
09625          c = is_strict ? p->route->hop : p->okcontacturi;
09626       else
09627          c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
09628    } else if (!ast_strlen_zero(p->okcontacturi)) 
09629       c = is_strict ? p->route->hop : p->okcontacturi; /* Use for BYE or REINVITE */
09630    else if (!ast_strlen_zero(p->uri)) 
09631       c = p->uri;
09632    else {
09633       char *n;
09634       /* We have no URI, use To: or From:  header as URI (depending on direction) */
09635       ast_copy_string(stripped, get_header(orig, is_outbound ? "To" : "From"),
09636             sizeof(stripped));
09637       n = get_in_brackets(stripped);
09638       c = remove_uri_parameters(n);
09639    }  
09640    init_req(req, sipmethod, c);
09641 
09642    snprintf(tmp, sizeof(tmp), "%d %s", seqno, sip_methods[sipmethod].text);
09643 
09644    add_header(req, "Via", p->via);
09645    if (p->route) {
09646       set_destination(p, p->route->hop);
09647       add_route(req, is_strict ? p->route->next : p->route);
09648    }
09649    add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
09650 
09651    ot = get_header(orig, "To");
09652    of = get_header(orig, "From");
09653 
09654    /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
09655       as our original request, including tag (or presumably lack thereof) */
09656    if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
09657       /* Add the proper tag if we don't have it already.  If they have specified
09658          their tag, use it.  Otherwise, use our own tag */
09659       if (is_outbound && !ast_strlen_zero(p->theirtag))
09660          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
09661       else if (!is_outbound)
09662          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
09663       else
09664          snprintf(newto, sizeof(newto), "%s", ot);
09665       ot = newto;
09666    }
09667 
09668    if (is_outbound) {
09669       add_header(req, "From", of);
09670       add_header(req, "To", ot);
09671    } else {
09672       add_header(req, "From", ot);
09673       add_header(req, "To", of);
09674    }
09675    /* Do not add Contact for MESSAGE, BYE and Cancel requests */
09676    if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
09677       add_header(req, "Contact", p->our_contact);
09678 
09679    copy_header(req, orig, "Call-ID");
09680    add_header(req, "CSeq", tmp);
09681 
09682    if (!ast_strlen_zero(global_useragent))
09683       add_header(req, "User-Agent", global_useragent);
09684 
09685    if (!ast_strlen_zero(p->rpid))
09686       add_header(req, "Remote-Party-ID", p->rpid);
09687 
09688    if (!ast_strlen_zero(p->url)) {
09689       add_header(req, "Access-URL", p->url);
09690       ast_string_field_set(p, url, NULL);
09691    }
09692 
09693    /* Add Session-Timers related headers if the feature is active for this session.
09694       An exception to this behavior is the ACK request. Since Asterisk never requires 
09695       session-timers support from a remote end-point (UAS) in an INVITE, it must 
09696       not send 'Require: timer' header in the ACK request. 
09697       This should only be added in the INVITE transactions, not MESSAGE or REFER or other
09698       in-dialog messages.
09699    */
09700    if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE 
09701        && sipmethod == SIP_INVITE) {
09702       char se_hdr[256];
09703       snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval, 
09704          strefresher2str(p->stimer->st_ref));
09705       add_header(req, "Require", "timer");
09706       add_header(req, "Session-Expires", se_hdr);
09707       snprintf(se_hdr, sizeof(se_hdr), "%d", st_get_se(p, FALSE));
09708       add_header(req, "Min-SE", se_hdr);
09709    }
09710 
09711    return 0;
09712 }
09713 
09714 /*! \brief Base transmit response function */
09715 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
09716 {
09717    struct sip_request resp;
09718    int seqno = 0;
09719 
09720    if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
09721       ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
09722       return -1;
09723    }
09724    respprep(&resp, p, msg, req);
09725    /* If we are cancelling an incoming invite for some reason, add information
09726       about the reason why we are doing this in clear text */
09727    if (p->method == SIP_INVITE && msg[0] != '1' && p->owner && p->owner->hangupcause) {
09728       char buf[10];
09729 
09730       add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
09731       snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
09732       add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
09733    }
09734    return send_response(p, &resp, reliable, seqno);
09735 }
09736 
09737 static int temp_pvt_init(void *data)
09738 {
09739    struct sip_pvt *p = data;
09740 
09741    p->do_history = 0;   /* XXX do we need it ? isn't already all 0 ? */
09742    return ast_string_field_init(p, 512);
09743 }
09744 
09745 static void temp_pvt_cleanup(void *data)
09746 {
09747    struct sip_pvt *p = data;
09748 
09749    ast_string_field_free_memory(p);
09750 
09751    ast_free(data);
09752 }
09753 
09754 /*! \brief Transmit response, no retransmits, using a temporary pvt structure */
09755 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)
09756 {
09757    struct sip_pvt *p = NULL;
09758 
09759    if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
09760       ast_log(LOG_ERROR, "Failed to get temporary pvt\n");
09761       return -1;
09762    }
09763 
09764    /* XXX the structure may be dirty from previous usage.
09765     * Here we should state clearly how we should reinitialize it
09766     * before using it.
09767     * E.g. certainly the threadstorage should be left alone,
09768     * but other thihngs such as flags etc. maybe need cleanup ?
09769     */
09770     
09771    /* Initialize the bare minimum */
09772    p->method = intended_method;
09773 
09774    if (!sin)
09775       p->ourip = internip;
09776    else {
09777       p->sa = *sin;
09778       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
09779    }
09780 
09781    p->branch = ast_random();
09782    make_our_tag(p->tag, sizeof(p->tag));
09783    p->ocseq = INITIAL_CSEQ;
09784 
09785    if (useglobal_nat && sin) {
09786       ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
09787       p->recv = *sin;
09788       do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
09789    }
09790 
09791    ast_string_field_set(p, fromdomain, default_fromdomain);
09792    build_via(p);
09793    ast_string_field_set(p, callid, callid);
09794 
09795    copy_socket_data(&p->socket, &req->socket);
09796 
09797    /* Use this temporary pvt structure to send the message */
09798    __transmit_response(p, msg, req, XMIT_UNRELIABLE);
09799 
09800    /* Free the string fields, but not the pool space */
09801    ast_string_field_init(p, 0);
09802 
09803    return 0;
09804 }
09805 
09806 /*! \brief Transmit response, no retransmits */
09807 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req) 
09808 {
09809    return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
09810 }
09811 
09812 /*! \brief Transmit response, no retransmits */
09813 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported) 
09814 {
09815    struct sip_request resp;
09816    respprep(&resp, p, msg, req);
09817    append_date(&resp);
09818    add_header(&resp, "Unsupported", unsupported);
09819    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
09820 }
09821 
09822 /*! \brief Transmit 422 response with Min-SE header (Session-Timers)  */
09823 static int transmit_response_with_minse(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minse_int)
09824 {
09825    struct sip_request resp;
09826    char minse_str[20];
09827 
09828    respprep(&resp, p, msg, req);
09829    append_date(&resp);
09830 
09831    snprintf(minse_str, sizeof(minse_str), "%d", minse_int);
09832    add_header(&resp, "Min-SE", minse_str);
09833    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
09834 }
09835 
09836 
09837 /*! \brief Transmit response, Make sure you get an ACK
09838    This is only used for responses to INVITEs, where we need to make sure we get an ACK
09839 */
09840 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
09841 {
09842    return __transmit_response(p, msg, req, req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL);
09843 }
09844 
09845 /*! \brief Append date to SIP message */
09846 static void append_date(struct sip_request *req)
09847 {
09848    char tmpdat[256];
09849    struct tm tm;
09850    time_t t = time(NULL);
09851 
09852    gmtime_r(&t, &tm);
09853    strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
09854    add_header(req, "Date", tmpdat);
09855 }
09856 
09857 /*! \brief Append date and content length before transmitting response */
09858 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
09859 {
09860    struct sip_request resp;
09861    respprep(&resp, p, msg, req);
09862    append_date(&resp);
09863    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
09864 }
09865 
09866 /*! \brief Append Accept header, content length before transmitting response */
09867 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
09868 {
09869    struct sip_request resp;
09870    respprep(&resp, p, msg, req);
09871    add_header(&resp, "Accept", "application/sdp");
09872    return send_response(p, &resp, reliable, 0);
09873 }
09874 
09875 /*! \brief Respond with authorization request */
09876 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)
09877 {
09878    struct sip_request resp;
09879    char tmp[512];
09880    int seqno = 0;
09881 
09882    if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
09883       ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
09884       return -1;
09885    }
09886    /* Stale means that they sent us correct authentication, but 
09887       based it on an old challenge (nonce) */
09888    snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", sip_cfg.realm, randdata, stale ? ", stale=true" : "");
09889    respprep(&resp, p, msg, req);
09890    add_header(&resp, header, tmp);
09891    append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
09892    return send_response(p, &resp, reliable, seqno);
09893 }
09894 
09895 /* Only use a static string for the msg, here! */
09896 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp)
09897 {
09898    int res;
09899 
09900    if (!(res = with_sdp ? transmit_response_with_sdp(p, msg, req, XMIT_UNRELIABLE, FALSE) : transmit_response(p, msg, req))) {
09901       p->last_provisional = msg;
09902       update_provisional_keepalive(p, with_sdp);
09903    }
09904 
09905    return res;
09906 }
09907 
09908 /*! \brief Add text body to SIP message */
09909 static int add_text(struct sip_request *req, const char *text)
09910 {
09911    /* XXX Convert \n's to \r\n's XXX */
09912    add_header(req, "Content-Type", "text/plain;charset=UTF-8");
09913    add_content(req, text);
09914    return 0;
09915 }
09916 
09917 /*! \brief Add DTMF INFO tone to sip message 
09918    Mode =   0 for application/dtmf-relay (Cisco)
09919       1 for application/dtmf
09920 */
09921 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode)
09922 {
09923    char tmp[256];
09924    int event;
09925    if (mode) {
09926       /* Application/dtmf short version used by some implementations */
09927       if (digit == '*')
09928          event = 10;
09929       else if (digit == '#')
09930          event = 11;
09931       else if ((digit >= 'A') && (digit <= 'D'))
09932          event = 12 + digit - 'A';
09933       else
09934          event = atoi(&digit);
09935       snprintf(tmp, sizeof(tmp), "%d\r\n", event);
09936       add_header(req, "Content-Type", "application/dtmf");
09937       add_content(req, tmp);
09938    } else {
09939       /* Application/dtmf-relay as documented by Cisco */
09940       snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
09941       add_header(req, "Content-Type", "application/dtmf-relay");
09942       add_content(req, tmp);
09943    }
09944    return 0;
09945 }
09946 
09947 /*! \brief add XML encoded media control with update 
09948    \note XML: The only way to turn 0 bits of information into a few hundred. (markster) */
09949 static int add_vidupdate(struct sip_request *req)
09950 {
09951    const char *xml_is_a_huge_waste_of_space =
09952       "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
09953       " <media_control>\r\n"
09954       "  <vc_primitive>\r\n"
09955       "   <to_encoder>\r\n"
09956       "    <picture_fast_update>\r\n"
09957       "    </picture_fast_update>\r\n"
09958       "   </to_encoder>\r\n"
09959       "  </vc_primitive>\r\n"
09960       " </media_control>\r\n";
09961    add_header(req, "Content-Type", "application/media_control+xml");
09962    add_content(req, xml_is_a_huge_waste_of_space);
09963    return 0;
09964 }
09965 
09966 /*! \brief Add codec offer to SDP offer/answer body in INVITE or 200 OK */
09967 static void add_codec_to_sdp(const struct sip_pvt *p, int codec,
09968               struct ast_str **m_buf, struct ast_str **a_buf,
09969               int debug, int *min_packet_size)
09970 {
09971    int rtp_code;
09972    struct ast_format_list fmt;
09973 
09974 
09975    if (debug)
09976       ast_verbose("Adding codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
09977    if ((rtp_code = ast_rtp_lookup_code(p->rtp, 1, codec)) == -1)
09978       return;
09979 
09980    if (p->rtp) {
09981       struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
09982       fmt = ast_codec_pref_getsize(pref, codec);
09983    } 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 */
09984       return;
09985    ast_str_append(m_buf, 0, " %d", rtp_code);
09986    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
09987              ast_rtp_lookup_mime_subtype(1, codec,
09988                      ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
09989              ast_rtp_lookup_sample_rate(1, codec));
09990 
09991    switch (codec) {
09992    case AST_FORMAT_G729A:
09993       /* Indicate that we don't support VAD (G.729 annex B) */
09994       ast_str_append(a_buf, 0, "a=fmtp:%d annexb=no\r\n", rtp_code);
09995       break;
09996    case AST_FORMAT_G723_1:
09997       /* Indicate that we don't support VAD (G.723.1 annex A) */
09998       ast_str_append(a_buf, 0, "a=fmtp:%d annexa=no\r\n", rtp_code);
09999       break;
10000    case AST_FORMAT_ILBC:
10001       /* Add information about us using only 20/30 ms packetization */
10002       ast_str_append(a_buf, 0, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
10003       break;
10004    case AST_FORMAT_SIREN7:
10005       /* Indicate that we only expect 32Kbps */
10006       ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=32000\r\n", rtp_code);
10007       break;
10008    case AST_FORMAT_SIREN14:
10009       /* Indicate that we only expect 48Kbps */
10010       ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=48000\r\n", rtp_code);
10011       break;
10012    }
10013 
10014    if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
10015       *min_packet_size = fmt.cur_ms;
10016 
10017    /* Our first codec packetization processed cannot be zero */
10018    if ((*min_packet_size)==0 && fmt.cur_ms)
10019       *min_packet_size = fmt.cur_ms;
10020 }
10021 
10022 /*! \brief Add video codec offer to SDP offer/answer body in INVITE or 200 OK */
10023 /* This is different to the audio one now so we can add more caps later */
10024 static void add_vcodec_to_sdp(const struct sip_pvt *p, int codec,
10025               struct ast_str **m_buf, struct ast_str **a_buf,
10026               int debug, int *min_packet_size)
10027 {
10028    int rtp_code;
10029 
10030    if (!p->vrtp)
10031       return;
10032 
10033    if (debug)
10034       ast_verbose("Adding video codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
10035 
10036    if ((rtp_code = ast_rtp_lookup_code(p->vrtp, 1, codec)) == -1)
10037       return;
10038 
10039    ast_str_append(m_buf, 0, " %d", rtp_code);
10040    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10041              ast_rtp_lookup_mime_subtype(1, codec, 0),
10042              ast_rtp_lookup_sample_rate(1, codec));
10043    /* Add fmtp code here */
10044 }
10045 
10046 /*! \brief Add text codec offer to SDP offer/answer body in INVITE or 200 OK */
10047 static void add_tcodec_to_sdp(const struct sip_pvt *p, int codec,
10048               struct ast_str **m_buf, struct ast_str **a_buf,
10049               int debug, int *min_packet_size)
10050 {
10051    int rtp_code;
10052 
10053    if (!p->trtp)
10054       return;
10055 
10056    if (debug)
10057       ast_verbose("Adding text codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
10058 
10059    if ((rtp_code = ast_rtp_lookup_code(p->trtp, 1, codec)) == -1)
10060       return;
10061 
10062    ast_str_append(m_buf, 0, " %d", rtp_code);
10063    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10064              ast_rtp_lookup_mime_subtype(1, codec, 0),
10065              ast_rtp_lookup_sample_rate(1, codec));
10066    /* Add fmtp code here */
10067 
10068    if (codec == AST_FORMAT_T140RED) {
10069       ast_str_append(a_buf, 0, "a=fmtp:%d %d/%d/%d\r\n", rtp_code,
10070           ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140),
10071           ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140),
10072           ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140));
10073 
10074    }
10075 }
10076 
10077 
10078 /*! \brief Get Max T.38 Transmission rate from T38 capabilities */
10079 static unsigned int t38_get_rate(enum ast_control_t38_rate rate)
10080 {
10081    switch (rate) {
10082    case AST_T38_RATE_2400:
10083       return 2400;
10084    case AST_T38_RATE_4800:
10085       return 4800;
10086    case AST_T38_RATE_7200:
10087       return 7200;
10088    case AST_T38_RATE_9600:
10089       return 9600;
10090    case AST_T38_RATE_12000:
10091       return 12000;
10092    case AST_T38_RATE_14400:
10093       return 14400;
10094    default:
10095       return 0;
10096    }
10097 }
10098 
10099 /*! \brief Add RFC 2833 DTMF offer to SDP */
10100 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
10101             struct ast_str **m_buf, struct ast_str **a_buf,
10102             int debug)
10103 {
10104    int rtp_code;
10105 
10106    if (debug)
10107       ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype(0, format, 0));
10108    if ((rtp_code = ast_rtp_lookup_code(p->rtp, 0, format)) == -1)
10109       return;
10110 
10111    ast_str_append(m_buf, 0, " %d", rtp_code);
10112    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10113              ast_rtp_lookup_mime_subtype(0, format, 0),
10114              ast_rtp_lookup_sample_rate(0, format));
10115    if (format == AST_RTP_DTMF)   /* Indicate we support DTMF and FLASH... */
10116       ast_str_append(a_buf, 0, "a=fmtp:%d 0-16\r\n", rtp_code);
10117 }
10118 
10119 /*! \brief Set all IP media addresses for this call 
10120    \note called from add_sdp()
10121 */
10122 static void get_our_media_address(struct sip_pvt *p, int needvideo,
10123    struct sockaddr_in *sin, struct sockaddr_in *vsin, struct sockaddr_in *tsin,
10124    struct sockaddr_in *dest, struct sockaddr_in *vdest)
10125 {
10126    /* First, get our address */
10127    ast_rtp_get_us(p->rtp, sin);
10128    if (p->vrtp)
10129       ast_rtp_get_us(p->vrtp, vsin);
10130    if (p->trtp)
10131       ast_rtp_get_us(p->trtp, tsin);
10132 
10133    /* Now, try to figure out where we want them to send data */
10134    /* Is this a re-invite to move the media out, then use the original offer from caller  */
10135    if (p->redirip.sin_addr.s_addr) {   /* If we have a redirection IP, use it */
10136       dest->sin_port = p->redirip.sin_port;
10137       dest->sin_addr = p->redirip.sin_addr;
10138    } else {
10139       dest->sin_addr = p->ourip.sin_addr;
10140       dest->sin_port = sin->sin_port;
10141    }
10142    if (needvideo) {
10143       /* Determine video destination */
10144       if (p->vredirip.sin_addr.s_addr) {
10145          vdest->sin_addr = p->vredirip.sin_addr;
10146          vdest->sin_port = p->vredirip.sin_port;
10147       } else {
10148          vdest->sin_addr = p->ourip.sin_addr;
10149          vdest->sin_port = vsin->sin_port;
10150       }
10151    }
10152 
10153 }
10154 
10155 /*! \brief Add Session Description Protocol message 
10156 
10157     If oldsdp is TRUE, then the SDP version number is not incremented. This mechanism
10158     is used in Session-Timers where RE-INVITEs are used for refreshing SIP sessions 
10159     without modifying the media session in any way. 
10160 */
10161 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38)
10162 {
10163    int alreadysent = 0;
10164 
10165    struct sockaddr_in sin;
10166    struct sockaddr_in vsin;
10167    struct sockaddr_in tsin;
10168    struct sockaddr_in dest;
10169    struct sockaddr_in udptlsin;
10170    struct sockaddr_in vdest = { 0, };
10171    struct sockaddr_in tdest = { 0, };
10172    struct sockaddr_in udptldest = { 0, };
10173 
10174    /* SDP fields */
10175    char *version =   "v=0\r\n";     /* Protocol version */
10176    char subject[256];            /* Subject of the session */
10177    char owner[256];           /* Session owner/creator */
10178    char connection[256];            /* Connection data */
10179    char *session_time = "t=0 0\r\n";         /* Time the session is active */
10180    char bandwidth[256] = "";        /* Max bitrate */
10181    char *hold = "";
10182    struct ast_str *m_audio = ast_str_alloca(256);  /* Media declaration line for audio */
10183    struct ast_str *m_video = ast_str_alloca(256);  /* Media declaration line for video */
10184    struct ast_str *m_text = ast_str_alloca(256);   /* Media declaration line for text */
10185    struct ast_str *m_modem = ast_str_alloca(256);  /* Media declaration line for modem */
10186    struct ast_str *a_audio = ast_str_alloca(1024); /* Attributes for audio */
10187    struct ast_str *a_video = ast_str_alloca(1024); /* Attributes for video */
10188    struct ast_str *a_text = ast_str_alloca(1024);  /* Attributes for text */
10189    struct ast_str *a_modem = ast_str_alloca(1024); /* Attributes for modem */
10190 
10191    int x;
10192    int capability = 0;
10193    int needaudio = FALSE;
10194    int needvideo = FALSE;
10195    int needtext = FALSE;
10196    int debug = sip_debug_test_pvt(p);
10197    int min_audio_packet_size = 0;
10198    int min_video_packet_size = 0;
10199    int min_text_packet_size = 0;
10200 
10201    char codecbuf[SIPBUFSIZE];
10202    char buf[SIPBUFSIZE];
10203    char dummy_answer[256];
10204 
10205    /* Set the SDP session name */
10206    snprintf(subject, sizeof(subject), "s=%s\r\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
10207 
10208    if (!p->rtp) {
10209       ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
10210       return AST_FAILURE;
10211    }
10212    /* XXX We should not change properties in the SIP dialog until 
10213       we have acceptance of the offer if this is a re-invite */
10214 
10215    /* Set RTP Session ID and version */
10216    if (!p->sessionid) {
10217       p->sessionid = (int)ast_random();
10218       p->sessionversion = p->sessionid;
10219    } else {
10220       if (oldsdp == FALSE)
10221          p->sessionversion++;
10222    }
10223 
10224    if (add_audio) {
10225       /* Check if we need video in this call */
10226       if ((p->jointcapability & AST_FORMAT_VIDEO_MASK) && !p->novideo) {
10227          if (p->vrtp) {
10228             needvideo = TRUE;
10229             ast_debug(2, "This call needs video offers!\n");
10230          } else
10231             ast_debug(2, "This call needs video offers, but there's no video support enabled!\n");
10232       }
10233       /* Check if we need text in this call */
10234       if ((p->jointcapability & AST_FORMAT_TEXT_MASK) && !p->notext) {
10235          if (sipdebug_text)
10236             ast_verbose("We think we can do text\n");
10237          if (p->trtp) {
10238             if (sipdebug_text) {
10239                ast_verbose("And we have a text rtp object\n");
10240             }
10241             needtext = TRUE;
10242             ast_debug(2, "This call needs text offers! \n");
10243          } else {
10244             ast_debug(2, "This call needs text offers, but there's no text support enabled ! \n");
10245          }
10246       }
10247    }
10248 
10249    get_our_media_address(p, needvideo, &sin, &vsin, &tsin, &dest, &vdest);
10250 
10251    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));
10252    snprintf(connection, sizeof(connection), "c=IN IP4 %s\r\n", ast_inet_ntoa(dest.sin_addr));
10253 
10254    if (add_audio) {
10255       capability = p->jointcapability;
10256 
10257       /* XXX note, Video and Text are negated - 'true' means 'no' */
10258       ast_debug(1, "** Our capability: %s Video flag: %s Text flag: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability), 
10259            p->novideo ? "True" : "False", p->notext ? "True" : "False");
10260       ast_debug(1, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));
10261 
10262       /* Check if we need audio */
10263       if (capability & AST_FORMAT_AUDIO_MASK)
10264          needaudio = TRUE;
10265 
10266       if (debug) 
10267          ast_verbose("Audio is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(sin.sin_port)); 
10268 
10269       /* Ok, we need video. Let's add what we need for video and set codecs.
10270          Video is handled differently than audio since we can not transcode. */
10271       if (needvideo) {
10272          ast_str_append(&m_video, 0, "m=video %d RTP/AVP", ntohs(vdest.sin_port));
10273 
10274          /* Build max bitrate string */
10275          if (p->maxcallbitrate)
10276             snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
10277          if (debug) 
10278             ast_verbose("Video is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(vdest.sin_port));  
10279       }
10280 
10281       /* Ok, we need text. Let's add what we need for text and set codecs.
10282          Text is handled differently than audio since we can not transcode. */
10283       if (needtext) {
10284          if (sipdebug_text)
10285             ast_verbose("Lets set up the text sdp\n");
10286          /* Determine text destination */
10287          if (p->tredirip.sin_addr.s_addr) {
10288             tdest.sin_addr = p->tredirip.sin_addr;
10289             tdest.sin_port = p->tredirip.sin_port;
10290          } else {
10291             tdest.sin_addr = p->ourip.sin_addr;
10292             tdest.sin_port = tsin.sin_port;
10293          }
10294          ast_str_append(&m_text, 0, "m=text %d RTP/AVP", ntohs(tdest.sin_port));
10295          if (debug) /* XXX should I use tdest below ? */
10296             ast_verbose("Text is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(tsin.sin_port)); 
10297 
10298       }
10299 
10300       /* Start building generic SDP headers */
10301 
10302       /* We break with the "recommendation" and send our IP, in order that our
10303          peer doesn't have to ast_gethostbyname() us */
10304 
10305       ast_str_append(&m_audio, 0, "m=audio %d RTP/AVP", ntohs(dest.sin_port));
10306 
10307       if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR)
10308          hold = "a=recvonly\r\n";
10309       else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE)
10310          hold = "a=inactive\r\n";
10311       else
10312          hold = "a=sendrecv\r\n";
10313 
10314       /* Now, start adding audio codecs. These are added in this order:
10315          - First what was requested by the calling channel
10316          - Then preferences in order from sip.conf device config for this peer/user
10317          - Then other codecs in capabilities, including video
10318       */
10319 
10320       /* Prefer the audio codec we were requested to use, first, no matter what 
10321          Note that p->prefcodec can include video codecs, so mask them out
10322       */
10323       if (capability & p->prefcodec) {
10324          int codec = p->prefcodec & AST_FORMAT_AUDIO_MASK;
10325 
10326          add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
10327          alreadysent |= codec;
10328       }
10329 
10330       /* Start by sending our preferred audio/video codecs */
10331       for (x = 0; x < 32; x++) {
10332          int codec;
10333 
10334          if (!(codec = ast_codec_pref_index(&p->prefs, x)))
10335             break; 
10336 
10337          if (!(capability & codec))
10338             continue;
10339 
10340          if (alreadysent & codec)
10341             continue;
10342 
10343          add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
10344          alreadysent |= codec;
10345       }
10346 
10347       /* Now send any other common audio and video codecs, and non-codec formats: */
10348       for (x = 1; x <= (needtext ? AST_FORMAT_TEXT_MASK : (needvideo ? AST_FORMAT_VIDEO_MASK : AST_FORMAT_AUDIO_MASK)); x <<= 1) {
10349          if (!(capability & x))  /* Codec not requested */
10350             continue;
10351 
10352          if (alreadysent & x) /* Already added to SDP */
10353             continue;
10354 
10355          if (x & AST_FORMAT_AUDIO_MASK)
10356             add_codec_to_sdp(p, x, &m_audio, &a_audio, debug, &min_audio_packet_size);
10357          else if (x & AST_FORMAT_VIDEO_MASK)
10358             add_vcodec_to_sdp(p, x, &m_video, &a_video, debug, &min_video_packet_size);
10359          else if (x & AST_FORMAT_TEXT_MASK)
10360             add_tcodec_to_sdp(p, x, &m_text, &a_text, debug, &min_text_packet_size);
10361       }
10362 
10363       /* Now add DTMF RFC2833 telephony-event as a codec */
10364       for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
10365          if (!(p->jointnoncodeccapability & x))
10366             continue;
10367 
10368          add_noncodec_to_sdp(p, x, &m_audio, &a_audio, debug);
10369       }
10370 
10371       ast_debug(3, "-- Done with adding codecs to SDP\n");
10372 
10373       if (!p->owner || !ast_internal_timing_enabled(p->owner))
10374          ast_str_append(&a_audio, 0, "a=silenceSupp:off - - - -\r\n");
10375 
10376       if (min_audio_packet_size)
10377          ast_str_append(&a_audio, 0, "a=ptime:%d\r\n", min_audio_packet_size);
10378 
10379       /* XXX don't think you can have ptime for video */
10380       if (min_video_packet_size)
10381          ast_str_append(&a_video, 0, "a=ptime:%d\r\n", min_video_packet_size);
10382 
10383       /* XXX don't think you can have ptime for text */
10384       if (min_text_packet_size)
10385          ast_str_append(&a_text, 0, "a=ptime:%d\r\n", min_text_packet_size);
10386  
10387       if (m_audio->len - m_audio->used < 2 || m_video->len - m_video->used < 2 ||
10388           m_text->len - m_text->used < 2 || a_text->len - a_text->used < 2 ||
10389           a_audio->len - a_audio->used < 2 || a_video->len - a_video->used < 2)
10390          ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
10391    }
10392 
10393    if (add_t38) {
10394       /* Our T.38 end is */
10395       ast_udptl_get_us(p->udptl, &udptlsin);
10396 
10397       /* Determine T.38 UDPTL destination */
10398       if (p->udptlredirip.sin_addr.s_addr) {
10399          udptldest.sin_port = p->udptlredirip.sin_port;
10400          udptldest.sin_addr = p->udptlredirip.sin_addr;
10401       } else {
10402          udptldest.sin_addr = p->ourip.sin_addr;
10403          udptldest.sin_port = udptlsin.sin_port;
10404       }
10405 
10406       if (debug)
10407          ast_debug(1, "T.38 UDPTL is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(udptlsin.sin_port));
10408 
10409       /* We break with the "recommendation" and send our IP, in order that our
10410          peer doesn't have to ast_gethostbyname() us */
10411 
10412       ast_str_append(&m_modem, 0, "m=image %d udptl t38\r\n", ntohs(udptldest.sin_port));
10413 
10414       ast_str_append(&a_modem, 0, "a=T38FaxVersion:%d\r\n", p->t38.our_parms.version);
10415       ast_str_append(&a_modem, 0, "a=T38MaxBitRate:%d\r\n", t38_get_rate(p->t38.our_parms.rate));
10416       if (p->t38.our_parms.fill_bit_removal) {
10417          ast_str_append(&a_modem, 0, "a=T38FaxFillBitRemoval\r\n");
10418       }
10419       if (p->t38.our_parms.transcoding_mmr) {
10420          ast_str_append(&a_modem, 0, "a=T38FaxTranscodingMMR\r\n");
10421       }
10422       if (p->t38.our_parms.transcoding_jbig) {
10423          ast_str_append(&a_modem, 0, "a=T38FaxTranscodingJBIG\r\n");
10424       }
10425       switch (p->t38.our_parms.rate_management) {
10426       case AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF:
10427          ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:transferredTCF\r\n");
10428          break;
10429       case AST_T38_RATE_MANAGEMENT_LOCAL_TCF:
10430          ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:localTCF\r\n");
10431          break;
10432       }
10433       ast_str_append(&a_modem, 0, "a=T38FaxMaxDatagram:%u\r\n", ast_udptl_get_local_max_datagram(p->udptl));
10434       switch (ast_udptl_get_error_correction_scheme(p->udptl)) {
10435       case UDPTL_ERROR_CORRECTION_NONE:
10436          break;
10437       case UDPTL_ERROR_CORRECTION_FEC:
10438          ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPFEC\r\n");
10439          break;
10440       case UDPTL_ERROR_CORRECTION_REDUNDANCY:
10441          ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPRedundancy\r\n");
10442          break;
10443       }
10444    }
10445 
10446    if (needaudio)
10447       ast_str_append(&m_audio, 0, "\r\n");
10448    if (needvideo)
10449       ast_str_append(&m_video, 0, "\r\n");
10450    if (needtext)
10451       ast_str_append(&m_text, 0, "\r\n");
10452 
10453    add_header(resp, "Content-Type", "application/sdp");
10454    add_content(resp, version);
10455    add_content(resp, owner);
10456    add_content(resp, subject);
10457    add_content(resp, connection);
10458    if (needvideo)    /* only if video response is appropriate */
10459       add_content(resp, bandwidth);
10460    add_content(resp, session_time);
10461    if (needaudio) {
10462       add_content(resp, m_audio->str);
10463       add_content(resp, a_audio->str);
10464       add_content(resp, hold);
10465    } else if (p->offered_media[SDP_AUDIO].offered) {
10466       snprintf(dummy_answer, sizeof(dummy_answer), "m=audio 0 RTP/AVP %s\r\n", p->offered_media[SDP_AUDIO].text);
10467       add_content(resp, dummy_answer);
10468    }
10469    if (needvideo) { /* only if video response is appropriate */
10470       add_content(resp, m_video->str);
10471       add_content(resp, a_video->str);
10472       add_content(resp, hold);   /* Repeat hold for the video stream */
10473    } else if (p->offered_media[SDP_VIDEO].offered) {
10474       snprintf(dummy_answer, sizeof(dummy_answer), "m=video 0 RTP/AVP %s\r\n", p->offered_media[SDP_VIDEO].text);
10475       add_content(resp, dummy_answer);
10476    }
10477    if (needtext) { /* only if text response is appropriate */
10478       add_content(resp, m_text->str);
10479       add_content(resp, a_text->str);
10480       add_content(resp, hold);   /* Repeat hold for the text stream */
10481    } else if (p->offered_media[SDP_TEXT].offered) {
10482       snprintf(dummy_answer, sizeof(dummy_answer), "m=text 0 RTP/AVP %s\r\n", p->offered_media[SDP_TEXT].text);
10483       add_content(resp, dummy_answer);
10484    }
10485    if (add_t38) {
10486       add_content(resp, m_modem->str);
10487       add_content(resp, a_modem->str);
10488    } else if (p->offered_media[SDP_IMAGE].offered) {
10489       add_content(resp, "m=image 0 udptl t38\r\n");
10490    }
10491 
10492    /* Update lastrtprx when we send our SDP */
10493    p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
10494 
10495    ast_debug(3, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, capability));
10496 
10497    return AST_SUCCESS;
10498 }
10499 
10500 /*! \brief Used for 200 OK and 183 early media */
10501 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
10502 {
10503    struct sip_request resp;
10504    int seqno;
10505    
10506    if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
10507       ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
10508       return -1;
10509    }
10510    respprep(&resp, p, msg, req);
10511    if (p->udptl) {
10512       add_sdp(&resp, p, 0, 0, 1);
10513    } else 
10514       ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
10515    if (retrans && !p->pendinginvite)
10516       p->pendinginvite = seqno;     /* Buggy clients sends ACK on RINGING too */
10517    return send_response(p, &resp, retrans, seqno);
10518 }
10519 
10520 /*! \brief copy SIP request (mostly used to save request for responses) */
10521 static void copy_request(struct sip_request *dst, const struct sip_request *src)
10522 {
10523    /* XXX this function can encounter memory allocation errors, perhaps it
10524     * should return a value */
10525 
10526    struct ast_str *duplicate = dst->data;
10527    struct ast_str *duplicate_content = dst->content;
10528 
10529    /* copy the entire request then restore the original data and content
10530     * members from the dst request */
10531    memcpy(dst, src, sizeof(*dst));
10532    dst->data = duplicate;
10533    dst->content = duplicate_content;
10534 
10535    /* copy the data into the dst request */
10536    if (!dst->data && !(dst->data = ast_str_create(ast_str_strlen(src->data) + 1)))
10537       return;
10538    ast_str_copy_string(&dst->data, src->data);
10539 
10540    /* copy the content into the dst request (if it exists) */
10541    if (src->content) {
10542       if (!dst->content && !(dst->content = ast_str_create(ast_str_strlen(src->content) + 1)))
10543          return;
10544       ast_str_copy_string(&dst->content, src->content);
10545    }
10546 }
10547 
10548 /*! \brief Used for 200 OK and 183 early media 
10549    \return Will return XMIT_ERROR for network errors.
10550 */
10551 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp)
10552 {
10553    struct sip_request resp;
10554    int seqno;
10555    if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
10556       ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
10557       return -1;
10558    }
10559    respprep(&resp, p, msg, req);
10560    if (p->rtp) {
10561       if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
10562          ast_debug(1, "Setting framing from config on incoming call\n");
10563          ast_rtp_codec_setpref(p->rtp, &p->prefs);
10564       }
10565       try_suggested_sip_codec(p);
10566       if (p->t38.state == T38_ENABLED) {
10567          add_sdp(&resp, p, oldsdp, TRUE, TRUE);
10568       } else {
10569          add_sdp(&resp, p, oldsdp, TRUE, FALSE);
10570       }
10571    } else 
10572       ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
10573    if (reliable && !p->pendinginvite)
10574       p->pendinginvite = seqno;     /* Buggy clients sends ACK on RINGING too */
10575    return send_response(p, &resp, reliable, seqno);
10576 }
10577 
10578 /*! \brief Parse first line of incoming SIP request */
10579 static int determine_firstline_parts(struct sip_request *req) 
10580 {
10581    char *e = ast_skip_blanks(req->data->str);   /* there shouldn't be any */
10582    char *local_rlPart1;
10583 
10584    if (!*e)
10585       return -1;
10586    req->rlPart1 = e - req->data->str;  /* method or protocol */
10587    local_rlPart1 = e;
10588    e = ast_skip_nonblanks(e);
10589    if (*e)
10590       *e++ = '\0';
10591    /* Get URI or status code */
10592    e = ast_skip_blanks(e);
10593    if ( !*e )
10594       return -1;
10595    ast_trim_blanks(e);
10596 
10597    if (!strcasecmp(local_rlPart1, "SIP/2.0") ) { /* We have a response */
10598       if (strlen(e) < 3)   /* status code is 3 digits */
10599          return -1;
10600       req->rlPart2 = e - req->data->str;
10601    } else { /* We have a request */
10602       if ( *e == '<' ) { /* XXX the spec says it must not be in <> ! */
10603          ast_debug(3, "Oops. Bogus uri in <> %s\n", e);
10604          e++;
10605          if (!*e)
10606             return -1; 
10607       }
10608       req->rlPart2 = e - req->data->str;  /* URI */
10609       e = ast_skip_nonblanks(e);
10610       if (*e)
10611          *e++ = '\0';
10612       e = ast_skip_blanks(e);
10613       if (strcasecmp(e, "SIP/2.0") ) {
10614          ast_debug(3, "Skipping packet - Bad request protocol %s\n", e);
10615          return -1;
10616       }
10617    }
10618    return 1;
10619 }
10620 
10621 /*! \brief Transmit reinvite with SDP
10622 \note    A re-invite is basically a new INVITE with the same CALL-ID and TAG as the
10623    INVITE that opened the SIP dialogue 
10624    We reinvite so that the audio stream (RTP) go directly between
10625    the SIP UAs. SIP Signalling stays with * in the path.
10626    
10627    If t38version is TRUE, we send T38 SDP for re-invite from audio/video to
10628    T38 UDPTL transmission on the channel
10629 
10630     If oldsdp is TRUE then the SDP version number is not incremented. This
10631     is needed for Session-Timers so we can send a re-invite to refresh the
10632     SIP session without modifying the media session. 
10633 */
10634 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp)
10635 {
10636    struct sip_request req;
10637    
10638    reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ?  SIP_UPDATE : SIP_INVITE, 0, 1);
10639 
10640    add_header(&req, "Allow", ALLOWED_METHODS);
10641    add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
10642    if (sipdebug) {
10643       if (oldsdp == TRUE)
10644          add_header(&req, "X-asterisk-Info", "SIP re-invite (Session-Timers)");
10645       else
10646          add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
10647    }
10648 
10649    if (p->do_history)
10650       append_history(p, "ReInv", "Re-invite sent");
10651    memset(p->offered_media, 0, sizeof(p->offered_media));
10652 
10653    if (t38version)
10654       add_sdp(&req, p, oldsdp, FALSE, TRUE);
10655    else
10656       add_sdp(&req, p, oldsdp, TRUE, FALSE);
10657 
10658    /* Use this as the basis */
10659    initialize_initreq(p, &req);
10660    p->lastinvite = p->ocseq;
10661    ast_set_flag(&p->flags[0], SIP_OUTGOING);       /* Change direction of this dialog */
10662 
10663    return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
10664 }
10665 
10666 /* \brief Remove URI parameters at end of URI, not in username part though */
10667 static char *remove_uri_parameters(char *uri)
10668 {
10669    char *atsign;
10670    atsign = strchr(uri, '@'); /* First, locate the at sign */
10671    if (!atsign)
10672       atsign = uri;  /* Ok hostname only, let's stick with the rest */
10673    atsign = strchr(atsign, ';'); /* Locate semi colon */
10674    if (atsign)
10675       *atsign = '\0';   /* Kill at the semi colon */
10676    return uri;
10677 }
10678 
10679 /*! \brief Check Contact: URI of SIP message */
10680 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
10681 {
10682    char stripped[SIPBUFSIZE];
10683    char *c;
10684 
10685    ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
10686    c = get_in_brackets(stripped);
10687    /* Cut the URI at the at sign after the @, not in the username part */
10688    c = remove_uri_parameters(c);
10689    if (!ast_strlen_zero(c))
10690       ast_string_field_set(p, uri, c);
10691 
10692 }
10693 
10694 /*! \brief Build contact header - the contact header we send out */
10695 static void build_contact(struct sip_pvt *p)
10696 {
10697 
10698    int ourport = ntohs(p->ourip.sin_port);
10699    /* only add port if it's non-standard for the transport type */
10700    if (!sip_standard_port(p->socket.type, ourport)) {
10701       if (p->socket.type == SIP_TRANSPORT_UDP)
10702          ast_string_field_build(p, our_contact, "<sip:%s%s%s:%d>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr), ourport);
10703       else
10704          ast_string_field_build(p, our_contact, "<sip:%s%s%s:%d;transport=%s>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr), ourport, get_transport(p->socket.type));
10705    } else {
10706       if (p->socket.type == SIP_TRANSPORT_UDP)
10707          ast_string_field_build(p, our_contact, "<sip:%s%s%s>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr));
10708       else
10709          ast_string_field_build(p, our_contact, "<sip:%s%s%s;transport=%s>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr), get_transport(p->socket.type));
10710    }
10711 }
10712 
10713 /*! \brief Build the Remote Party-ID & From using callingpres options */
10714 static void build_rpid(struct sip_pvt *p)
10715 {
10716    int send_pres_tags = TRUE;
10717    const char *privacy=NULL;
10718    const char *screen=NULL;
10719    char buf[256];
10720    const char *clid = default_callerid;
10721    const char *clin = NULL;
10722    const char *fromdomain;
10723 
10724    if (!ast_strlen_zero(p->rpid) || !ast_strlen_zero(p->rpid_from))  
10725       return;
10726 
10727    if (p->owner && !ast_strlen_zero(p->owner->cid.cid_num))
10728       clid = p->owner->cid.cid_num;
10729    if (p->owner && p->owner->cid.cid_name)
10730       clin = p->owner->cid.cid_name;
10731    if (ast_strlen_zero(clin))
10732       clin = clid;
10733 
10734    switch (p->callingpres) {
10735    case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
10736       privacy = "off";
10737       screen = "no";
10738       break;
10739    case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
10740       privacy = "off";
10741       screen = "yes";
10742       break;
10743    case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
10744       privacy = "off";
10745       screen = "no";
10746       break;
10747    case AST_PRES_ALLOWED_NETWORK_NUMBER:
10748       privacy = "off";
10749       screen = "yes";
10750       break;
10751    case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
10752       privacy = "full";
10753       screen = "no";
10754       break;
10755    case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
10756       privacy = "full";
10757       screen = "yes";
10758       break;
10759    case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
10760       privacy = "full";
10761       screen = "no";
10762       break;
10763    case AST_PRES_PROHIB_NETWORK_NUMBER:
10764       privacy = "full";
10765       screen = "yes";
10766       break;
10767    case AST_PRES_NUMBER_NOT_AVAILABLE:
10768       send_pres_tags = FALSE;
10769       break;
10770    default:
10771       ast_log(LOG_WARNING, "Unsupported callingpres (%d)\n", p->callingpres);
10772       if ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)
10773          privacy = "full";
10774       else
10775          privacy = "off";
10776       screen = "no";
10777       break;
10778    }
10779    
10780    fromdomain = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr));
10781 
10782    snprintf(buf, sizeof(buf), "\"%s\" <sip:%s@%s>", clin, clid, fromdomain);
10783    if (send_pres_tags)
10784       snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ";privacy=%s;screen=%s", privacy, screen);
10785    ast_string_field_set(p, rpid, buf);
10786 
10787    ast_string_field_build(p, rpid_from, "\"%s\" <sip:%s@%s>;tag=%s", clin,
10788                 S_OR(p->fromuser, clid),
10789                 fromdomain, p->tag);
10790 }
10791 
10792 /*! \brief Initiate new SIP request to peer/user */
10793 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod)
10794 {
10795    struct ast_str *invite = ast_str_alloca(256);
10796    char from[256];
10797    char to[256];
10798    char tmp_n[SIPBUFSIZE/2];  /* build a local copy of 'n' if needed */
10799    char tmp_l[SIPBUFSIZE/2];  /* build a local copy of 'l' if needed */
10800    const char *l = NULL;   /* XXX what is this, exactly ? */
10801    const char *n = NULL;   /* XXX what is this, exactly ? */
10802    const char *d = NULL;   /* domain in from header */
10803    const char *urioptions = "";
10804    int ourport;
10805 
10806    if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
10807       const char *s = p->username;  /* being a string field, cannot be NULL */
10808 
10809       /* Test p->username against allowed characters in AST_DIGIT_ANY
10810          If it matches the allowed characters list, then sipuser = ";user=phone"
10811          If not, then sipuser = ""
10812       */
10813       /* + is allowed in first position in a tel: uri */
10814       if (*s == '+')
10815          s++;
10816       for (; *s; s++) {
10817          if (!strchr(AST_DIGIT_ANYNUM, *s) )
10818             break;
10819       }
10820       /* If we have only digits, add ;user=phone to the uri */
10821       if (!*s)
10822          urioptions = ";user=phone";
10823    }
10824 
10825 
10826    snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
10827 
10828    d = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr));
10829    if (p->owner) {
10830       l = p->owner->cid.cid_num;
10831       n = p->owner->cid.cid_name;
10832    }
10833    /* if we are not sending RPID and user wants his callerid restricted */
10834    if (!ast_test_flag(&p->flags[0], SIP_SENDRPID) &&
10835        ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)) {
10836       l = CALLERID_UNKNOWN;
10837       n = l;
10838       d = FROMDOMAIN_INVALID;
10839    }
10840    if (ast_strlen_zero(l))
10841       l = default_callerid;
10842    if (ast_strlen_zero(n))
10843       n = l;
10844    /* Allow user to be overridden */
10845    if (!ast_strlen_zero(p->fromuser))
10846       l = p->fromuser;
10847    else /* Save for any further attempts */
10848       ast_string_field_set(p, fromuser, l);
10849 
10850    /* Allow user to be overridden */
10851    if (!ast_strlen_zero(p->fromname))
10852       n = p->fromname;
10853    else /* Save for any further attempts */
10854       ast_string_field_set(p, fromname, n);
10855 
10856    if (sip_cfg.pedanticsipchecking) {
10857       ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
10858       n = tmp_n;
10859       ast_uri_encode(l, tmp_l, sizeof(tmp_l), 0);
10860       l = tmp_l;
10861    }
10862 
10863    ourport = ntohs(p->ourip.sin_port);
10864    if (!sip_standard_port(p->socket.type, ourport) && ast_strlen_zero(p->fromdomain))
10865       snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=%s", n, l, d, ourport, p->tag);
10866    else
10867       snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, l, d, p->tag);
10868 
10869    /* If we're calling a registered SIP peer, use the fullcontact to dial to the peer */
10870    if (!ast_strlen_zero(p->fullcontact)) {
10871       /* If we have full contact, trust it */
10872       ast_str_append(&invite, 0, "%s", p->fullcontact);
10873    } else {
10874       /* Otherwise, use the username while waiting for registration */
10875       ast_str_append(&invite, 0, "sip:");
10876       if (!ast_strlen_zero(p->username)) {
10877          n = p->username;
10878          if (sip_cfg.pedanticsipchecking) {
10879             ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
10880             n = tmp_n;
10881          }
10882          ast_str_append(&invite, 0, "%s@", n);
10883       }
10884       ast_str_append(&invite, 0, "%s", p->tohost);
10885       if (p->portinuri)
10886          ast_str_append(&invite, 0, ":%d", ntohs(p->sa.sin_port));
10887       ast_str_append(&invite, 0, "%s", urioptions);
10888    }
10889 
10890    /* If custom URI options have been provided, append them */
10891    if (p->options && !ast_strlen_zero(p->options->uri_options))
10892       ast_str_append(&invite, 0, ";%s", p->options->uri_options);
10893    
10894    /* This is the request URI, which is the next hop of the call
10895       which may or may not be the destination of the call
10896    */
10897    ast_string_field_set(p, uri, invite->str);
10898   
10899    if (!ast_strlen_zero(p->todnid)) {
10900       /*! \todo Need to add back the VXML URL here at some point, possibly use build_string for all this junk */
10901       if (!strchr(p->todnid, '@')) {
10902          /* We have no domain in the dnid */
10903          snprintf(to, sizeof(to), "<sip:%s@%s>%s%s", p->todnid, p->tohost, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
10904       } else {
10905          snprintf(to, sizeof(to), "<sip:%s>%s%s", p->todnid, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
10906       }
10907    } else {
10908       if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) { 
10909          /* If this is a NOTIFY, use the From: tag in the subscribe (RFC 3265) */
10910          snprintf(to, sizeof(to), "<%s%s>;tag=%s", (strncasecmp(p->uri, "sip:", 4) ? "sip:" : ""), p->uri, p->theirtag);
10911       } else if (p->options && p->options->vxml_url) {
10912          /* If there is a VXML URL append it to the SIP URL */
10913          snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
10914       } else 
10915          snprintf(to, sizeof(to), "<%s>", p->uri);
10916    }
10917 
10918    init_req(req, sipmethod, p->uri);
10919    /* now tmp_n is available so reuse it to build the CSeq */
10920    snprintf(tmp_n, sizeof(tmp_n), "%d %s", ++p->ocseq, sip_methods[sipmethod].text);
10921 
10922    add_header(req, "Via", p->via);
10923    add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
10924    /* This will be a no-op most of the time. However, under certain circumstances,
10925     * NOTIFY messages will use this function for preparing the request and should
10926     * have Route headers present.
10927     */
10928    add_route(req, p->route);
10929 
10930    /* Build Remote Party-ID and From */
10931    if (ast_test_flag(&p->flags[0], SIP_SENDRPID) && (sipmethod == SIP_INVITE)) {
10932       build_rpid(p);
10933       add_header(req, "From", p->rpid_from);
10934    } else 
10935       add_header(req, "From", from);
10936    add_header(req, "To", to);
10937    ast_string_field_set(p, exten, l);
10938    build_contact(p);
10939    add_header(req, "Contact", p->our_contact);
10940    add_header(req, "Call-ID", p->callid);
10941    add_header(req, "CSeq", tmp_n);
10942    if (!ast_strlen_zero(global_useragent))
10943       add_header(req, "User-Agent", global_useragent);
10944    if (!ast_strlen_zero(p->rpid))
10945       add_header(req, "Remote-Party-ID", p->rpid);
10946 }
10947 
10948 /*! \brief Build REFER/INVITE/OPTIONS/SUBSCRIBE message and transmit it 
10949    \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
10950  \param p sip_pvt structure
10951  \param sdp unknown 
10952  \param sipmethod unknown 
10953  
10954 */
10955 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init)
10956 {
10957    struct sip_request req;
10958    struct ast_variable *var;
10959    
10960    req.method = sipmethod;
10961    if (init) {/* Bump branch even on initial requests */
10962       p->branch ^= ast_random();
10963       p->invite_branch = p->branch;
10964       build_via(p);
10965    }
10966    if (init > 1)
10967       initreqprep(&req, p, sipmethod);
10968    else
10969       /* If init=1, we should not generate a new branch. If it's 0, we need a new branch. */
10970       reqprep(&req, p, sipmethod, 0, init ? 0 : 1);
10971       
10972    if (p->options && p->options->auth)
10973       add_header(&req, p->options->authheader, p->options->auth);
10974    append_date(&req);
10975    if (sipmethod == SIP_REFER) { /* Call transfer */
10976       if (p->refer) {
10977          char buf[SIPBUFSIZE];
10978          if (!ast_strlen_zero(p->refer->refer_to))
10979             add_header(&req, "Refer-To", p->refer->refer_to);
10980          if (!ast_strlen_zero(p->refer->referred_by)) {
10981             snprintf(buf, sizeof(buf), "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
10982             add_header(&req, "Referred-By", buf);
10983          }
10984       }
10985    } else if (sipmethod == SIP_SUBSCRIBE) { /* We only support sending MWI subscriptions right now */
10986       char buf[SIPBUFSIZE];
10987 
10988       add_header(&req, "Event", "message-summary");
10989       add_header(&req, "Accept", "application/simple-message-summary");
10990       snprintf(buf, sizeof(buf), "%d", mwi_expiry);
10991       add_header(&req, "Expires", buf);
10992    }
10993 
10994    /* This new INVITE is part of an attended transfer. Make sure that the
10995    other end knows and replace the current call with this new call */
10996    if (p->options && !ast_strlen_zero(p->options->replaces)) {
10997       add_header(&req, "Replaces", p->options->replaces);
10998       add_header(&req, "Require", "replaces");
10999    }
11000 
11001    /* Add Session-Timers related headers */
11002    if (st_get_mode(p) == SESSION_TIMER_MODE_ORIGINATE) {
11003       char i2astr[10];
11004 
11005       if (!p->stimer->st_interval)
11006          p->stimer->st_interval = st_get_se(p, TRUE);
11007 
11008       p->stimer->st_active = TRUE;
11009       
11010       snprintf(i2astr, sizeof(i2astr), "%d", p->stimer->st_interval);
11011       add_header(&req, "Session-Expires", i2astr);
11012       snprintf(i2astr, sizeof(i2astr), "%d", st_get_se(p, FALSE));
11013       add_header(&req, "Min-SE", i2astr);
11014    }
11015 
11016    add_header(&req, "Allow", ALLOWED_METHODS);
11017    add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
11018 
11019    if(p->notify_headers) {
11020       char buf[512];
11021       for (var = p->notify_headers; var; var = var->next) {
11022          ast_copy_string(buf, var->value, sizeof(buf));
11023          add_header(&req, var->name, ast_unescape_semicolon(buf));
11024       }
11025    }
11026    if (p->options && p->options->addsipheaders && p->owner) {
11027       struct ast_channel *chan = p->owner; /* The owner channel */
11028       struct varshead *headp;
11029    
11030       ast_channel_lock(chan);
11031 
11032       headp = &chan->varshead;
11033 
11034       if (!headp)
11035          ast_log(LOG_WARNING, "No Headp for the channel...ooops!\n");
11036       else {
11037          const struct ast_var_t *current;
11038          AST_LIST_TRAVERSE(headp, current, entries) {  
11039             /* SIPADDHEADER: Add SIP header to outgoing call */
11040             if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
11041                char *content, *end;
11042                const char *header = ast_var_value(current);
11043                char *headdup = ast_strdupa(header);
11044 
11045                /* Strip of the starting " (if it's there) */
11046                if (*headdup == '"')
11047                   headdup++;
11048                if ((content = strchr(headdup, ':'))) {
11049                   *content++ = '\0';
11050                   content = ast_skip_blanks(content); /* Skip white space */
11051                   /* Strip the ending " (if it's there) */
11052                   end = content + strlen(content) -1; 
11053                   if (*end == '"')
11054                      *end = '\0';
11055                
11056                   add_header(&req, headdup, content);
11057                   if (sipdebug)
11058                      ast_debug(1, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
11059                }
11060             }
11061          }
11062       }
11063 
11064       ast_channel_unlock(chan);
11065    }
11066    if (sdp) {
11067       memset(p->offered_media, 0, sizeof(p->offered_media));
11068       if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
11069          ast_debug(1, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
11070          add_sdp(&req, p, FALSE, FALSE, TRUE);
11071       } else if (p->rtp) 
11072          add_sdp(&req, p, FALSE, TRUE, FALSE);
11073    }
11074 
11075    if (!p->initreq.headers || init > 2)
11076       initialize_initreq(p, &req);
11077    p->lastinvite = p->ocseq;
11078    return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
11079 }
11080 
11081 /*! \brief Send a subscription or resubscription for MWI */
11082 static int sip_subscribe_mwi_do(const void *data)
11083 {
11084    struct sip_subscription_mwi *mwi = (struct sip_subscription_mwi*)data;
11085    
11086    if (!mwi) {
11087       return -1;
11088    }
11089    
11090    mwi->resub = -1;
11091    __sip_subscribe_mwi_do(mwi);
11092    ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
11093    
11094    return 0;
11095 }
11096 
11097 /*! \brief Actually setup an MWI subscription or resubscribe */
11098 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi)
11099 {
11100    /* If we have no DNS manager let's do a lookup */
11101    if (!mwi->dnsmgr) {
11102       char transport[MAXHOSTNAMELEN];
11103       snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(mwi->transport), get_srv_protocol(mwi->transport));
11104       ast_dnsmgr_lookup(mwi->hostname, &mwi->us, &mwi->dnsmgr, sip_cfg.srvlookup ? transport : NULL);
11105    }
11106 
11107    /* If we already have a subscription up simply send a resubscription */
11108    if (mwi->call) {
11109       transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 0);
11110       return 0;
11111    }
11112    
11113    /* Create a dialog that we will use for the subscription */
11114    if (!(mwi->call = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
11115       return -1;
11116    }
11117 
11118    ref_proxy(mwi->call, obproxy_get(mwi->call, NULL));
11119 
11120    if (!mwi->us.sin_port && mwi->portno) {
11121       mwi->us.sin_port = htons(mwi->portno);
11122    }
11123    
11124    /* Setup the destination of our subscription */
11125    if (create_addr(mwi->call, mwi->hostname, &mwi->us, 0)) {
11126       dialog_unlink_all(mwi->call, TRUE, TRUE);
11127       mwi->call = dialog_unref(mwi->call, "unref dialog after unlink_all");
11128       return 0;
11129    }
11130    
11131    if (!mwi->dnsmgr && mwi->portno) {
11132       mwi->call->sa.sin_port = htons(mwi->portno);
11133       mwi->call->recv.sin_port = htons(mwi->portno);
11134    } else {
11135       mwi->portno = ntohs(mwi->call->sa.sin_port);
11136    }
11137    
11138    /* Set various other information */
11139    if (!ast_strlen_zero(mwi->authuser)) {
11140       ast_string_field_set(mwi->call, peername, mwi->authuser);
11141       ast_string_field_set(mwi->call, authname, mwi->authuser);
11142       ast_string_field_set(mwi->call, fromuser, mwi->authuser);
11143    } else {
11144       ast_string_field_set(mwi->call, peername, mwi->username);
11145       ast_string_field_set(mwi->call, authname, mwi->username);
11146       ast_string_field_set(mwi->call, fromuser, mwi->username);
11147    }
11148    ast_string_field_set(mwi->call, username, mwi->username);
11149    if (!ast_strlen_zero(mwi->secret)) {
11150       ast_string_field_set(mwi->call, peersecret, mwi->secret);
11151    }
11152    set_socket_transport(&mwi->call->socket, mwi->transport);
11153    mwi->call->socket.port = htons(mwi->portno);
11154    ast_sip_ouraddrfor(&mwi->call->sa.sin_addr, &mwi->call->ourip, mwi->call);
11155    build_contact(mwi->call);
11156    build_via(mwi->call);
11157    build_callid_pvt(mwi->call);
11158    ast_set_flag(&mwi->call->flags[0], SIP_OUTGOING);
11159    
11160    /* Associate the call with us */
11161    mwi->call->mwi = ASTOBJ_REF(mwi);
11162    
11163    /* Actually send the packet */
11164    transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 2);
11165 
11166    return 0;
11167 }
11168 
11169 static int find_calling_channel(struct ast_channel *c, void *data) {
11170    struct sip_pvt *p = data;
11171 
11172    return (c->pbx &&
11173          (!strcasecmp(c->macroexten, p->exten) || !strcasecmp(c->exten, p->exten)) &&
11174          (sip_cfg.notifycid == IGNORE_CONTEXT || !strcasecmp(c->context, p->context)));
11175 }
11176 
11177 /*! \brief Used in the SUBSCRIBE notification subsystem (RFC3265) */
11178 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
11179 {
11180    struct ast_str *tmp = ast_str_alloca(4000);
11181    char from[256], to[256];
11182    char *c, *mfrom, *mto;
11183    struct sip_request req;
11184    char hint[AST_MAX_EXTENSION];
11185    char *statestring = "terminated";
11186    const struct cfsubscription_types *subscriptiontype;
11187    enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
11188    char *pidfstate = "--";
11189    char *pidfnote= "Ready";
11190    
11191    memset(from, 0, sizeof(from));
11192    memset(to, 0, sizeof(to));
11193 
11194    switch (state) {
11195    case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
11196       statestring = (sip_cfg.notifyringing) ? "early" : "confirmed";
11197       local_state = NOTIFY_INUSE;
11198       pidfstate = "busy";
11199       pidfnote = "Ringing";
11200       break;
11201    case AST_EXTENSION_RINGING:
11202       statestring = "early";
11203       local_state = NOTIFY_INUSE;
11204       pidfstate = "busy";
11205       pidfnote = "Ringing";
11206       break;
11207    case AST_EXTENSION_INUSE:
11208       statestring = "confirmed";
11209       local_state = NOTIFY_INUSE;
11210       pidfstate = "busy";
11211       pidfnote = "On the phone";
11212       break;
11213    case AST_EXTENSION_BUSY:
11214       statestring = "confirmed";
11215       local_state = NOTIFY_CLOSED;
11216       pidfstate = "busy";
11217       pidfnote = "On the phone";
11218       break;
11219    case AST_EXTENSION_UNAVAILABLE:
11220       statestring = "terminated";
11221       local_state = NOTIFY_CLOSED;
11222       pidfstate = "away";
11223       pidfnote = "Unavailable";
11224       break;
11225    case AST_EXTENSION_ONHOLD:
11226       statestring = "confirmed";
11227       local_state = NOTIFY_CLOSED;
11228       pidfstate = "busy";
11229       pidfnote = "On hold";
11230       break;
11231    case AST_EXTENSION_NOT_INUSE:
11232    default:
11233       /* Default setting */
11234       break;
11235    }
11236 
11237    subscriptiontype = find_subscription_type(p->subscribed);
11238    
11239    /* Check which device/devices we are watching  and if they are registered */
11240    if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten)) {
11241       char *hint2 = hint, *individual_hint = NULL;
11242       int hint_count = 0, unavailable_count = 0;
11243 
11244       while ((individual_hint = strsep(&hint2, "&"))) {
11245          hint_count++;
11246 
11247          if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
11248             unavailable_count++;
11249       }
11250 
11251       /* If none of the hinted devices are registered, we will
11252        * override notification and show no availability.
11253        */
11254       if (hint_count > 0 && hint_count == unavailable_count) {
11255          local_state = NOTIFY_CLOSED;
11256          pidfstate = "away";
11257          pidfnote = "Not online";
11258       }
11259    }
11260 
11261    ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
11262    c = get_in_brackets(from);
11263    if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
11264       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
11265       return -1;
11266    }
11267    
11268    mfrom = remove_uri_parameters(c);
11269 
11270    ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
11271    c = get_in_brackets(to);
11272    if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
11273       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
11274       return -1;
11275    }
11276    mto = remove_uri_parameters(c);
11277 
11278    reqprep(&req, p, SIP_NOTIFY, 0, 1);
11279 
11280    
11281    add_header(&req, "Event", subscriptiontype->event);
11282    add_header(&req, "Content-Type", subscriptiontype->mediatype);
11283    switch(state) {
11284    case AST_EXTENSION_DEACTIVATED:
11285       if (timeout)
11286          add_header(&req, "Subscription-State", "terminated;reason=timeout");
11287       else {
11288          add_header(&req, "Subscription-State", "terminated;reason=probation");
11289          add_header(&req, "Retry-After", "60");
11290       }
11291       break;
11292    case AST_EXTENSION_REMOVED:
11293       add_header(&req, "Subscription-State", "terminated;reason=noresource");
11294       break;
11295    default:
11296       if (p->expiry)
11297          add_header(&req, "Subscription-State", "active");
11298       else  /* Expired */
11299          add_header(&req, "Subscription-State", "terminated;reason=timeout");
11300    }
11301    switch (p->subscribed) {
11302    case XPIDF_XML:
11303    case CPIM_PIDF_XML:
11304       ast_str_append(&tmp, 0,
11305          "<?xml version=\"1.0\"?>\n"
11306          "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n"
11307          "<presence>\n");
11308       ast_str_append(&tmp, 0, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
11309       ast_str_append(&tmp, 0, "<atom id=\"%s\">\n", p->exten);
11310       ast_str_append(&tmp, 0, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
11311       ast_str_append(&tmp, 0, "<status status=\"%s\" />\n", (local_state ==  NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
11312       ast_str_append(&tmp, 0, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
11313       ast_str_append(&tmp, 0, "</address>\n</atom>\n</presence>\n");
11314       break;
11315    case PIDF_XML: /* Eyebeam supports this format */
11316       ast_str_append(&tmp, 0,
11317          "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
11318          "<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);
11319       ast_str_append(&tmp, 0, "<pp:person><status>\n");
11320       if (pidfstate[0] != '-')
11321          ast_str_append(&tmp, 0, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
11322       ast_str_append(&tmp, 0, "</status></pp:person>\n");
11323       ast_str_append(&tmp, 0, "<note>%s</note>\n", pidfnote); /* Note */
11324       ast_str_append(&tmp, 0, "<tuple id=\"%s\">\n", p->exten); /* Tuple start */
11325       ast_str_append(&tmp, 0, "<contact priority=\"1\">%s</contact>\n", mto);
11326       if (pidfstate[0] == 'b') /* Busy? Still open ... */
11327          ast_str_append(&tmp, 0, "<status><basic>open</basic></status>\n");
11328       else
11329          ast_str_append(&tmp, 0, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
11330       ast_str_append(&tmp, 0, "</tuple>\n</presence>\n");
11331       break;
11332    case DIALOG_INFO_XML: /* SNOM subscribes in this format */
11333       ast_str_append(&tmp, 0, "<?xml version=\"1.0\"?>\n");
11334       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);
11335       if ((state & AST_EXTENSION_RINGING) && sip_cfg.notifyringing) {
11336          const char *local_display = p->exten;
11337          char *local_target = mto;
11338 
11339          /* There are some limitations to how this works.  The primary one is that the
11340             callee must be dialing the same extension that is being monitored.  Simply dialing
11341             the hint'd device is not sufficient. */
11342          if (sip_cfg.notifycid) {
11343             struct ast_channel *caller = ast_channel_search_locked(find_calling_channel, p);
11344 
11345             if (caller) {
11346                int need = strlen(caller->cid.cid_num) + strlen(p->fromdomain) + sizeof("sip:@");
11347                local_target = alloca(need);
11348                snprintf(local_target, need, "sip:%s@%s", caller->cid.cid_num, p->fromdomain);
11349                if (!(ast_strlen_zero(caller->cid.cid_name))) {
11350                   local_display = ast_strdupa(caller->cid.cid_name);
11351                }
11352                ast_channel_unlock(caller);
11353                caller = NULL;
11354             }
11355             /* We create a fake call-id which the phone will send back in an INVITE
11356              * Replaces header which we can grab and do some magic with. */
11357             ast_str_append(&tmp, 0, 
11358                   "<dialog id=\"%s\" call-id=\"pickup-%s\" direction=\"recipient\">\n"
11359                   "<remote>\n"
11360                   /* See the limitations of this above.  Luckily the phone seems to still be
11361                      happy when these values are not correct. */
11362                   "<identity display=\"%s\">%s</identity>\n"
11363                   "<target uri=\"%s\"/>\n"
11364                   "</remote>\n"
11365                   "<local>\n"
11366                   "<identity>%s</identity>\n"
11367                   "<target uri=\"%s\"/>\n"
11368                   "</local>\n",
11369                   p->exten, p->callid, local_display, local_target, local_target, mto, mto);
11370          } else {
11371             ast_str_append(&tmp, 0, "<dialog id=\"%s\" direction=\"recipient\">\n", p->exten);
11372          }
11373       } else {
11374          ast_str_append(&tmp, 0, "<dialog id=\"%s\">\n", p->exten);
11375       }
11376       ast_str_append(&tmp, 0, "<state>%s</state>\n", statestring);
11377       if (state == AST_EXTENSION_ONHOLD) {
11378          ast_str_append(&tmp, 0, "<local>\n<target uri=\"%s\">\n"
11379                                          "<param pname=\"+sip.rendering\" pvalue=\"no\"/>\n"
11380                                          "</target>\n</local>\n", mto);
11381       }
11382       ast_str_append(&tmp, 0, "</dialog>\n</dialog-info>\n");
11383       break;
11384    case NONE:
11385    default:
11386       break;
11387    }
11388 
11389    add_content(&req, tmp->str);
11390 
11391    p->pendinginvite = p->ocseq;  /* Remember that we have a pending NOTIFY in order not to confuse the NOTIFY subsystem */
11392 
11393    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11394 }
11395 
11396 /*! \brief Notify user of messages waiting in voicemail (RFC3842)
11397 \note - Notification only works for registered peers with mailbox= definitions
11398    in sip.conf
11399    - We use the SIP Event package message-summary
11400     MIME type defaults to  "application/simple-message-summary";
11401  */
11402 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten)
11403 {
11404    struct sip_request req;
11405    struct ast_str *out = ast_str_alloca(500);
11406    int ourport = ntohs(p->ourip.sin_port);
11407    const char *exten = S_OR(vmexten, default_vmexten);
11408 
11409    initreqprep(&req, p, SIP_NOTIFY);
11410    add_header(&req, "Event", "message-summary");
11411    add_header(&req, "Content-Type", default_notifymime);
11412    ast_str_append(&out, 0, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
11413 
11414    if (!ast_strlen_zero(p->fromdomain)) {
11415       ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, p->fromdomain);
11416    } else if (!sip_standard_port(p->socket.type, ourport)) {
11417       if (p->socket.type == SIP_TRANSPORT_UDP) {
11418          ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr), ourport);
11419       } else {
11420          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));
11421       }
11422    } else {
11423       if (p->socket.type == SIP_TRANSPORT_UDP) {
11424          ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr));
11425       } else {
11426          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));
11427       }
11428    }
11429    /* Cisco has a bug in the SIP stack where it can't accept the
11430       (0/0) notification. This can temporarily be disabled in
11431       sip.conf with the "buggymwi" option */
11432    ast_str_append(&out, 0, "Voice-Message: %d/%d%s\r\n",
11433       newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));
11434 
11435    if (p->subscribed) {
11436       if (p->expiry)
11437          add_header(&req, "Subscription-State", "active");
11438       else  /* Expired */
11439          add_header(&req, "Subscription-State", "terminated;reason=timeout");
11440    }
11441 
11442    add_content(&req, out->str);
11443 
11444    if (!p->initreq.headers) 
11445       initialize_initreq(p, &req);
11446    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11447 }
11448 
11449 /*! \brief Notify a transferring party of the status of transfer (RFC3515) */
11450 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
11451 {
11452    struct sip_request req;
11453    char tmp[SIPBUFSIZE/2];
11454    
11455    reqprep(&req, p, SIP_NOTIFY, 0, 1);
11456    snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
11457    add_header(&req, "Event", tmp);
11458    add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
11459    add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
11460    add_header(&req, "Allow", ALLOWED_METHODS);
11461    add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
11462 
11463    snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
11464    add_content(&req, tmp);
11465 
11466    if (!p->initreq.headers)
11467       initialize_initreq(p, &req);
11468 
11469    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11470 }
11471 
11472 /*! \brief Notify device with custom headers from sip_notify.conf */
11473 static int transmit_notify_custom(struct sip_pvt *p, struct ast_variable *vars) {
11474    struct sip_request req;
11475    struct ast_variable *var, *newvar;
11476 
11477    initreqprep(&req, p, SIP_NOTIFY);
11478 
11479    /* Copy notify vars and add headers */
11480    p->notify_headers = newvar = ast_variable_new("Subscription-State", "terminated", "");
11481    add_header(&req, newvar->name, newvar->value);
11482    for (var = vars; var; var = var->next) {
11483       char buf[512];
11484 
11485       if (!strcasecmp(var->name, "Content-Length")) {
11486          ast_debug(2, "Ignoring pair %s=%s\n", var->name, var->value);
11487          continue; /* ignore content-length, it is calculated automatically */
11488       }
11489 
11490       ast_debug(2, "  Adding pair %s=%s\n", var->name, var->value);
11491       ast_copy_string(buf, var->value, sizeof(buf));
11492       add_header(&req, var->name, ast_unescape_semicolon(buf));
11493       newvar->next = ast_variable_new(var->name, var->value, "");
11494       newvar = newvar->next;
11495    }
11496 
11497    if (!p->initreq.headers) { /* Initialize first request before sending */
11498       initialize_initreq(p, &req);
11499    }
11500 
11501    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11502 }
11503 
11504 static int manager_sipnotify(struct mansession *s, const struct message *m)
11505 {
11506    const char *channame = astman_get_header(m, "Channel");
11507    struct ast_variable *vars = astman_get_variables(m);
11508    struct sip_pvt *p;
11509 
11510    if (ast_strlen_zero(channame)) {
11511       astman_send_error(s, m, "SIPNotify requires a channel name");
11512       return 0;
11513    }
11514 
11515    if (!strncasecmp(channame, "sip/", 4)) {
11516       channame += 4;
11517    }
11518 
11519    if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
11520       astman_send_error(s, m, "Unable to build sip pvt data for notify (memory/socket error)");
11521       return 0;
11522    }
11523 
11524    if (create_addr(p, channame, NULL, 0)) {
11525       /* Maybe they're not registered, etc. */
11526       dialog_unlink_all(p, TRUE, TRUE);
11527       dialog_unref(p, "unref dialog inside for loop" );
11528       /* sip_destroy(p); */
11529       astman_send_error(s, m, "Could not create address");
11530       return 0;
11531    }
11532 
11533    /* Notify is outgoing call */
11534    ast_set_flag(&p->flags[0], SIP_OUTGOING);
11535 
11536    /* Recalculate our side, and recalculate Call ID */
11537    ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
11538    build_via(p);
11539    ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
11540    build_callid_pvt(p);
11541    ao2_t_link(dialogs, p, "Linking in new name");
11542    dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
11543    sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
11544 
11545    if (!transmit_notify_custom(p, vars)) {
11546       astman_send_ack(s, m, "Notify Sent");
11547    } else {
11548       astman_send_error(s, m, "Unable to send notify");
11549    }
11550    ast_variables_destroy(vars);
11551    return 0;
11552 }
11553 
11554 static char mandescr_sipnotify[] =
11555 "Description: Sends a SIP Notify event\n"
11556 "All parameters for this event must be specified in the body of this request\n"
11557 "via multiple Variable: name=value sequences.\n"
11558 "Variables: \n"
11559 "  *Channel: <peername>       Peer to receive the notify. Required.\n"
11560 "  *Variable: <name>=<value>  At least one variable pair must be specified.\n"
11561 "  ActionID: <id>             Action ID for this transaction. Will be returned.\n";
11562 
11563 static const struct _map_x_s regstatestrings[] = {
11564    { REG_STATE_FAILED,     "Failed" },
11565    { REG_STATE_UNREGISTERED, "Unregistered"},
11566    { REG_STATE_REGSENT, "Request Sent"},
11567    { REG_STATE_AUTHSENT, "Auth. Sent"},
11568    { REG_STATE_REGISTERED, "Registered"},
11569    { REG_STATE_REJECTED, "Rejected"},
11570    { REG_STATE_TIMEOUT, "Timeout"},
11571    { REG_STATE_NOAUTH, "No Authentication"},
11572    { -1, NULL } /* terminator */
11573 };
11574 
11575 /*! \brief Convert registration state status to string */
11576 static const char *regstate2str(enum sipregistrystate regstate)
11577 {
11578    return map_x_s(regstatestrings, regstate, "Unknown");
11579 }
11580 
11581 /*! \brief Update registration with SIP Proxy.
11582  * Called from the scheduler when the previous registration expires,
11583  * so we don't have to cancel the pending event.
11584  * We assume the reference so the sip_registry is valid, since it
11585  * is stored in the scheduled event anyways.
11586  */
11587 static int sip_reregister(const void *data) 
11588 {
11589    /* if we are here, we know that we need to reregister. */
11590    struct sip_registry *r= (struct sip_registry *) data;
11591 
11592    /* if we couldn't get a reference to the registry object, punt */
11593    if (!r)
11594       return 0;
11595 
11596    if (r->call && r->call->do_history)
11597       append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
11598    /* Since registry's are only added/removed by the the monitor thread, this
11599       may be overkill to reference/dereference at all here */
11600    if (sipdebug)
11601       ast_log(LOG_NOTICE, "   -- Re-registration for  %s@%s\n", r->username, r->hostname);
11602 
11603    r->expire = -1;
11604    r->expiry = r->configured_expiry;
11605    __sip_do_register(r);
11606    registry_unref(r, "unref the re-register scheduled event");
11607    return 0;
11608 }
11609 
11610 /*! \brief Register with SIP proxy */
11611 static int __sip_do_register(struct sip_registry *r)
11612 {
11613    int res;
11614 
11615    res = transmit_register(r, SIP_REGISTER, NULL, NULL);
11616    return res;
11617 }
11618 
11619 /*! \brief Registration timeout, register again
11620  * Registered as a timeout handler during transmit_register(),
11621  * to retransmit the packet if a reply does not come back.
11622  * This is called by the scheduler so the event is not pending anymore when
11623  * we are called.
11624  */
11625 static int sip_reg_timeout(const void *data)
11626 {
11627 
11628    /* if we are here, our registration timed out, so we'll just do it over */
11629    struct sip_registry *r = (struct sip_registry *)data; /* the ref count should have been bumped when the sched item was added */
11630    struct sip_pvt *p;
11631    int res;
11632 
11633    /* if we couldn't get a reference to the registry object, punt */
11634    if (!r)
11635       return 0;
11636 
11637    if (r->dnsmgr) {
11638       /* If the registration has timed out, maybe the IP changed.  Force a refresh. */
11639       ast_dnsmgr_refresh(r->dnsmgr);
11640    }
11641 
11642    ast_log(LOG_NOTICE, "   -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts); 
11643    /* If the initial tranmission failed, we may not have an existing dialog,
11644     * so it is possible that r->call == NULL.
11645     * Otherwise destroy it, as we have a timeout so we don't want it.
11646     */
11647    if (r->call) {
11648       /* Unlink us, destroy old call.  Locking is not relevant here because all this happens
11649          in the single SIP manager thread. */
11650       p = r->call;
11651       sip_pvt_lock(p);
11652       pvt_set_needdestroy(p, "registration timeout");
11653       /* Pretend to ACK anything just in case */
11654       __sip_pretend_ack(p);
11655       sip_pvt_unlock(p);
11656 
11657       /* decouple the two objects */
11658       /* p->registry == r, so r has 2 refs, and the unref won't take the object away */
11659       if (p->registry)
11660          p->registry = registry_unref(p->registry, "p->registry unreffed");
11661       r->call = dialog_unref(r->call, "unrefing r->call");
11662    }
11663    /* If we have a limit, stop registration and give up */
11664    r->timeout = -1;
11665    if (global_regattempts_max && r->regattempts > global_regattempts_max) {
11666       /* Ok, enough is enough. Don't try any more */
11667       /* We could add an external notification here... 
11668          steal it from app_voicemail :-) */
11669       ast_log(LOG_NOTICE, "   -- Giving up forever trying to register '%s@%s'\n", r->username, r->hostname);
11670       r->regstate = REG_STATE_FAILED;
11671    } else {
11672       r->regstate = REG_STATE_UNREGISTERED;
11673       res=transmit_register(r, SIP_REGISTER, NULL, NULL);
11674    }
11675    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));
11676    registry_unref(r, "unreffing registry_unref r");
11677    return 0;
11678 }
11679 
11680 /*! \brief Transmit register to SIP proxy or UA
11681  * auth = NULL on the initial registration (from sip_reregister())
11682  */
11683 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
11684 {
11685    struct sip_request req;
11686    char from[256];
11687    char to[256];
11688    char tmp[80];
11689    char addr[80];
11690    struct sip_pvt *p;
11691    struct sip_peer *peer = NULL;
11692    int res;
11693    char *fromdomain;
11694    char *domainport = NULL;
11695 
11696    /* exit if we are already in process with this registrar ?*/
11697    if (r == NULL || ((auth == NULL) && (r->regstate == REG_STATE_REGSENT || r->regstate == REG_STATE_AUTHSENT))) {
11698       if (r) {
11699          ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
11700       }
11701       return 0;
11702    }
11703 
11704    if (r->dnsmgr == NULL) {
11705       char transport[MAXHOSTNAMELEN];
11706       peer = find_peer(r->hostname, NULL, TRUE, FINDPEERS, FALSE, 0);
11707       snprintf(transport, sizeof(transport), "_%s._%s",get_srv_service(r->transport), get_srv_protocol(r->transport)); /* have to use static get_transport function */
11708       ast_dnsmgr_lookup(peer ? peer->tohost : r->hostname, &r->us, &r->dnsmgr, sip_cfg.srvlookup ? transport : NULL);
11709       if (peer) {
11710          peer = unref_peer(peer, "removing peer ref for dnsmgr_lookup");
11711       }
11712    }
11713 
11714    if (r->call) { /* We have a registration */
11715       if (!auth) {
11716          ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
11717          return 0;
11718       } else {
11719          p = dialog_ref(r->call, "getting a copy of the r->call dialog in transmit_register");
11720          make_our_tag(p->tag, sizeof(p->tag));  /* create a new local tag for every register attempt */
11721          ast_string_field_set(p, theirtag, NULL);  /* forget their old tag, so we don't match tags when getting response */
11722       }
11723    } else {
11724       /* Build callid for registration if we haven't registered before */
11725       if (!r->callid_valid) {
11726          build_callid_registry(r, internip.sin_addr, default_fromdomain);
11727          r->callid_valid = TRUE;
11728       }
11729       /* Allocate SIP dialog for registration */
11730       if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER, NULL))) {
11731          ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
11732          return 0;
11733       }
11734       
11735       if (p->do_history)
11736          append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
11737 
11738       /* Use port number specified if no SRV record was found */
11739       if (!r->us.sin_port && r->portno)
11740          r->us.sin_port = htons(r->portno);
11741 
11742       /* Find address to hostname */
11743       if (create_addr(p, S_OR(r->peername, r->hostname), &r->us, 0)) {
11744          /* we have what we hope is a temporary network error,
11745           * probably DNS.  We need to reschedule a registration try */
11746          dialog_unlink_all(p, TRUE, TRUE);
11747          p = dialog_unref(p, "unref dialog after unlink_all");
11748          if (r->timeout > -1) {
11749             AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
11750                               registry_unref(_data, "del for REPLACE of registry ptr"), 
11751                               registry_unref(r, "object ptr dec when SCHED_REPLACE add failed"),
11752                               registry_addref(r,"add for REPLACE registry ptr"));
11753             ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
11754          } else {
11755             r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, registry_addref(r, "add for REPLACE registry ptr"));
11756             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);
11757          }
11758          r->regattempts++;
11759          return 0;
11760       }
11761 
11762       /* Copy back Call-ID in case create_addr changed it */
11763       ast_string_field_set(r, callid, p->callid);
11764       if (!r->dnsmgr && r->portno) {
11765          p->sa.sin_port = htons(r->portno);
11766          p->recv.sin_port = htons(r->portno);
11767       } else { /* Set registry port to the port set from the peer definition/srv or default */
11768          r->portno = ntohs(p->sa.sin_port);
11769       }
11770       ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Registration is outgoing call */
11771       r->call = dialog_ref(p, "copying dialog into registry r->call");     /* Save pointer to SIP dialog */
11772       p->registry = registry_addref(r, "transmit_register: addref to p->registry in transmit_register"); /* Add pointer to registry in packet */
11773       if (!ast_strlen_zero(r->secret)) {  /* Secret (password) */
11774          ast_string_field_set(p, peersecret, r->secret);
11775       }
11776       if (!ast_strlen_zero(r->md5secret))
11777          ast_string_field_set(p, peermd5secret, r->md5secret);
11778       /* User name in this realm  
11779       - if authuser is set, use that, otherwise use username */
11780       if (!ast_strlen_zero(r->authuser)) {   
11781          ast_string_field_set(p, peername, r->authuser);
11782          ast_string_field_set(p, authname, r->authuser);
11783       } else if (!ast_strlen_zero(r->username)) {
11784          ast_string_field_set(p, peername, r->username);
11785          ast_string_field_set(p, authname, r->username);
11786          ast_string_field_set(p, fromuser, r->username);
11787       }
11788       if (!ast_strlen_zero(r->username))
11789          ast_string_field_set(p, username, r->username);
11790       /* Save extension in packet */
11791       if (!ast_strlen_zero(r->callback))
11792          ast_string_field_set(p, exten, r->callback);
11793 
11794       /* Set transport and port so the correct contact is built */
11795       set_socket_transport(&p->socket, r->transport);
11796       if (r->transport == SIP_TRANSPORT_TLS || r->transport == SIP_TRANSPORT_TCP) {
11797          p->socket.port = sip_tcp_desc.local_address.sin_port;
11798       }
11799 
11800       /*
11801         check which address we should use in our contact header 
11802         based on whether the remote host is on the external or
11803         internal network so we can register through nat
11804        */
11805       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
11806       build_contact(p);
11807    }
11808 
11809    /* set up a timeout */
11810    if (auth == NULL)  {
11811       if (r->timeout > -1)
11812          ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
11813       AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
11814                         registry_unref(_data,"reg ptr unrefed from del in SCHED_REPLACE"),
11815                         registry_unref(r,"reg ptr unrefed from add failure in SCHED_REPLACE"),
11816                         registry_addref(r,"reg ptr reffed from add in SCHED_REPLACE"));
11817       ast_debug(1, "Scheduled a registration timeout for %s id  #%d \n", r->hostname, r->timeout);
11818    }
11819 
11820    if ((fromdomain = strchr(r->username, '@'))) {
11821       /* the domain name is just behind '@' */
11822       fromdomain++ ;
11823       /* We have a domain in the username for registration */
11824       snprintf(from, sizeof(from), "<sip:%s>;tag=%s", r->username, p->tag);
11825       if (!ast_strlen_zero(p->theirtag))
11826          snprintf(to, sizeof(to), "<sip:%s>;tag=%s", r->username, p->theirtag);
11827       else
11828          snprintf(to, sizeof(to), "<sip:%s>", r->username);
11829 
11830       /* If the registration username contains '@', then the domain should be used as
11831          the equivalent of "fromdomain" for the registration */
11832       if (ast_strlen_zero(p->fromdomain)) {
11833          ast_string_field_set(p, fromdomain, fromdomain);
11834       }
11835    } else {
11836       snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->tag);
11837       if (!ast_strlen_zero(p->theirtag))
11838          snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->theirtag);
11839       else
11840          snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, p->tohost);
11841    }
11842    
11843    /* Fromdomain is what we are registering to, regardless of actual
11844       host name from SRV */
11845    if (!ast_strlen_zero(p->fromdomain)) {
11846       domainport = strrchr(p->fromdomain, ':');
11847       if (domainport) {
11848          *domainport++ = '\0'; /* trim off domainport from p->fromdomain */
11849          if (ast_strlen_zero(domainport))
11850             domainport = NULL;
11851       }     
11852       if (domainport) {       
11853          if (atoi(domainport) != STANDARD_SIP_PORT)
11854             snprintf(addr, sizeof(addr), "sip:%s:%s", p->fromdomain, domainport);
11855          else
11856             snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
11857       } else {
11858          if (r->portno && r->portno != STANDARD_SIP_PORT)
11859             snprintf(addr, sizeof(addr), "sip:%s:%d", p->fromdomain, r->portno);
11860          else
11861             snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
11862       }
11863    } else {
11864       if (r->portno && r->portno != STANDARD_SIP_PORT)
11865          snprintf(addr, sizeof(addr), "sip:%s:%d", r->hostname, r->portno);
11866       else
11867          snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
11868    }
11869    ast_string_field_set(p, uri, addr);
11870 
11871    p->branch ^= ast_random();
11872 
11873    init_req(&req, sipmethod, addr);
11874 
11875    /* Add to CSEQ */
11876    snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
11877    p->ocseq = r->ocseq;
11878 
11879    build_via(p);
11880    add_header(&req, "Via", p->via);
11881    add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
11882    add_header(&req, "From", from);
11883    add_header(&req, "To", to);
11884    add_header(&req, "Call-ID", p->callid);
11885    add_header(&req, "CSeq", tmp);
11886    if (!ast_strlen_zero(global_useragent))
11887       add_header(&req, "User-Agent", global_useragent);
11888 
11889    
11890    if (auth)   /* Add auth header */
11891       add_header(&req, authheader, auth);
11892    else if (!ast_strlen_zero(r->nonce)) {
11893       char digest[1024];
11894 
11895       /* We have auth data to reuse, build a digest header.
11896        * Note, this is not always useful because some parties do not
11897        * like nonces to be reused (for good reasons!) so they will
11898        * challenge us anyways.
11899        */
11900       if (sipdebug)
11901          ast_debug(1, "   >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
11902       ast_string_field_set(p, realm, r->realm);
11903       ast_string_field_set(p, nonce, r->nonce);
11904       ast_string_field_set(p, domain, r->domain);
11905       ast_string_field_set(p, opaque, r->opaque);
11906       ast_string_field_set(p, qop, r->qop);
11907       p->noncecount = ++r->noncecount;
11908 
11909       memset(digest, 0, sizeof(digest));
11910       if(!build_reply_digest(p, sipmethod, digest, sizeof(digest)))
11911          add_header(&req, "Authorization", digest);
11912       else
11913          ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
11914    
11915    }
11916 
11917    snprintf(tmp, sizeof(tmp), "%d", r->expiry);
11918    add_header(&req, "Expires", tmp);
11919    add_header(&req, "Contact", p->our_contact);
11920 
11921    initialize_initreq(p, &req);
11922    if (sip_debug_test_pvt(p)) {
11923       ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
11924    }
11925    r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
11926    r->regattempts++; /* Another attempt */
11927    ast_debug(4, "REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
11928    res = send_request(p, &req, XMIT_CRITICAL, p->ocseq);
11929    dialog_unref(p, "p is finished here at the end of transmit_register");
11930    return res;
11931 }
11932 
11933 /*! \brief Transmit text with SIP MESSAGE method */
11934 static int transmit_message_with_text(struct sip_pvt *p, const char *text)
11935 {
11936    struct sip_request req;
11937    
11938    reqprep(&req, p, SIP_MESSAGE, 0, 1);
11939    add_text(&req, text);
11940    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11941 }
11942 
11943 /*! \brief Allocate SIP refer structure */
11944 static int sip_refer_allocate(struct sip_pvt *p)
11945 {
11946    p->refer = ast_calloc(1, sizeof(struct sip_refer)); 
11947    return p->refer ? 1 : 0;
11948 }
11949 
11950 /*! \brief Transmit SIP REFER message (initiated by the transfer() dialplan application
11951    \note this is currently broken as we have no way of telling the dialplan
11952    engine whether a transfer succeeds or fails.
11953    \todo Fix the transfer() dialplan function so that a transfer may fail
11954 */
11955 static int transmit_refer(struct sip_pvt *p, const char *dest)
11956 {
11957    struct sip_request req = { 
11958       .headers = 0,  
11959    };
11960    char from[256];
11961    const char *of;
11962    char *c;
11963    char referto[256];
11964    char *ttag, *ftag;
11965    char *theirtag = ast_strdupa(p->theirtag);
11966    int   use_tls=FALSE;
11967 
11968    if (sipdebug)
11969       ast_debug(1, "SIP transfer of %s to %s\n", p->callid, dest);
11970 
11971    /* Are we transfering an inbound or outbound call ? */
11972    if (ast_test_flag(&p->flags[0], SIP_OUTGOING))  {
11973       of = get_header(&p->initreq, "To");
11974       ttag = theirtag;
11975       ftag = p->tag;
11976    } else {
11977       of = get_header(&p->initreq, "From");
11978       ftag = theirtag;
11979       ttag = p->tag;
11980    }
11981 
11982    ast_copy_string(from, of, sizeof(from));
11983    of = get_in_brackets(from);
11984    ast_string_field_set(p, from, of);
11985    if (!strncasecmp(of, "sip:", 4)) {
11986       of += 4;
11987    }else if (!strncasecmp(of, "sips:", 5)) {
11988       of += 5;
11989       use_tls = TRUE;
11990    } else {
11991       ast_log(LOG_NOTICE, "From address missing 'sip(s):', assuming sip:\n");
11992    }
11993    /* Get just the username part */
11994    if ((c = strchr(dest, '@')))
11995       c = NULL;
11996    else if ((c = strchr(of, '@')))
11997       *c++ = '\0';
11998    if (c) 
11999       snprintf(referto, sizeof(referto), "<sip%s:%s@%s>", use_tls ? "s" : "", dest, c);
12000    else
12001       snprintf(referto, sizeof(referto), "<sip%s:%s>", use_tls ? "s" : "", dest);
12002 
12003    /* save in case we get 407 challenge */
12004    sip_refer_allocate(p);
12005    ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
12006    ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
12007    p->refer->status = REFER_SENT;   /* Set refer status */
12008 
12009    reqprep(&req, p, SIP_REFER, 0, 1);
12010 
12011    add_header(&req, "Refer-To", referto);
12012    add_header(&req, "Allow", ALLOWED_METHODS);
12013    add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
12014    if (!ast_strlen_zero(p->our_contact))
12015       add_header(&req, "Referred-By", p->our_contact);
12016 
12017    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12018 
12019    /* We should propably wait for a NOTIFY here until we ack the transfer */
12020    /* Maybe fork a new thread and wait for a STATUS of REFER_200OK on the refer status before returning to app_transfer */
12021 
12022    /*! \todo In theory, we should hang around and wait for a reply, before
12023    returning to the dial plan here. Don't know really how that would
12024    affect the transfer() app or the pbx, but, well, to make this
12025    useful we should have a STATUS code on transfer().
12026    */
12027 }
12028 
12029 
12030 /*! \brief Send SIP INFO dtmf message, see Cisco documentation on cisco.com */
12031 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
12032 {
12033    struct sip_request req;
12034    
12035    reqprep(&req, p, SIP_INFO, 0, 1);
12036    add_digit(&req, digit, duration, (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO));
12037    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12038 }
12039 
12040 /*! \brief Send SIP INFO with video update request */
12041 static int transmit_info_with_vidupdate(struct sip_pvt *p)
12042 {
12043    struct sip_request req;
12044    
12045    reqprep(&req, p, SIP_INFO, 0, 1);
12046    add_vidupdate(&req);
12047    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12048 }
12049 
12050 /*! \brief Transmit generic SIP request 
12051    returns XMIT_ERROR if transmit failed with a critical error (don't retry)
12052 */
12053 static int transmit_request(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
12054 {
12055    struct sip_request resp;
12056    
12057    if (sipmethod == SIP_ACK)
12058       p->invitestate = INV_CONFIRMED;
12059 
12060    reqprep(&resp, p, sipmethod, seqno, newbranch);
12061    if (sipmethod == SIP_CANCEL && p->answered_elsewhere) 
12062       add_header(&resp, "Reason", "SIP;cause=200;text=\"Call completed elsewhere\"");
12063 
12064    return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
12065 }
12066 
12067 /*! \brief return the request and response heade for a 401 or 407 code */
12068 static void auth_headers(enum sip_auth_type code, char **header, char **respheader)
12069 {
12070    if (code == WWW_AUTH) {       /* 401 */
12071       *header = "WWW-Authenticate";
12072       *respheader = "Authorization";
12073    } else if (code == PROXY_AUTH) { /* 407 */
12074       *header = "Proxy-Authenticate";
12075       *respheader = "Proxy-Authorization";
12076    } else {
12077       ast_verbose("-- wrong response code %d\n", code);
12078       *header = *respheader = "Invalid";
12079    }
12080 }
12081 
12082 /*! \brief Transmit SIP request, auth added */
12083 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
12084 {
12085    struct sip_request resp;
12086    
12087    reqprep(&resp, p, sipmethod, seqno, newbranch);
12088    if (!ast_strlen_zero(p->realm)) {
12089       char digest[1024];
12090 
12091       memset(digest, 0, sizeof(digest));
12092       if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
12093          char *dummy, *response;
12094          enum sip_auth_type code = p->options ? p->options->auth_type : PROXY_AUTH; /* XXX force 407 if unknown */
12095          auth_headers(code, &dummy, &response);
12096          add_header(&resp, response, digest);
12097       } else
12098          ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
12099    }
12100    /* If we are hanging up and know a cause for that, send it in clear text to make
12101       debugging easier. */
12102    if (sipmethod == SIP_BYE)  {
12103       char buf[10];
12104 
12105       add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->hangupcause));
12106       snprintf(buf, sizeof(buf), "%d", p->hangupcause);
12107       add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
12108    }
12109 
12110    return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);   
12111 }
12112 
12113 /*! \brief Remove registration data from realtime database or AST/DB when registration expires */
12114 static void destroy_association(struct sip_peer *peer)
12115 {
12116    int realtimeregs = ast_check_realtime("sipregs");
12117    char *tablename = (realtimeregs) ? "sipregs" : "sippeers";
12118 
12119    if (!sip_cfg.ignore_regexpire) {
12120       if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
12121          ast_update_realtime(tablename, "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", peer->deprecated_username ? "username" : "defaultuser", "", "regserver", "", "useragent", "", "lastms", "", SENTINEL);
12122       } else {
12123          ast_db_del("SIP/Registry", peer->name);
12124       }
12125    }
12126 }
12127 
12128 static void set_socket_transport(struct sip_socket *socket, int transport)
12129 {
12130    /* if the transport type changes, clear all socket data */
12131    if (socket->type != transport) {
12132       socket->fd = -1;
12133       socket->type = transport;
12134       if (socket->tcptls_session) {
12135          ao2_ref(socket->tcptls_session, -1);
12136          socket->tcptls_session = NULL;
12137       }
12138    }
12139 }
12140 
12141 /*! \brief Expire registration of SIP peer */
12142 static int expire_register(const void *data)
12143 {
12144    struct sip_peer *peer = (struct sip_peer *)data;
12145 
12146    if (!peer)     /* Hmmm. We have no peer. Weird. */
12147       return 0;
12148 
12149    peer->expire = -1;
12150    peer->portinuri = 0;
12151 
12152    destroy_association(peer); /* remove registration data from storage */
12153    set_socket_transport(&peer->socket, peer->default_outbound_transport);
12154 
12155    if (peer->socket.tcptls_session) {
12156       ao2_ref(peer->socket.tcptls_session, -1);
12157       peer->socket.tcptls_session = NULL;
12158    }
12159 
12160    manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
12161    register_peer_exten(peer, FALSE);   /* Remove regexten */
12162    ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
12163 
12164    /* Do we need to release this peer from memory? 
12165       Only for realtime peers and autocreated peers
12166    */
12167    if (peer->is_realtime)
12168       ast_debug(3, "-REALTIME- peer expired registration. Name: %s. Realtime peer objects now %d\n", peer->name, rpeerobjs);
12169 
12170    if (peer->selfdestruct ||
12171        ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
12172       unlink_peer_from_tables(peer);
12173    }
12174 
12175    /* Only clear the addr after we check for destruction.  The addr must remain
12176     * in order to unlink from the peers_by_ip container correctly */
12177    memset(&peer->addr, 0, sizeof(peer->addr));
12178 
12179    unref_peer(peer, "removing peer ref for expire_register");
12180 
12181    return 0;
12182 }
12183 
12184 /*! \brief Poke peer (send qualify to check if peer is alive and well) */
12185 static int sip_poke_peer_s(const void *data)
12186 {
12187    struct sip_peer *peer = (struct sip_peer *)data;
12188 
12189    peer->pokeexpire = -1;
12190 
12191    sip_poke_peer(peer, 0);
12192 
12193    unref_peer(peer, "removing poke peer ref");
12194 
12195    return 0;
12196 }
12197 
12198 /*! \brief Get registration details from Asterisk DB */
12199 static void reg_source_db(struct sip_peer *peer)
12200 {
12201    char data[256];
12202    struct in_addr in;
12203    int expire;
12204    int port;
12205    char *scan, *addr, *port_str, *expiry_str, *username, *contact;
12206 
12207    if (peer->rt_fromcontact) 
12208       return;
12209    if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data)))
12210       return;
12211 
12212    scan = data;
12213    addr = strsep(&scan, ":");
12214    port_str = strsep(&scan, ":");
12215    expiry_str = strsep(&scan, ":");
12216    username = strsep(&scan, ":");
12217    contact = scan;   /* Contact include sip: and has to be the last part of the database entry as long as we use : as a separator */
12218 
12219    if (!inet_aton(addr, &in))
12220       return;
12221 
12222    if (port_str)
12223       port = atoi(port_str);
12224    else
12225       return;
12226 
12227    if (expiry_str)
12228       expire = atoi(expiry_str);
12229    else
12230       return;
12231 
12232    if (username)
12233       ast_string_field_set(peer, username, username);
12234    if (contact)
12235       ast_string_field_set(peer, fullcontact, contact);
12236 
12237    ast_debug(2, "SIP Seeding peer from astdb: '%s' at %s@%s:%d for %d\n",
12238        peer->name, peer->username, ast_inet_ntoa(in), port, expire);
12239 
12240    memset(&peer->addr, 0, sizeof(peer->addr));
12241    peer->addr.sin_family = AF_INET;
12242    peer->addr.sin_addr = in;
12243    peer->addr.sin_port = htons(port);
12244    if (sipsock < 0) {
12245       /* SIP isn't up yet, so schedule a poke only, pretty soon */
12246       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ast_random() % 5000 + 1, sip_poke_peer_s, peer,
12247             unref_peer(_data, "removing poke peer ref"),
12248             unref_peer(peer, "removing poke peer ref"),
12249             ref_peer(peer, "adding poke peer ref"));
12250    } else {
12251       sip_poke_peer(peer, 0);
12252    }
12253    AST_SCHED_REPLACE_UNREF(peer->expire, sched, (expire + 10) * 1000, expire_register, peer,
12254          unref_peer(_data, "remove registration ref"),
12255          unref_peer(peer, "remove registration ref"),
12256          ref_peer(peer, "add registration ref"));
12257    register_peer_exten(peer, TRUE);
12258 }
12259 
12260 /*! \brief Save contact header for 200 OK on INVITE */
12261 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
12262 {
12263    char contact[SIPBUFSIZE]; 
12264    char *c;
12265 
12266    /* Look for brackets */
12267    ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
12268    c = get_in_brackets(contact);
12269 
12270    /* Save full contact to call pvt for later bye or re-invite */
12271    ast_string_field_set(pvt, fullcontact, c);
12272 
12273    /* Save URI for later ACKs, BYE or RE-invites */
12274    ast_string_field_set(pvt, okcontacturi, c);
12275 
12276    /* We should return false for URI:s we can't handle,
12277       like tel:, mailto:,ldap: etc */
12278    return TRUE;      
12279 }
12280 
12281 static int __set_address_from_contact(const char *fullcontact, struct sockaddr_in *sin, int tcp)
12282 {
12283    struct hostent *hp;
12284    struct ast_hostent ahp;
12285    int port = STANDARD_SIP_PORT;
12286    char *host, *pt, *transport;
12287    char contact_buf[256];
12288    char *contact;
12289 
12290    /* Work on a copy */
12291    ast_copy_string(contact_buf, fullcontact, sizeof(contact_buf));
12292    contact = contact_buf;
12293 
12294    /* 
12295     * We have only the part in <brackets> here so we just need to parse a SIP URI.
12296     *
12297     * Note: The outbound proxy could be using UDP between the proxy and Asterisk.
12298     * We still need to be able to send to the remote agent through the proxy.
12299     */
12300 
12301    if (parse_uri(contact, "sip:,sips:", &contact, NULL, &host, &pt, NULL, &transport)) {
12302       ast_log(LOG_WARNING, "Invalid contact uri %s (missing sip: or sips:), attempting to use anyway\n", fullcontact);
12303    }
12304 
12305    /* set port */
12306    if (((get_transport_str2enum(transport) == SIP_TRANSPORT_TLS)) || !(strncasecmp(fullcontact, "sips", 4))) {
12307       port = port_str2int(pt, STANDARD_TLS_PORT);
12308    } else {
12309       port = port_str2int(pt, STANDARD_SIP_PORT);
12310    }
12311 
12312 
12313    /* XXX This could block for a long time XXX */
12314    /* We should only do this if it's a name, not an IP */
12315    /* \todo - if there's no PORT number in contact - we are required to check NAPTR/SRV records
12316       to find transport, port address and hostname. If there's a port number, we have to
12317       assume that the domain part is a host name and only look for an A/AAAA record in DNS.
12318    */
12319    hp = ast_gethostbyname(host, &ahp);
12320    if (!hp)  {
12321       ast_log(LOG_WARNING, "Invalid host name in Contact: (can't resolve in DNS) : '%s'\n", host);
12322       return -1;
12323    }
12324    sin->sin_family = AF_INET;
12325    memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
12326    sin->sin_port = htons(port);
12327 
12328    return 0;
12329 }
12330 
12331 /*! \brief Change the other partys IP address based on given contact */
12332 static int set_address_from_contact(struct sip_pvt *pvt)
12333 {
12334    if (ast_test_flag(&pvt->flags[0], SIP_NAT_ROUTE)) {
12335       /* NAT: Don't trust the contact field.  Just use what they came to us
12336          with. */
12337       /*! \todo We need to save the TRANSPORT here too */
12338       pvt->sa = pvt->recv;
12339       return 0;
12340    }
12341 
12342    return __set_address_from_contact(pvt->fullcontact, &pvt->sa, pvt->socket.type == SIP_TRANSPORT_TLS ? 1 : 0);
12343 }
12344 
12345 /*! \brief Parse contact header and save registration (peer registration) */
12346 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
12347 {
12348    char contact[SIPBUFSIZE];
12349    char data[SIPBUFSIZE];
12350    const char *expires = get_header(req, "Expires");
12351    int expire = atoi(expires);
12352    char *curi, *host, *pt, *transport;
12353    int port;
12354    int transport_type;
12355    const char *useragent;
12356    struct hostent *hp;
12357    struct ast_hostent ahp;
12358    struct sockaddr_in oldsin, testsin;
12359 
12360 
12361    ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
12362 
12363    if (ast_strlen_zero(expires)) {  /* No expires header, try look in Contact: */
12364       char *s = strcasestr(contact, ";expires=");
12365       if (s) {
12366          expires = strsep(&s, ";"); /* trim ; and beyond */
12367          if (sscanf(expires + 9, "%30d", &expire) != 1)
12368             expire = default_expiry;
12369       } else {
12370          /* Nothing has been specified */
12371          expire = default_expiry;
12372       }
12373    }
12374 
12375    copy_socket_data(&pvt->socket, &req->socket);
12376 
12377    /* Look for brackets */
12378    curi = contact;
12379    if (strchr(contact, '<') == NULL)   /* No <, check for ; and strip it */
12380       strsep(&curi, ";");  /* This is Header options, not URI options */
12381    curi = get_in_brackets(contact);
12382 
12383    /* if they did not specify Contact: or Expires:, they are querying
12384       what we currently have stored as their contact address, so return
12385       it
12386    */
12387    if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
12388       /* If we have an active registration, tell them when the registration is going to expire */
12389       if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact))
12390          pvt->expiry = ast_sched_when(sched, peer->expire);
12391       return PARSE_REGISTER_QUERY;
12392    } else if (!strcasecmp(curi, "*") || !expire) { /* Unregister this peer */
12393       /* This means remove all registrations and return OK */
12394       memset(&peer->addr, 0, sizeof(peer->addr));
12395       set_socket_transport(&peer->socket, peer->default_outbound_transport);
12396 
12397       AST_SCHED_DEL_UNREF(sched, peer->expire,
12398             unref_peer(peer, "remove register expire ref"));
12399 
12400       destroy_association(peer);
12401 
12402       register_peer_exten(peer, FALSE);   /* Remove extension from regexten= setting in sip.conf */
12403       ast_string_field_set(peer, fullcontact, "");
12404       ast_string_field_set(peer, useragent, "");
12405       peer->sipoptions = 0;
12406       peer->lastms = 0;
12407       peer->portinuri = 0;
12408       pvt->expiry = 0;
12409 
12410       ast_verb(3, "Unregistered SIP '%s'\n", peer->name);
12411 
12412       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\n", peer->name);
12413       return PARSE_REGISTER_UPDATE;
12414    }
12415 
12416    /* Store whatever we got as a contact from the client */
12417    ast_string_field_set(peer, fullcontact, curi);
12418 
12419    /* For the 200 OK, we should use the received contact */
12420    ast_string_field_build(pvt, our_contact, "<%s>", curi);
12421 
12422    /* Make sure it's a SIP URL */
12423    if (parse_uri(curi, "sip:,sips:", &curi, NULL, &host, &pt, NULL, &transport)) {
12424       ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:) trying to use anyway\n");
12425    }
12426 
12427    /* If we have a port number in the given URI, make sure we do remember to not check for NAPTR/SRV records. 
12428       The domain part is actually a host. */
12429    peer->portinuri = !ast_strlen_zero(pt) ? TRUE : FALSE;
12430 
12431    /* handle the transport type specified in Contact header. */
12432    if ((transport_type = get_transport_str2enum(transport))) {
12433       /* if the port is not specified but the transport is, make sure to set the
12434        * default port to match the specified transport.  This may or may not be the
12435        * same transport used by the pvt struct for the Register dialog. */
12436       
12437       port = port_str2int(pt, (transport_type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
12438    } else {
12439       port = port_str2int(pt, STANDARD_SIP_PORT);
12440       transport_type = pvt->socket.type;
12441    }
12442 
12443    /* if the peer's socket type is different than the Registration
12444     * transport type, change it.  If it got this far, it is a
12445     * supported type, but check just in case */
12446    if ((peer->socket.type != transport_type) && (peer->transports & transport_type)) {
12447       set_socket_transport(&peer->socket, transport_type);
12448    }
12449 
12450    oldsin = peer->addr;
12451 
12452    /* If we were already linked into the peers_by_ip container unlink ourselves so nobody can find us */
12453    if (peer->addr.sin_addr.s_addr) {
12454       ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
12455    }
12456 
12457    if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE)) {
12458       /* use the data provided in the Contact header for call routing */
12459       ast_debug(1, "Store REGISTER's Contact header for call routing.\n");
12460       /* XXX This could block for a long time XXX */
12461       /*! \todo Check NAPTR/SRV if we have not got a port in the URI */
12462       hp = ast_gethostbyname(host, &ahp);
12463       if (!hp)  {
12464          ast_log(LOG_WARNING, "Invalid host '%s'\n", host);
12465          ast_string_field_set(peer, fullcontact, "");
12466          ast_string_field_set(pvt, our_contact, "");
12467          return PARSE_REGISTER_FAILED;
12468       }
12469       peer->addr.sin_family = AF_INET;
12470       memcpy(&peer->addr.sin_addr, hp->h_addr, sizeof(peer->addr.sin_addr));
12471       peer->addr.sin_port = htons(port);
12472    } else {
12473       /* Don't trust the contact field.  Just use what they came to us
12474          with */
12475       ast_debug(1, "Store REGISTER's src-IP:port for call routing.\n");
12476       peer->addr = pvt->recv;
12477    }
12478 
12479    /* Check that they're allowed to register at this IP */
12480    memcpy(&testsin.sin_addr, &peer->addr.sin_addr, sizeof(testsin.sin_addr));
12481    if (ast_apply_ha(global_contact_ha, &testsin) != AST_SENSE_ALLOW ||
12482          ast_apply_ha(peer->contactha, &testsin) != AST_SENSE_ALLOW) {
12483       ast_log(LOG_WARNING, "Host '%s' disallowed by contact ACL (violating IP %s)\n", host, ast_inet_ntoa(testsin.sin_addr));
12484       ast_string_field_set(peer, fullcontact, "");
12485       ast_string_field_set(pvt, our_contact, "");
12486       return PARSE_REGISTER_DENIED;
12487    }
12488 
12489    /* if the Contact header information copied into peer->addr matches the
12490     * received address, and the transport types are the same, then copy socket
12491     * data into the peer struct */
12492    if ((peer->socket.type == pvt->socket.type) &&
12493       (peer->addr.sin_addr.s_addr == pvt->recv.sin_addr.s_addr) &&
12494       (peer->addr.sin_port == pvt->recv.sin_port)){
12495 
12496       copy_socket_data(&peer->socket, &pvt->socket);
12497    }
12498 
12499    /* Now that our address has been updated put ourselves back into the container for lookups */
12500    ao2_t_link(peers_by_ip, peer, "ao2_link into peers_by_ip table");
12501 
12502    /* Save SIP options profile */
12503    peer->sipoptions = pvt->sipoptions;
12504 
12505    if (!ast_strlen_zero(curi) && ast_strlen_zero(peer->username))
12506       ast_string_field_set(peer, username, curi);
12507 
12508    AST_SCHED_DEL_UNREF(sched, peer->expire,
12509          unref_peer(peer, "remove register expire ref"));
12510 
12511    if (expire > max_expiry)
12512       expire = max_expiry;
12513    if (expire < min_expiry)
12514       expire = min_expiry;
12515    if (peer->is_realtime && !ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
12516       peer->expire = -1;
12517    } else {
12518       peer->expire = ast_sched_add(sched, (expire + 10) * 1000, expire_register,
12519             ref_peer(peer, "add registration ref"));
12520       if (peer->expire == -1) {
12521          unref_peer(peer, "remote registration ref");
12522       }
12523    }
12524    pvt->expiry = expire;
12525    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);
12526    /* Saving TCP connections is useless, we won't be able to reconnect 
12527       XXX WHY???? XXX
12528       \todo Fix this immediately.
12529    */
12530    if (!peer->rt_fromcontact && (peer->socket.type & SIP_TRANSPORT_UDP))
12531       ast_db_put("SIP/Registry", peer->name, data);
12532    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));
12533 
12534    /* Is this a new IP address for us? */
12535    if (VERBOSITY_ATLEAST(2) && inaddrcmp(&peer->addr, &oldsin)) {
12536       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));
12537    }
12538    sip_poke_peer(peer, 0);
12539    register_peer_exten(peer, 1);
12540    
12541    /* Save User agent */
12542    useragent = get_header(req, "User-Agent");
12543    if (strcasecmp(useragent, peer->useragent)) {
12544       ast_string_field_set(peer, useragent, useragent);
12545       ast_verb(4, "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
12546    }
12547    return PARSE_REGISTER_UPDATE;
12548 }
12549 
12550 /*! \brief Remove route from route list */
12551 static void free_old_route(struct sip_route *route)
12552 {
12553    struct sip_route *next;
12554 
12555    while (route) {
12556       next = route->next;
12557       ast_free(route);
12558       route = next;
12559    }
12560 }
12561 
12562 /*! \brief List all routes - mostly for debugging */
12563 static void list_route(struct sip_route *route)
12564 {
12565    if (!route)
12566       ast_verbose("list_route: no route\n");
12567    else {
12568       for (;route; route = route->next)
12569          ast_verbose("list_route: hop: <%s>\n", route->hop);
12570    }
12571 }
12572 
12573 /*! \brief Build route list from Record-Route header */
12574 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
12575 {
12576    struct sip_route *thishop, *head, *tail;
12577    int start = 0;
12578    int len;
12579    const char *rr, *contact, *c;
12580 
12581    /* Once a persistant route is set, don't fool with it */
12582    if (p->route && p->route_persistant) {
12583       ast_debug(1, "build_route: Retaining previous route: <%s>\n", p->route->hop);
12584       return;
12585    }
12586 
12587    if (p->route) {
12588       free_old_route(p->route);
12589       p->route = NULL;
12590    }
12591 
12592    /* We only want to create the route set the first time this is called */
12593    p->route_persistant = 1;
12594    
12595    /* Build a tailq, then assign it to p->route when done.
12596     * If backwards, we add entries from the head so they end up
12597     * in reverse order. However, we do need to maintain a correct
12598     * tail pointer because the contact is always at the end.
12599     */
12600    head = NULL;
12601    tail = head;
12602    /* 1st we pass through all the hops in any Record-Route headers */
12603    for (;;) {
12604       /* Each Record-Route header */
12605       rr = __get_header(req, "Record-Route", &start);
12606       if (*rr == '\0')
12607          break;
12608       for (; (rr = strchr(rr, '<')) ; rr += len) { /* Each route entry */
12609          ++rr;
12610          len = strcspn(rr, ">") + 1;
12611          /* Make a struct route */
12612          if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
12613             /* ast_calloc is not needed because all fields are initialized in this block */
12614             ast_copy_string(thishop->hop, rr, len);
12615             ast_debug(2, "build_route: Record-Route hop: <%s>\n", thishop->hop);
12616             /* Link in */
12617             if (backwards) {
12618                /* Link in at head so they end up in reverse order */
12619                thishop->next = head;
12620                head = thishop;
12621                /* If this was the first then it'll be the tail */
12622                if (!tail)
12623                   tail = thishop;
12624             } else {
12625                thishop->next = NULL;
12626                /* Link in at the end */
12627                if (tail)
12628                   tail->next = thishop;
12629                else
12630                   head = thishop;
12631                tail = thishop;
12632             }
12633          }
12634       }
12635    }
12636 
12637    /* Only append the contact if we are dealing with a strict router */
12638    if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop, ";lr") == NULL) ) {
12639       /* 2nd append the Contact: if there is one */
12640       /* Can be multiple Contact headers, comma separated values - we just take the first */
12641       contact = get_header(req, "Contact");
12642       if (!ast_strlen_zero(contact)) {
12643          ast_debug(2, "build_route: Contact hop: %s\n", contact);
12644          /* Look for <: delimited address */
12645          c = strchr(contact, '<');
12646          if (c) {
12647             /* Take to > */
12648             ++c;
12649             len = strcspn(c, ">") + 1;
12650          } else {
12651             /* No <> - just take the lot */
12652             c = contact;
12653             len = strlen(contact) + 1;
12654          }
12655          if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
12656             /* ast_calloc is not needed because all fields are initialized in this block */
12657             ast_copy_string(thishop->hop, c, len);
12658             thishop->next = NULL;
12659             /* Goes at the end */
12660             if (tail)
12661                tail->next = thishop;
12662             else
12663                head = thishop;
12664          }
12665       }
12666    }
12667 
12668    /* Store as new route */
12669    p->route = head;
12670 
12671    /* For debugging dump what we ended up with */
12672    if (sip_debug_test_pvt(p))
12673       list_route(p->route);
12674 }
12675 
12676 /*! \brief builds the sip_pvt's randdata field which is used for the nonce
12677  *  challenge.  When forceupdate is not set, the nonce is only updated if
12678  *  the current one is stale.  In this case, a stalenonce is one which
12679  *  has already received a response, if a nonce has not received a response
12680  *  it is not always necessary or beneficial to create a new one. */
12681 
12682 static void set_nonce_randdata(struct sip_pvt *p, int forceupdate)
12683 {
12684    if (p->stalenonce || forceupdate || ast_strlen_zero(p->randdata)) {
12685       ast_string_field_build(p, randdata, "%08lx", ast_random()); /* Create nonce for challenge */
12686       p->stalenonce = 0;
12687    }
12688 }
12689 
12690 AST_THREADSTORAGE(check_auth_buf);
12691 #define CHECK_AUTH_BUF_INITLEN   256
12692 
12693 /*! \brief  Check user authorization from peer definition 
12694    Some actions, like REGISTER and INVITEs from peers require
12695    authentication (if peer have secret set) 
12696     \return 0 on success, non-zero on error
12697 */
12698 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
12699                 const char *secret, const char *md5secret, int sipmethod,
12700                 char *uri, enum xmittype reliable, int ignore)
12701 {
12702    const char *response;
12703    char *reqheader, *respheader;
12704    const char *authtoken;
12705    char a1_hash[256];
12706    char resp_hash[256]="";
12707    char *c;
12708    int  wrongnonce = FALSE;
12709    int  good_response;
12710    const char *usednonce = p->randdata;
12711    struct ast_str *buf;
12712    int res;
12713 
12714    /* table of recognised keywords, and their value in the digest */
12715    enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
12716    struct x {
12717       const char *key;
12718       const char *s;
12719    } *i, keys[] = {
12720       [K_RESP] = { "response=", "" },
12721       [K_URI] = { "uri=", "" },
12722       [K_USER] = { "username=", "" },
12723       [K_NONCE] = { "nonce=", "" },
12724       [K_LAST] = { NULL, NULL}
12725    };
12726 
12727    /* Always OK if no secret */
12728    if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
12729       return AUTH_SUCCESSFUL;
12730 
12731    /* Always auth with WWW-auth since we're NOT a proxy */
12732    /* Using proxy-auth in a B2BUA may block proxy authorization in the same transaction */
12733    response = "401 Unauthorized";
12734 
12735    /*
12736     * Note the apparent swap of arguments below, compared to other
12737     * usages of auth_headers().
12738     */
12739    auth_headers(WWW_AUTH, &respheader, &reqheader);
12740 
12741    authtoken =  get_header(req, reqheader);  
12742    if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
12743       /* This is a retransmitted invite/register/etc, don't reconstruct authentication
12744          information */
12745       if (!reliable) {
12746          /* Resend message if this was NOT a reliable delivery.   Otherwise the
12747             retransmission should get it */
12748          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
12749          /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
12750          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12751       }
12752       return AUTH_CHALLENGE_SENT;
12753    } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
12754       /* We have no auth, so issue challenge and request authentication */
12755       set_nonce_randdata(p, 1); /* Create nonce for challenge */
12756       transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
12757       /* Schedule auto destroy in 32 seconds */
12758       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12759       return AUTH_CHALLENGE_SENT;
12760    } 
12761 
12762    /* --- We have auth, so check it */
12763 
12764    /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
12765       an example in the spec of just what it is you're doing a hash on. */
12766 
12767    if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN)))
12768       return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
12769 
12770    /* Make a copy of the response and parse it */
12771    res = ast_str_set(&buf, 0, "%s", authtoken);
12772 
12773    if (res == AST_DYNSTR_BUILD_FAILED)
12774       return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
12775 
12776    c = buf->str;
12777 
12778    while(c && *(c = ast_skip_blanks(c)) ) { /* lookup for keys */
12779       for (i = keys; i->key != NULL; i++) {
12780          const char *separator = ",";  /* default */
12781 
12782          if (strncasecmp(c, i->key, strlen(i->key)) != 0)
12783             continue;
12784          /* Found. Skip keyword, take text in quotes or up to the separator. */
12785          c += strlen(i->key);
12786          if (*c == '"') { /* in quotes. Skip first and look for last */
12787             c++;
12788             separator = "\"";
12789          }
12790          i->s = c;
12791          strsep(&c, separator);
12792          break;
12793       }
12794       if (i->key == NULL) /* not found, jump after space or comma */
12795          strsep(&c, " ,");
12796    }
12797 
12798    /* Verify that digest username matches  the username we auth as */
12799    if (strcmp(username, keys[K_USER].s)) {
12800       ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
12801          username, keys[K_USER].s);
12802       /* Oops, we're trying something here */
12803       return AUTH_USERNAME_MISMATCH;
12804    }
12805 
12806    /* Verify nonce from request matches our nonce, and the nonce has not already been responded to.
12807     * If this check fails, send 401 with new nonce */
12808    if (strcasecmp(p->randdata, keys[K_NONCE].s) || p->stalenonce) { /* XXX it was 'n'casecmp ? */
12809       wrongnonce = TRUE;
12810       usednonce = keys[K_NONCE].s;
12811    } else {
12812       p->stalenonce = 1; /* now, since the nonce has a response, mark it as stale so it can't be sent or responded to again */
12813    }
12814 
12815    if (!ast_strlen_zero(md5secret))
12816       ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
12817    else {
12818       char a1[256];
12819       snprintf(a1, sizeof(a1), "%s:%s:%s", username, sip_cfg.realm, secret);
12820       ast_md5_hash(a1_hash, a1);
12821    }
12822 
12823    /* compute the expected response to compare with what we received */
12824    {
12825       char a2[256];
12826       char a2_hash[256];
12827       char resp[256];
12828 
12829       snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
12830             S_OR(keys[K_URI].s, uri));
12831       ast_md5_hash(a2_hash, a2);
12832       snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
12833       ast_md5_hash(resp_hash, resp);
12834    }
12835 
12836    good_response = keys[K_RESP].s &&
12837          !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
12838    if (wrongnonce) {
12839       if (good_response) {
12840          if (sipdebug)
12841             ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "From"));
12842          /* We got working auth token, based on stale nonce . */
12843          set_nonce_randdata(p, 0);
12844          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
12845       } else {
12846          /* Everything was wrong, so give the device one more try with a new challenge */
12847          if (!req->ignore) {
12848             if (sipdebug)
12849                ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
12850             set_nonce_randdata(p, 1);
12851          } else {
12852             if (sipdebug)
12853                ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", get_header(req, "To"));
12854          }
12855          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
12856       }
12857 
12858       /* Schedule auto destroy in 32 seconds */
12859       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12860       return AUTH_CHALLENGE_SENT;
12861    } 
12862    if (good_response) {
12863       append_history(p, "AuthOK", "Auth challenge successful for %s", username);
12864       return AUTH_SUCCESSFUL;
12865    }
12866 
12867    /* Ok, we have a bad username/secret pair */
12868    /* Tell the UAS not to re-send this authentication data, because
12869       it will continue to fail
12870    */
12871 
12872    return AUTH_SECRET_FAILED;
12873 }
12874 
12875 /*! \brief Change onhold state of a peer using a pvt structure */
12876 static void sip_peer_hold(struct sip_pvt *p, int hold)
12877 {
12878    struct sip_peer *peer = find_peer(p->peername, NULL, 1, FINDALLDEVICES, FALSE, 0);
12879 
12880    if (!peer)
12881       return;
12882 
12883    /* If they put someone on hold, increment the value... otherwise decrement it */
12884    ast_atomic_fetchadd_int(&peer->onHold, (hold ? +1 : -1));
12885 
12886    /* Request device state update */
12887    ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
12888    unref_peer(peer, "sip_peer_hold: from find_peer operation");
12889    
12890    return;
12891 }
12892 
12893 /*! \brief Receive MWI events that we have subscribed to */
12894 static void mwi_event_cb(const struct ast_event *event, void *userdata)
12895 {
12896    struct sip_peer *peer = userdata;
12897 
12898    ao2_lock(peer);
12899    sip_send_mwi_to_peer(peer, event, 0);
12900    ao2_unlock(peer);
12901 }
12902 
12903 /*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem
12904 \note If you add an "hint" priority to the extension in the dial plan,
12905    you will get notifications on device state changes */
12906 static int cb_extensionstate(char *context, char* exten, int state, void *data)
12907 {
12908    struct sip_pvt *p = data;
12909 
12910    sip_pvt_lock(p);
12911 
12912    switch(state) {
12913    case AST_EXTENSION_DEACTIVATED:  /* Retry after a while */
12914    case AST_EXTENSION_REMOVED:   /* Extension is gone */
12915       if (p->autokillid > -1 && sip_cancel_destroy(p))   /* Remove subscription expiry for renewals */
12916          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
12917       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);  /* Delete subscription in 32 secs */
12918       ast_verb(2, "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
12919       p->stateid = -1;
12920       p->subscribed = NONE;
12921       append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
12922       break;
12923    default: /* Tell user */
12924       p->laststate = state;
12925       break;
12926    }
12927    if (p->subscribed != NONE) {  /* Only send state NOTIFY if we know the format */
12928       if (!p->pendinginvite) {
12929          transmit_state_notify(p, state, 1, FALSE);
12930       } else {
12931          /* We already have a NOTIFY sent that is not answered. Queue the state up.
12932             if many state changes happen meanwhile, we will only send a notification of the last one */
12933          ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
12934       }
12935    }
12936    ast_verb(2, "Extension Changed %s[%s] new state %s for Notify User %s %s\n", exten, context, ast_extension_state2str(state), p->username,
12937          ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
12938 
12939    sip_pvt_unlock(p);
12940 
12941    return 0;
12942 }
12943 
12944 /*! \brief Send a fake 401 Unauthorized response when the administrator
12945   wants to hide the names of local devices  from fishers
12946  */
12947 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable)
12948 {
12949    /* We have to emulate EXACTLY what we'd get with a good peer
12950     * and a bad password, or else we leak information. */
12951    const char *response = "407 Proxy Authentication Required";
12952    const char *reqheader = "Proxy-Authorization";
12953    const char *respheader = "Proxy-Authenticate";
12954    const char *authtoken;
12955    struct ast_str *buf;
12956    char *c;
12957 
12958    /* table of recognised keywords, and their value in the digest */
12959    enum keys { K_NONCE, K_LAST };
12960    struct x {
12961       const char *key;
12962       const char *s;
12963    } *i, keys[] = {
12964       [K_NONCE] = { "nonce=", "" },
12965       [K_LAST] = { NULL, NULL}
12966    };
12967 
12968    if (sipmethod == SIP_REGISTER || sipmethod == SIP_SUBSCRIBE) {
12969       response = "401 Unauthorized";
12970       reqheader = "Authorization";
12971       respheader = "WWW-Authenticate";
12972    }
12973    authtoken = get_header(req, reqheader);
12974    if (req->ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
12975       /* This is a retransmitted invite/register/etc, don't reconstruct authentication
12976        * information */
12977       transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
12978       /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
12979       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12980       return;
12981    } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
12982       /* We have no auth, so issue challenge and request authentication */
12983       set_nonce_randdata(p, 1);
12984       transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
12985       /* Schedule auto destroy in 32 seconds */
12986       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12987       return;
12988    }
12989 
12990    if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
12991       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
12992       return;
12993    }
12994 
12995    /* Make a copy of the response and parse it */
12996    if (ast_str_set(&buf, 0, "%s", authtoken) == AST_DYNSTR_BUILD_FAILED) {
12997       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
12998       return;
12999    }
13000 
13001    c = buf->str;
13002 
13003    while (c && *(c = ast_skip_blanks(c))) { /* lookup for keys */
13004       for (i = keys; i->key != NULL; i++) {
13005          const char *separator = ",";  /* default */
13006 
13007          if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
13008             continue;
13009          }
13010          /* Found. Skip keyword, take text in quotes or up to the separator. */
13011          c += strlen(i->key);
13012          if (*c == '"') { /* in quotes. Skip first and look for last */
13013             c++;
13014             separator = "\"";
13015          }
13016          i->s = c;
13017          strsep(&c, separator);
13018          break;
13019       }
13020       if (i->key == NULL) { /* not found, jump after space or comma */
13021          strsep(&c, " ,");
13022       }
13023    }
13024 
13025    /* Verify nonce from request matches our nonce.  If not, send 401 with new nonce */
13026    if (strcasecmp(p->randdata, keys[K_NONCE].s)) {
13027       if (!req->ignore) {
13028          set_nonce_randdata(p, 1);
13029       }
13030       transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
13031 
13032       /* Schedule auto destroy in 32 seconds */
13033       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13034    } else {
13035       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
13036    }
13037 }
13038 
13039 /*!
13040  * Terminate the uri at the first ';' or space.
13041  * Technically we should ignore escaped space per RFC3261 (19.1.1 etc)
13042  * but don't do it for the time being. Remember the uri format is:
13043  * (User-parameters was added after RFC 3261)
13044  *\verbatim
13045  *
13046  * sip:user:password;user-parameters@host:port;uri-parameters?headers
13047  * sips:user:password;user-parameters@host:port;uri-parameters?headers
13048  *
13049  *\endverbatim
13050  * \todo As this function does not support user-parameters, it's considered broken
13051  * and needs fixing.
13052  */
13053 static char *terminate_uri(char *uri)
13054 {
13055    char *t = uri;
13056    while (*t && *t > ' ' && *t != ';')
13057       t++;
13058    *t = '\0';
13059    return uri;
13060 }
13061 
13062 /*! \brief Verify registration of user 
13063    - Registration is done in several steps, first a REGISTER without auth
13064      to get a challenge (nonce) then a second one with auth
13065    - Registration requests are only matched with peers that are marked as "dynamic"
13066  */
13067 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
13068                      struct sip_request *req, char *uri)
13069 {
13070    enum check_auth_result res = AUTH_NOT_FOUND;
13071    struct sip_peer *peer;
13072    char tmp[256];
13073    char *name, *c;
13074    char *domain;
13075 
13076    terminate_uri(uri);  /* warning, overwrite the string */
13077 
13078    ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
13079    if (sip_cfg.pedanticsipchecking)
13080       ast_uri_decode(tmp);
13081 
13082    c = get_in_brackets(tmp);
13083    c = remove_uri_parameters(c);
13084 
13085    if (!strncasecmp(c, "sip:", 4)) {
13086       name = c + 4;
13087    } else if (!strncasecmp(c, "sips:", 5)) {
13088       name = c + 5;
13089    } else {
13090       name = c;
13091       ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_inet_ntoa(sin->sin_addr));
13092    }
13093 
13094    /*! \todo XXX here too we interpret a missing @domain as a name-only
13095     * URI, whereas the RFC says this is a domain-only uri.
13096     */
13097    /* Strip off the domain name */
13098    if ((c = strchr(name, '@'))) {
13099       *c++ = '\0';
13100       domain = c;
13101       if ((c = strchr(domain, ':')))   /* Remove :port */
13102          *c = '\0';
13103       if (!AST_LIST_EMPTY(&domain_list)) {
13104          if (!check_sip_domain(domain, NULL, 0)) {
13105             transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
13106             return AUTH_UNKNOWN_DOMAIN;
13107          }
13108       }
13109    }
13110    c = strchr(name, ';');  /* Remove any Username parameters */
13111    if (c)
13112       *c = '\0';
13113 
13114    ast_string_field_set(p, exten, name);
13115    build_contact(p);
13116    if (req->ignore) {
13117       /* Expires is a special case, where we only want to load the peer if this isn't a deregistration attempt */
13118       const char *expires = get_header(req, "Expires");
13119       int expire = atoi(expires);
13120 
13121       if (ast_strlen_zero(expires)) { /* No expires header; look in Contact */
13122          if ((expires = strcasestr(get_header(req, "Contact"), ";expires="))) {
13123             expire = atoi(expires + 9);
13124          }
13125       }
13126       if (!ast_strlen_zero(expires) && expire == 0) {
13127          transmit_response_with_date(p, "200 OK", req);
13128          return 0;
13129       }
13130    }
13131    peer = find_peer(name, NULL, TRUE, FINDPEERS, FALSE, 0);
13132    if (!(peer && ast_apply_ha(peer->ha, sin))) {
13133       /* Peer fails ACL check */
13134       if (peer) {
13135          unref_peer(peer, "register_verify: unref_peer: from find_peer operation");
13136          peer = NULL;
13137          res = AUTH_ACL_FAILED;
13138       } else
13139          res = AUTH_NOT_FOUND;
13140    }
13141 
13142    if (peer) {
13143       /*! \todo OEJ Remove this - there's never RTP in a REGISTER dialog... */
13144       /* Set Frame packetization */
13145       if (p->rtp) {
13146          ast_rtp_codec_setpref(p->rtp, &peer->prefs);
13147          p->autoframing = peer->autoframing;
13148       }
13149       if (!peer->host_dynamic) {
13150          ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
13151          res = AUTH_PEER_NOT_DYNAMIC;
13152       } else {
13153          ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT);
13154          if (ast_test_flag(&p->flags[1], SIP_PAGE2_REGISTERTRYING))
13155             transmit_response(p, "100 Trying", req);
13156          if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri, XMIT_UNRELIABLE, req->ignore))) {
13157             if (sip_cancel_destroy(p))
13158                ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
13159 
13160             if (check_request_transport(peer, req)) {
13161                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
13162                transmit_response_with_date(p, "403 Forbidden", req);
13163                res = AUTH_BAD_TRANSPORT;
13164             } else {
13165 
13166                /* We have a successful registration attempt with proper authentication,
13167                   now, update the peer */
13168                switch (parse_register_contact(p, peer, req)) {
13169                case PARSE_REGISTER_DENIED:
13170                   ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
13171                   transmit_response_with_date(p, "603 Denied", req);
13172                   peer->lastmsgssent = -1;
13173                   res = 0;
13174                   break;
13175                case PARSE_REGISTER_FAILED:
13176                   ast_log(LOG_WARNING, "Failed to parse contact info\n");
13177                   transmit_response_with_date(p, "400 Bad Request", req);
13178                   peer->lastmsgssent = -1;
13179                   res = 0;
13180                   break;
13181                case PARSE_REGISTER_QUERY:
13182                   ast_string_field_set(p, fullcontact, peer->fullcontact);
13183                   transmit_response_with_date(p, "200 OK", req);
13184                   peer->lastmsgssent = -1;
13185                   res = 0;
13186                   break;
13187                case PARSE_REGISTER_UPDATE:
13188                   ast_string_field_set(p, fullcontact, peer->fullcontact);
13189                   update_peer(peer, p->expiry);
13190                   /* Say OK and ask subsystem to retransmit msg counter */
13191                   transmit_response_with_date(p, "200 OK", req);
13192                   if (!ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY))
13193                      peer->lastmsgssent = -1;
13194                   res = 0;
13195                   break;
13196                }
13197             }
13198 
13199          } 
13200       }
13201    }
13202    if (!peer && sip_cfg.autocreatepeer) {
13203       /* Create peer if we have autocreate mode enabled */
13204       peer = temp_peer(name);
13205       if (peer) {
13206          ao2_t_link(peers, peer, "link peer into peer table");
13207          if (peer->addr.sin_addr.s_addr) {
13208             ao2_t_link(peers_by_ip, peer, "link peer into peers-by-ip table");
13209          }
13210          
13211          if (sip_cancel_destroy(p))
13212             ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
13213          switch (parse_register_contact(p, peer, req)) {
13214          case PARSE_REGISTER_DENIED:
13215             ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
13216             transmit_response_with_date(p, "403 Forbidden (ACL)", req);
13217             peer->lastmsgssent = -1;
13218             res = 0;
13219             break;
13220          case PARSE_REGISTER_FAILED:
13221             ast_log(LOG_WARNING, "Failed to parse contact info\n");
13222             transmit_response_with_date(p, "400 Bad Request", req);
13223             peer->lastmsgssent = -1;
13224             res = 0;
13225             break;
13226          case PARSE_REGISTER_QUERY:
13227             ast_string_field_set(p, fullcontact, peer->fullcontact);
13228             transmit_response_with_date(p, "200 OK", req);
13229             peer->lastmsgssent = -1;
13230             res = 0;
13231             break;
13232          case PARSE_REGISTER_UPDATE:
13233             ast_string_field_set(p, fullcontact, peer->fullcontact);
13234             /* Say OK and ask subsystem to retransmit msg counter */
13235             transmit_response_with_date(p, "200 OK", req);
13236             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));
13237             peer->lastmsgssent = -1;
13238             res = 0;
13239             break;
13240          }
13241       }
13242    }
13243    if (!peer && sip_cfg.alwaysauthreject) {
13244       /* If we found a peer, we transmit a 100 Trying.  Therefore, if we're
13245        * trying to avoid leaking information, we MUST also transmit the same
13246        * response when we DON'T find a peer. */
13247       transmit_response(p, "100 Trying", req);
13248       /* Insert a fake delay between the 100 and the subsequent failure. */
13249       sched_yield();
13250    }
13251    if (!res) {
13252       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
13253    }
13254    if (res < 0) {
13255       switch (res) {
13256       case AUTH_SECRET_FAILED:
13257          /* Wrong password in authentication. Go away, don't try again until you fixed it */
13258          transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
13259          if (global_authfailureevents)
13260             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", 
13261                name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13262          break;
13263       case AUTH_USERNAME_MISMATCH:
13264          /* Username and digest username does not match.
13265             Asterisk uses the From: username for authentication. We need the
13266             devices to use the same authentication user name until we support
13267             proper authentication by digest auth name */
13268       case AUTH_NOT_FOUND:
13269       case AUTH_PEER_NOT_DYNAMIC:
13270       case AUTH_ACL_FAILED:
13271          if (sip_cfg.alwaysauthreject) {
13272             transmit_fake_auth_response(p, SIP_REGISTER, &p->initreq, XMIT_UNRELIABLE);
13273             if (global_authfailureevents) {
13274                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",
13275                   name, res == AUTH_PEER_NOT_DYNAMIC ? "AUTH_PEER_NOT_DYNAMIC" : "URI_NOT_FOUND",
13276                   ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13277             }
13278          } else {
13279             /* URI not found */
13280             if (res == AUTH_PEER_NOT_DYNAMIC) {
13281                transmit_response(p, "403 Forbidden", &p->initreq);
13282                if (global_authfailureevents) {
13283                   manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
13284                      "ChannelType: SIP\r\n"
13285                      "Peer: SIP/%s\r\n"
13286                      "PeerStatus: Rejected\r\n"
13287                      "Cause: AUTH_PEER_NOT_DYNAMIC\r\n"
13288                      "Address: %s\r\n"
13289                      "Port: %d\r\n",
13290                      name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13291                }
13292             } else {
13293                transmit_response(p, "404 Not found", &p->initreq);
13294                if (global_authfailureevents) {
13295                   manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
13296                      "ChannelType: SIP\r\n"
13297                      "Peer: SIP/%s\r\n"
13298                      "PeerStatus: Rejected\r\n"
13299                      "Cause: %s\r\n"
13300                      "Address: %s\r\n"
13301                      "Port: %d\r\n",
13302                      name,
13303                      (res == AUTH_USERNAME_MISMATCH) ? "AUTH_USERNAME_MISMATCH" : "URI_NOT_FOUND",
13304                      ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13305                }
13306             }
13307          }
13308          break;
13309       case AUTH_BAD_TRANSPORT:
13310       default:
13311          break;
13312       }
13313    }
13314    if (peer)
13315       unref_peer(peer, "register_verify: unref_peer: tossing stack peer pointer at end of func");
13316 
13317    return res;
13318 }
13319 
13320 /*! \brief Translate referring cause */
13321 static void sip_set_redirstr(struct sip_pvt *p, char *reason) {
13322 
13323    if (!strcmp(reason, "unknown")) {
13324       ast_string_field_set(p, redircause, "UNKNOWN");
13325    } else if (!strcmp(reason, "user-busy")) {
13326       ast_string_field_set(p, redircause, "BUSY");
13327    } else if (!strcmp(reason, "no-answer")) {
13328       ast_string_field_set(p, redircause, "NOANSWER");
13329    } else if (!strcmp(reason, "unavailable")) {
13330       ast_string_field_set(p, redircause, "UNREACHABLE");
13331    } else if (!strcmp(reason, "unconditional")) {
13332       ast_string_field_set(p, redircause, "UNCONDITIONAL");
13333    } else if (!strcmp(reason, "time-of-day")) {
13334       ast_string_field_set(p, redircause, "UNKNOWN");
13335    } else if (!strcmp(reason, "do-not-disturb")) {
13336       ast_string_field_set(p, redircause, "UNKNOWN");
13337    } else if (!strcmp(reason, "deflection")) {
13338       ast_string_field_set(p, redircause, "UNKNOWN");
13339    } else if (!strcmp(reason, "follow-me")) {
13340       ast_string_field_set(p, redircause, "UNKNOWN");
13341    } else if (!strcmp(reason, "out-of-service")) {
13342       ast_string_field_set(p, redircause, "UNREACHABLE");
13343    } else if (!strcmp(reason, "away")) {
13344       ast_string_field_set(p, redircause, "UNREACHABLE");
13345    } else {
13346       ast_string_field_set(p, redircause, "UNKNOWN");
13347    }
13348 }
13349 
13350 /*! \brief Get referring dnis */
13351 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq)
13352 {
13353    char tmp[256], *exten, *rexten, *rdomain;
13354    char *params, *reason = NULL;
13355    struct sip_request *req;
13356    
13357    req = oreq ? oreq : &p->initreq;
13358 
13359    ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
13360    if (ast_strlen_zero(tmp))
13361       return 0;
13362 
13363    /*! \todo This function does not take user-parameters into consideration.
13364       First look for @, then start looking for ; to find uri-parameters.
13365    */
13366    params = strchr(tmp, ';');
13367 
13368    exten = get_in_brackets(tmp);
13369    if (!strncasecmp(exten, "sip:", 4)) {
13370       exten += 4;
13371    } else if (!strncasecmp(exten, "sips:", 5)) {
13372       exten += 5;
13373    } else {
13374       ast_log(LOG_WARNING, "Huh?  Not an RDNIS SIP header (%s)?\n", exten);
13375       return -1;
13376    }
13377 
13378    /* Get diversion-reason param if present */
13379    if (params) {
13380       *params = '\0';   /* Cut off parameters  */
13381       params++;
13382       while (*params == ';' || *params == ' ')
13383          params++;
13384       /* Check if we have a reason parameter */
13385       if ((reason = strcasestr(params, "reason="))) {
13386          reason+=7;
13387          /* Remove enclosing double-quotes */
13388          if (*reason == '"') 
13389             ast_strip_quoted(reason, "\"", "\"");
13390          if (!ast_strlen_zero(reason)) {
13391             sip_set_redirstr(p, reason);
13392             if (p->owner) {
13393                pbx_builtin_setvar_helper(p->owner, "__PRIREDIRECTREASON", p->redircause);
13394                pbx_builtin_setvar_helper(p->owner, "__SIPREDIRECTREASON", reason);
13395             }
13396          }
13397       }
13398    }
13399 
13400    rdomain = exten;
13401    rexten = strsep(&rdomain, "@");  /* trim anything after @ */
13402    if (p->owner) 
13403       pbx_builtin_setvar_helper(p->owner, "__SIPRDNISDOMAIN", rdomain);
13404 
13405    if (sip_debug_test_pvt(p))
13406       ast_verbose("RDNIS for this call is is %s (reason %s)\n", exten, reason ? reason : "");
13407 
13408    ast_string_field_set(p, rdnis, rexten);
13409 
13410    return 0;
13411 }
13412 
13413 /*! \brief Find out who the call is for.
13414    We use the request uri as a destination. 
13415    This code assumes authentication has been done, so that the
13416    device (peer/user) context is already set.
13417    \return 0 on success (found a matching extension),
13418    1 for pickup extension or overlap dialling support (if we support it),
13419    -1 on error.
13420 
13421   \note If the incoming uri is a SIPS: uri, we are required to carry this across
13422    the dialplan, so that the outbound call also is a sips: call or encrypted
13423    IAX2 call. If that's not available, the call should FAIL.
13424 */
13425 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
13426 {
13427    char tmp[256] = "", *uri, *a;
13428    char tmpf[256] = "", *from = NULL;
13429    struct sip_request *req;
13430    char *colon;
13431    char *decoded_uri;
13432    
13433    req = oreq;
13434    if (!req)
13435       req = &p->initreq;
13436 
13437    /* Find the request URI */
13438    if (req->rlPart2)
13439       ast_copy_string(tmp, REQ_OFFSET_TO_STR(req, rlPart2), sizeof(tmp));
13440    
13441    if (sip_cfg.pedanticsipchecking)
13442       ast_uri_decode(tmp);
13443 
13444    uri = get_in_brackets(tmp);
13445    
13446    if (!strncasecmp(uri, "sip:", 4)) {
13447       uri += 4;
13448    } else if (!strncasecmp(uri, "sips:", 5)) {
13449       uri += 5;
13450    } else {
13451       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", uri);
13452       return -1;
13453    }
13454 
13455    /* Now find the From: caller ID and name */
13456    /* XXX Why is this done in get_destination? Isn't it already done?
13457       Needs to be checked 
13458         */
13459    ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
13460    if (!ast_strlen_zero(tmpf)) {
13461       if (sip_cfg.pedanticsipchecking)
13462          ast_uri_decode(tmpf);
13463       from = get_in_brackets(tmpf);
13464    } 
13465    
13466    if (!ast_strlen_zero(from)) {
13467       if (!strncasecmp(from, "sip:", 4)) {
13468          from += 4;
13469       } else if (!strncasecmp(from, "sips:", 5)) {
13470          from += 5;
13471       } else {
13472          ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", from);
13473          return -1;
13474       }
13475       if ((a = strchr(from, '@')))
13476          *a++ = '\0';
13477       else
13478          a = from;   /* just a domain */
13479       from = strsep(&from, ";"); /* Remove userinfo options */
13480       a = strsep(&a, ";");    /* Remove URI options */
13481       ast_string_field_set(p, fromdomain, a);
13482    }
13483 
13484    /* Skip any options and find the domain */
13485 
13486    /* Get the target domain */
13487    if ((a = strchr(uri, '@'))) {
13488       *a++ = '\0';
13489    } else { /* No username part */
13490       a = uri;
13491       uri = "s";  /* Set extension to "s" */
13492    }
13493    colon = strchr(a, ':'); /* Remove :port */
13494    if (colon)
13495       *colon = '\0';
13496 
13497    uri = strsep(&uri, ";");   /* Remove userinfo options */
13498    a = strsep(&a, ";");    /* Remove URI options */
13499 
13500    ast_string_field_set(p, domain, a);
13501 
13502    if (!AST_LIST_EMPTY(&domain_list)) {
13503       char domain_context[AST_MAX_EXTENSION];
13504 
13505       domain_context[0] = '\0';
13506       if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
13507          if (!sip_cfg.allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
13508             ast_debug(1, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
13509             return -2;
13510          }
13511       }
13512       /* If we don't have a peer (i.e. we're a guest call),
13513        * overwrite the original context */
13514       if (!ast_test_flag(&p->flags[1], SIP_PAGE2_HAVEPEERCONTEXT) && !ast_strlen_zero(domain_context))
13515          ast_string_field_set(p, context, domain_context);
13516    }
13517 
13518    /* If the request coming in is a subscription and subscribecontext has been specified use it */
13519    if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext))
13520       ast_string_field_set(p, context, p->subscribecontext);
13521 
13522    if (sip_debug_test_pvt(p))
13523       ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
13524 
13525    /* If this is a subscription we actually just need to see if a hint exists for the extension */
13526    if (req->method == SIP_SUBSCRIBE) {
13527       char hint[AST_MAX_EXTENSION];
13528       return (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten) ? 0 : -1);
13529    } else {
13530       decoded_uri = ast_strdupa(uri);
13531       ast_uri_decode(decoded_uri);
13532       /* Check the dialplan for the username part of the request URI,
13533          the domain will be stored in the SIPDOMAIN variable
13534          Since extensions.conf can have unescaped characters, try matching a decoded
13535          uri in addition to the non-decoded uri
13536          Return 0 if we have a matching extension */
13537       if (ast_exists_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from)) || ast_exists_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from)) ||
13538           !strcmp(decoded_uri, ast_pickup_ext())) {
13539          if (!oreq)
13540             ast_string_field_set(p, exten, decoded_uri);
13541          return 0;
13542       } 
13543    }
13544 
13545    /* Return 1 for pickup extension or overlap dialling support (if we support it) */
13546    if((ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) && 
13547        ast_canmatch_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))) ||
13548        !strncmp(decoded_uri, ast_pickup_ext(), strlen(decoded_uri))) {
13549       return 1;
13550    }
13551    
13552    return -1;
13553 }
13554 
13555 /*! \brief Lock dialog lock and find matching pvt lock  
13556    \return a reference, remember to release it when done 
13557 */
13558 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag) 
13559 {
13560    struct sip_pvt *sip_pvt_ptr;
13561    struct sip_pvt tmp_dialog = {
13562       .callid = callid,
13563    };
13564 
13565    if (totag)
13566       ast_debug(4, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
13567 
13568    /* Search dialogs and find the match */
13569    
13570    sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find of dialog in dialogs table");
13571    if (sip_pvt_ptr) {
13572       /* Go ahead and lock it (and its owner) before returning */
13573       sip_pvt_lock(sip_pvt_ptr);
13574       if (sip_cfg.pedanticsipchecking) {
13575          unsigned char frommismatch = 0, tomismatch = 0;
13576 
13577          if (ast_strlen_zero(fromtag)) {
13578             sip_pvt_unlock(sip_pvt_ptr);
13579             ast_debug(4, "Matched %s call for callid=%s - no from tag specified, pedantic check fails\n",
13580                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
13581             return NULL;
13582          }
13583 
13584          if (ast_strlen_zero(totag)) {
13585             sip_pvt_unlock(sip_pvt_ptr);
13586             ast_debug(4, "Matched %s call for callid=%s - no to tag specified, pedantic check fails\n",
13587                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
13588             return NULL;
13589          }
13590          /* RFC 3891
13591           * > 3.  User Agent Server Behavior: Receiving a Replaces Header
13592           * > The Replaces header contains information used to match an existing
13593           * > SIP dialog (call-id, to-tag, and from-tag).  Upon receiving an INVITE
13594           * > with a Replaces header, the User Agent (UA) attempts to match this
13595           * > information with a confirmed or early dialog.  The User Agent Server
13596           * > (UAS) matches the to-tag and from-tag parameters as if they were tags
13597           * > present in an incoming request.  In other words, the to-tag parameter
13598           * > is compared to the local tag, and the from-tag parameter is compared
13599           * > to the remote tag.
13600           *
13601           * Thus, the totag is always compared to the local tag, regardless if
13602           * this our call is an incoming or outgoing call.
13603           */
13604          frommismatch = !!strcmp(fromtag, sip_pvt_ptr->theirtag);
13605          tomismatch = !!strcmp(totag, sip_pvt_ptr->tag);
13606 
13607          if (frommismatch || tomismatch) {
13608             sip_pvt_unlock(sip_pvt_ptr);
13609             if (frommismatch) {
13610                ast_debug(4, "Matched %s call for callid=%s - pedantic from tag check fails; their tag is %s our tag is %s\n",
13611                     sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid, 
13612                     fromtag, sip_pvt_ptr->theirtag);
13613             }
13614             if (tomismatch) {
13615                ast_debug(4, "Matched %s call for callid=%s - pedantic to tag check fails; their tag is %s our tag is %s\n",
13616                     sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid, 
13617                     totag, sip_pvt_ptr->tag);
13618             }
13619             return NULL;
13620          }
13621       }
13622       
13623       if (totag)
13624          ast_debug(4, "Matched %s call - their tag is %s Our tag is %s\n",
13625                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING",
13626                  sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
13627 
13628       /* deadlock avoidance... */
13629       while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
13630          sip_pvt_unlock(sip_pvt_ptr);
13631          usleep(1);
13632          sip_pvt_lock(sip_pvt_ptr);
13633       }
13634    }
13635    
13636    return sip_pvt_ptr;
13637 }
13638 
13639 /*! \brief Call transfer support (the REFER method) 
13640  *    Extracts Refer headers into pvt dialog structure 
13641  *
13642  * \note If we get a SIPS uri in the refer-to header, we're required to set up a secure signalling path
13643  * to that extension. As a minimum, this needs to be added to a channel variable, if not a channel
13644  * flag.
13645  */
13646 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
13647 {
13648 
13649    const char *p_referred_by = NULL;
13650    char *h_refer_to = NULL; 
13651    char *h_referred_by = NULL;
13652    char *refer_to;
13653    const char *p_refer_to;
13654    char *referred_by_uri = NULL;
13655    char *ptr;
13656    struct sip_request *req = NULL;
13657    const char *transfer_context = NULL;
13658    struct sip_refer *referdata;
13659 
13660 
13661    req = outgoing_req;
13662    referdata = transferer->refer;
13663 
13664    if (!req)
13665       req = &transferer->initreq;
13666 
13667    p_refer_to = get_header(req, "Refer-To");
13668    if (ast_strlen_zero(p_refer_to)) {
13669       ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
13670       return -2;  /* Syntax error */
13671    }
13672    h_refer_to = ast_strdupa(p_refer_to);
13673    refer_to = get_in_brackets(h_refer_to);
13674    if (sip_cfg.pedanticsipchecking)
13675       ast_uri_decode(refer_to);
13676 
13677    if (!strncasecmp(refer_to, "sip:", 4)) {
13678       refer_to += 4;       /* Skip sip: */
13679    } else if (!strncasecmp(refer_to, "sips:", 5)) {
13680       refer_to += 5;
13681    } else {
13682       ast_log(LOG_WARNING, "Can't transfer to non-sip: URI.  (Refer-to: %s)?\n", refer_to);
13683       return -3;
13684    }
13685 
13686    /* Get referred by header if it exists */
13687    p_referred_by = get_header(req, "Referred-By");
13688 
13689    /* Give useful transfer information to the dialplan */
13690    if (transferer->owner) {
13691       struct ast_channel *peer = ast_bridged_channel(transferer->owner);
13692       if (peer) {
13693          pbx_builtin_setvar_helper(peer, "SIPREFERRINGCONTEXT", transferer->context);
13694          pbx_builtin_setvar_helper(peer, "SIPREFERREDBYHDR", p_referred_by);
13695       }
13696    }
13697 
13698    if (!ast_strlen_zero(p_referred_by)) {
13699       char *lessthan;
13700       h_referred_by = ast_strdupa(p_referred_by);
13701       if (sip_cfg.pedanticsipchecking)
13702          ast_uri_decode(h_referred_by);
13703 
13704       /* Store referrer's caller ID name */
13705       ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
13706       if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
13707          *(lessthan - 1) = '\0'; /* Space */
13708       }
13709 
13710       referred_by_uri = get_in_brackets(h_referred_by);
13711       if (!strncasecmp(referred_by_uri, "sip:", 4)) {
13712          referred_by_uri += 4;      /* Skip sip: */
13713       } else if (!strncasecmp(referred_by_uri, "sips:", 5)) {
13714          referred_by_uri += 5;      /* Skip sips: */
13715       } else {
13716          ast_log(LOG_WARNING, "Huh?  Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
13717          referred_by_uri = NULL;
13718       }
13719    }
13720 
13721    /* Check for arguments in the refer_to header */
13722    if ((ptr = strcasestr(refer_to, "replaces="))) {
13723       char *to = NULL, *from = NULL;
13724       
13725       /* This is an attended transfer */
13726       referdata->attendedtransfer = 1;
13727       ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
13728       ast_uri_decode(referdata->replaces_callid);
13729       if ((ptr = strchr(referdata->replaces_callid, ';')))  /* Find options */ {
13730          *ptr++ = '\0';
13731       }
13732       
13733       if (ptr) {
13734          /* Find the different tags before we destroy the string */
13735          to = strcasestr(ptr, "to-tag=");
13736          from = strcasestr(ptr, "from-tag=");
13737       }
13738       
13739       /* Grab the to header */
13740       if (to) {
13741          ptr = to + 7;
13742          if ((to = strchr(ptr, '&')))
13743             *to = '\0';
13744          if ((to = strchr(ptr, ';')))
13745             *to = '\0';
13746          ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
13747       }
13748       
13749       if (from) {
13750          ptr = from + 9;
13751          if ((to = strchr(ptr, '&')))
13752             *to = '\0';
13753          if ((to = strchr(ptr, ';')))
13754             *to = '\0';
13755          ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
13756       }
13757       
13758       if (!sip_cfg.pedanticsipchecking)
13759          ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
13760       else
13761          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>" );
13762    }
13763    
13764    if ((ptr = strchr(refer_to, '@'))) {   /* Separate domain */
13765       char *urioption = NULL, *domain;
13766       *ptr++ = '\0';
13767 
13768       if ((urioption = strchr(ptr, ';'))) /* Separate urioptions */
13769          *urioption++ = '\0';
13770       
13771       domain = ptr;
13772       if ((ptr = strchr(domain, ':'))) /* Remove :port */
13773          *ptr = '\0';
13774       
13775       /* Save the domain for the dial plan */
13776       ast_copy_string(referdata->refer_to_domain, domain, sizeof(referdata->refer_to_domain));
13777       if (urioption)
13778          ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
13779    }
13780 
13781    if ((ptr = strchr(refer_to, ';')))  /* Remove options */
13782       *ptr = '\0';
13783    ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
13784    
13785    if (referred_by_uri) {
13786       if ((ptr = strchr(referred_by_uri, ';')))    /* Remove options */
13787          *ptr = '\0';
13788       ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
13789    } else {
13790       referdata->referred_by[0] = '\0';
13791    }
13792 
13793    /* Determine transfer context */
13794    if (transferer->owner)  /* Mimic behaviour in res_features.c */
13795       transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
13796 
13797    /* By default, use the context in the channel sending the REFER */
13798    if (ast_strlen_zero(transfer_context)) {
13799       transfer_context = S_OR(transferer->owner->macrocontext,
13800                S_OR(transferer->context, sip_cfg.default_context));
13801    }
13802 
13803    ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
13804    
13805    /* Either an existing extension or the parking extension */
13806    if (referdata->attendedtransfer || ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
13807       if (sip_debug_test_pvt(transferer)) {
13808          ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
13809       }
13810       /* We are ready to transfer to the extension */
13811       return 0;
13812    } 
13813    if (sip_debug_test_pvt(transferer))
13814       ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
13815 
13816    /* Failure, we can't find this extension */
13817    return -1;
13818 }
13819 
13820 
13821 /*! \brief Call transfer support (old way, deprecated by the IETF)
13822  * \note does not account for SIPS: uri requirements, nor check transport
13823  */
13824 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
13825 {
13826    char tmp[256] = "", *c, *a;
13827    struct sip_request *req = oreq ? oreq : &p->initreq;
13828    struct sip_refer *referdata = NULL;
13829    const char *transfer_context = NULL;
13830    
13831    if (!p->refer && !sip_refer_allocate(p))
13832       return -1;
13833 
13834    referdata = p->refer;
13835 
13836    ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
13837    c = get_in_brackets(tmp);
13838 
13839    if (sip_cfg.pedanticsipchecking)
13840       ast_uri_decode(c);
13841 
13842    if (!strncasecmp(c, "sip:", 4)) {
13843       c += 4;
13844    } else if (!strncasecmp(c, "sips:", 5)) {
13845       c += 5;
13846    } else {
13847       ast_log(LOG_WARNING, "Huh?  Not a SIP header in Also: transfer (%s)?\n", c);
13848       return -1;
13849    }
13850 
13851    if ((a = strchr(c, ';')))  /* Remove arguments */
13852       *a = '\0';
13853    
13854    if ((a = strchr(c, '@'))) {   /* Separate Domain */
13855       *a++ = '\0';
13856       ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
13857    }
13858    
13859    if (sip_debug_test_pvt(p))
13860       ast_verbose("Looking for %s in %s\n", c, p->context);
13861 
13862    if (p->owner)  /* Mimic behaviour in res_features.c */
13863       transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
13864 
13865    /* By default, use the context in the channel sending the REFER */
13866    if (ast_strlen_zero(transfer_context)) {
13867       transfer_context = S_OR(p->owner->macrocontext,
13868                S_OR(p->context, sip_cfg.default_context));
13869    }
13870    if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
13871       /* This is a blind transfer */
13872       ast_debug(1, "SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
13873       ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
13874       ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
13875       ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
13876       referdata->refer_call = dialog_unref(referdata->refer_call, "unreffing referdata->refer_call");
13877       /* Set new context */
13878       ast_string_field_set(p, context, transfer_context);
13879       return 0;
13880    } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
13881       return 1;
13882    }
13883 
13884    return -1;
13885 }
13886 
13887 /*! \brief check received= and rport= in a SIP response.
13888  * If we get a response with received= and/or rport= in the Via:
13889  * line, use them as 'p->ourip' (see RFC 3581 for rport,
13890  * and RFC 3261 for received).
13891  * Using these two fields SIP can produce the correct
13892  * address and port in the SIP headers without the need for STUN.
13893  * The address part is also reused for the media sessions.
13894  * Note that ast_sip_ouraddrfor() still rewrites p->ourip
13895  * if you specify externip/seternaddr/stunaddr.
13896  */
13897 static attribute_unused void check_via_response(struct sip_pvt *p, struct sip_request *req)
13898 {
13899    char via[256];
13900    char *cur, *opts;
13901 
13902    ast_copy_string(via, get_header(req, "Via"), sizeof(via));
13903 
13904    /* Work on the leftmost value of the topmost Via header */
13905    opts = strchr(via, ',');
13906    if (opts)
13907       *opts = '\0';
13908 
13909    /* parse all relevant options */
13910    opts = strchr(via, ';');
13911    if (!opts)
13912       return;  /* no options to parse */
13913    *opts++ = '\0';
13914    while ( (cur = strsep(&opts, ";")) ) {
13915       if (!strncmp(cur, "rport=", 6)) {
13916          int port = strtol(cur+6, NULL, 10);
13917          /* XXX add error checking */
13918          p->ourip.sin_port = ntohs(port);
13919       } else if (!strncmp(cur, "received=", 9)) {
13920          if (ast_parse_arg(cur+9, PARSE_INADDR, &p->ourip))
13921             ;  /* XXX add error checking */
13922       }
13923    }
13924 }
13925 
13926 /*! \brief check Via: header for hostname, port and rport request/answer */
13927 static void check_via(struct sip_pvt *p, struct sip_request *req)
13928 {
13929    char via[512];
13930    char *c, *pt, *maddr;
13931    struct hostent *hp;
13932    struct ast_hostent ahp;
13933 
13934    ast_copy_string(via, get_header(req, "Via"), sizeof(via));
13935 
13936    /* Work on the leftmost value of the topmost Via header */
13937    c = strchr(via, ',');
13938    if (c)
13939       *c = '\0';
13940 
13941    /* Check for rport */
13942    c = strstr(via, ";rport");
13943    if (c && (c[6] != '=')) /* rport query, not answer */
13944       ast_set_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT);
13945 
13946    /* Check for maddr */
13947    maddr = strstr(via, "maddr=");
13948    if (maddr) {
13949       maddr += 6;
13950       c = maddr + strspn(maddr, "0123456789.");
13951       *c = '\0';
13952    }
13953 
13954    c = strchr(via, ';');
13955    if (c)
13956       *c = '\0';
13957 
13958    c = strchr(via, ' ');
13959    if (c) {
13960       *c = '\0';
13961       c = ast_skip_blanks(c+1);
13962       if (strcasecmp(via, "SIP/2.0/UDP") && strcasecmp(via, "SIP/2.0/TCP") && strcasecmp(via, "SIP/2.0/TLS")) {
13963          ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
13964          return;
13965       }
13966       pt = strchr(c, ':');
13967       if (pt)
13968          *pt++ = '\0';  /* remember port pointer */
13969       /* Use maddr if found */
13970       if (maddr)
13971          c = maddr;
13972       hp = ast_gethostbyname(c, &ahp);
13973       if (!hp) {
13974          ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
13975          return;
13976       }
13977       memset(&p->sa, 0, sizeof(p->sa));
13978       p->sa.sin_family = AF_INET;
13979       memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
13980       p->sa.sin_port = htons(port_str2int(pt, STANDARD_SIP_PORT));
13981 
13982       if (sip_debug_test_pvt(p)) {
13983          const struct sockaddr_in *dst = sip_real_dst(p);
13984          ast_verbose("Sending to %s : %d (%s)\n", ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), sip_nat_mode(p));
13985       }
13986    }
13987 }
13988 
13989 /*! \brief  Get caller id name from SIP headers */
13990 static char *get_calleridname(const char *input, char *output, size_t outputsize)
13991 {
13992    const char *end = strchr(input, '<');  /* first_bracket */
13993    const char *tmp = strchr(input, '"');  /* first quote */
13994    int bytes = 0;
13995    int maxbytes = outputsize - 1;
13996 
13997    if (!end || end == input)  /* we require a part in brackets */
13998       return NULL;
13999 
14000    end--; /* move just before "<" */
14001 
14002    if (tmp && tmp <= end) {
14003       /* The quote (tmp) precedes the bracket (end+1).
14004        * Find the matching quote and return the content.
14005        */
14006       end = strchr(tmp+1, '"');
14007       if (!end)
14008          return NULL;
14009       bytes = (int) (end - tmp);
14010       /* protect the output buffer */
14011       if (bytes > maxbytes)
14012          bytes = maxbytes;
14013       ast_copy_string(output, tmp + 1, bytes);
14014    } else {
14015       /* No quoted string, or it is inside brackets. */
14016       /* clear the empty characters in the begining*/
14017       input = ast_skip_blanks(input);
14018       /* clear the empty characters in the end */
14019       while(*end && *end < 33 && end > input)
14020          end--;
14021       if (end >= input) {
14022          bytes = (int) (end - input) + 2;
14023          /* protect the output buffer */
14024          if (bytes > maxbytes)
14025             bytes = maxbytes;
14026          ast_copy_string(output, input, bytes);
14027       } else
14028          return NULL;
14029    }
14030    return output;
14031 }
14032 
14033 /*! \brief  Get caller id number from Remote-Party-ID header field 
14034  * Returns true if number should be restricted (privacy setting found)
14035  * output is set to NULL if no number found
14036  */
14037 static int get_rpid_num(const char *input, char *output, int maxlen)
14038 {
14039    char *start;
14040    char *end;
14041 
14042    start = strchr(input, ':');
14043    if (!start) {
14044       output[0] = '\0';
14045       return 0;
14046    }
14047    start++;
14048 
14049    /* we found "number" */
14050    ast_copy_string(output, start, maxlen);
14051    output[maxlen-1] = '\0';
14052 
14053    end = strchr(output, '@');
14054    if (end)
14055       *end = '\0';
14056    else
14057       output[0] = '\0';
14058    if (strstr(input, "privacy=full") || strstr(input, "privacy=uri"))
14059       return AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
14060 
14061    return 0;
14062 }
14063 
14064 
14065 /*! \brief helper function for check_{user|peer}_ok() */
14066 static void replace_cid(struct sip_pvt *p, const char *rpid_num, const char *calleridname)
14067 {
14068    /* replace callerid if rpid found, and not restricted */
14069    if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
14070       char *tmp = ast_strdupa(rpid_num); /* XXX the copy can be done later */
14071       if (!ast_strlen_zero(calleridname))
14072          ast_string_field_set(p, cid_name, calleridname);
14073       if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
14074          ast_shrink_phone_number(tmp);
14075       ast_string_field_set(p, cid_num, tmp);
14076    }
14077 }
14078 
14079 /*! \brief Validate device authentication */
14080 static enum check_auth_result check_peer_ok(struct sip_pvt *p, char *of,
14081    struct sip_request *req, int sipmethod, struct sockaddr_in *sin,
14082    struct sip_peer **authpeer,
14083    enum xmittype reliable,
14084    char *rpid_num, char *calleridname, char *uri2)
14085 {
14086    enum check_auth_result res;
14087    int debug=sip_debug_test_addr(sin);
14088    struct sip_peer *peer;
14089 
14090    if (sipmethod == SIP_SUBSCRIBE) {
14091       /* For subscribes, match on device name only; for other methods,
14092       * match on IP address-port of the incoming request.
14093       */
14094       peer = find_peer(of, NULL, TRUE, FINDALLDEVICES, FALSE, 0);
14095    } else {
14096       /* First find devices based on username (avoid all type=peer's) */
14097       peer = find_peer(of, NULL, TRUE, FINDUSERS, FALSE, 0);
14098 
14099       /* Then find devices based on IP */
14100       if (!peer) {
14101          peer = find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
14102       }
14103    }
14104 
14105    if (!peer) {
14106       if (debug)
14107          ast_verbose("No matching peer for '%s' from '%s:%d'\n",
14108             of, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
14109       return AUTH_DONT_KNOW;
14110    }
14111    if (!ast_apply_ha(peer->ha, sin)) {
14112       ast_debug(2, "Found peer '%s' for '%s', but fails host access\n", peer->name, of);
14113       unref_peer(peer, "unref_peer: check_peer_ok: from find_peer call, early return of AUTH_ACL_FAILED");
14114       return AUTH_ACL_FAILED;
14115    }
14116    if (debug)
14117       ast_verbose("Found peer '%s' for '%s' from %s:%d\n",
14118          peer->name, of, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
14119 
14120    /* XXX what about p->prefs = peer->prefs; ? */
14121    /* Set Frame packetization */
14122    if (p->rtp) {
14123       ast_rtp_codec_setpref(p->rtp, &peer->prefs);
14124       p->autoframing = peer->autoframing;
14125    }
14126 
14127    /* Take the peer */
14128    ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
14129    ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
14130 
14131    if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && p->udptl) {
14132       p->t38_maxdatagram = peer->t38_maxdatagram;
14133       set_t38_capabilities(p);
14134    }
14135 
14136    /* Copy SIP extensions profile to peer */
14137    /* XXX is this correct before a successful auth ? */
14138    if (p->sipoptions)
14139       peer->sipoptions = p->sipoptions;
14140 
14141    replace_cid(p, rpid_num, calleridname);
14142    do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE));
14143 
14144    ast_string_field_set(p, peersecret, peer->secret);
14145    ast_string_field_set(p, peermd5secret, peer->md5secret);
14146    ast_string_field_set(p, subscribecontext, peer->subscribecontext);
14147    ast_string_field_set(p, mohinterpret, peer->mohinterpret);
14148    ast_string_field_set(p, mohsuggest, peer->mohsuggest);
14149    ast_string_field_set(p, parkinglot, peer->parkinglot);
14150    if (peer->callingpres)  /* Peer calling pres setting will override RPID */
14151       p->callingpres = peer->callingpres;
14152    if (peer->maxms && peer->lastms)
14153       p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
14154    else
14155       p->timer_t1 = peer->timer_t1;
14156  
14157    /* Set timer B to control transaction timeouts */
14158    if (peer->timer_b)
14159       p->timer_b = peer->timer_b;
14160    else
14161       p->timer_b = 64 * p->timer_t1;
14162  
14163    if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
14164       /* Pretend there is no required authentication */
14165       ast_string_field_set(p, peersecret, NULL);
14166       ast_string_field_set(p, peermd5secret, NULL);
14167    }
14168    if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, req->ignore))) {
14169       ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
14170       ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
14171       /* If we have a call limit, set flag */
14172       if (peer->call_limit)
14173          ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
14174       ast_string_field_set(p, peername, peer->name);
14175       ast_string_field_set(p, authname, peer->name);
14176 
14177       if (sipmethod == SIP_INVITE) {
14178          /* copy channel vars */
14179          p->chanvars = copy_vars(peer->chanvars);
14180       }
14181 
14182       if (authpeer) {
14183          ao2_t_ref(peer, 1, "copy pointer into (*authpeer)");
14184          (*authpeer) = peer;  /* Add a ref to the object here, to keep it in memory a bit longer if it is realtime */
14185       }
14186 
14187       if (!ast_strlen_zero(peer->username)) {
14188          ast_string_field_set(p, username, peer->username);
14189          /* Use the default username for authentication on outbound calls */
14190          /* XXX this takes the name from the caller... can we override ? */
14191          ast_string_field_set(p, authname, peer->username);
14192       }
14193       if (!ast_strlen_zero(peer->cid_num)) {
14194          char *tmp = ast_strdupa(peer->cid_num);
14195          if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
14196             ast_shrink_phone_number(tmp);
14197          ast_string_field_set(p, cid_num, tmp);
14198       }
14199       if (!ast_strlen_zero(peer->cid_name)) 
14200          ast_string_field_set(p, cid_name, peer->cid_name);
14201       ast_string_field_set(p, fullcontact, peer->fullcontact);
14202       if (!ast_strlen_zero(peer->context))
14203          ast_string_field_set(p, context, peer->context);
14204       ast_string_field_set(p, peersecret, peer->secret);
14205       ast_string_field_set(p, peermd5secret, peer->md5secret);
14206       ast_string_field_set(p, language, peer->language);
14207       ast_string_field_set(p, accountcode, peer->accountcode);
14208       p->amaflags = peer->amaflags;
14209       p->callgroup = peer->callgroup;
14210       p->pickupgroup = peer->pickupgroup;
14211       p->capability = peer->capability;
14212       p->prefs = peer->prefs;
14213       p->jointcapability = peer->capability;
14214       if (p->peercapability)
14215          p->jointcapability &= p->peercapability;
14216       p->maxcallbitrate = peer->maxcallbitrate;
14217       if (!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) &&
14218             (!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
14219                !(p->capability & AST_FORMAT_VIDEO_MASK)) &&
14220             p->vrtp) {
14221          ast_rtp_destroy(p->vrtp);
14222          p->vrtp = NULL;
14223       }
14224       if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) || !(p->capability & AST_FORMAT_TEXT_MASK)) && p->trtp) {
14225          ast_rtp_destroy(p->trtp);
14226          p->trtp = NULL;
14227       }
14228       if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
14229           (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
14230          p->noncodeccapability |= AST_RTP_DTMF;
14231       else
14232          p->noncodeccapability &= ~AST_RTP_DTMF;
14233       p->jointnoncodeccapability = p->noncodeccapability;
14234    }
14235    unref_peer(peer, "check_peer_ok: unref_peer: tossing temp ptr to peer from find_peer");
14236    return res;
14237 }
14238 
14239 
14240 /*! \brief  Check if matching user or peer is defined 
14241    Match user on From: user name and peer on IP/port
14242    This is used on first invite (not re-invites) and subscribe requests 
14243     \return 0 on success, non-zero on failure
14244 */
14245 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
14246                      int sipmethod, char *uri, enum xmittype reliable,
14247                      struct sockaddr_in *sin, struct sip_peer **authpeer)
14248 {
14249    char from[256];
14250    char *dummy;   /* dummy return value for parse_uri */
14251    char *domain;  /* dummy return value for parse_uri */
14252    char *of;
14253    char rpid_num[50];
14254    const char *rpid;
14255    enum check_auth_result res;
14256    char calleridname[50];
14257    char *uri2 = ast_strdupa(uri);
14258 
14259    terminate_uri(uri2); /* trim extra stuff */
14260 
14261    ast_copy_string(from, get_header(req, "From"), sizeof(from));
14262    if (sip_cfg.pedanticsipchecking)
14263       ast_uri_decode(from);
14264    /* XXX here tries to map the username for invite things */
14265    memset(calleridname, 0, sizeof(calleridname));
14266    get_calleridname(from, calleridname, sizeof(calleridname));
14267    if (calleridname[0])
14268       ast_string_field_set(p, cid_name, calleridname);
14269 
14270    rpid = get_header(req, "Remote-Party-ID");
14271    memset(rpid_num, 0, sizeof(rpid_num));
14272    if (!ast_strlen_zero(rpid)) 
14273       p->callingpres = get_rpid_num(rpid, rpid_num, sizeof(rpid_num));
14274 
14275    of = get_in_brackets(from);
14276    if (ast_strlen_zero(p->exten)) {
14277       char *t = uri2;
14278       if (!strncasecmp(t, "sip:", 4))
14279          t+= 4;
14280       else if (!strncasecmp(t, "sips:", 5))
14281          t += 5;
14282       ast_string_field_set(p, exten, t);
14283       t = strchr(p->exten, '@');
14284       if (t)
14285          *t = '\0';
14286       if (ast_strlen_zero(p->our_contact))
14287          build_contact(p);
14288    }
14289    /* save the URI part of the From header */
14290    ast_string_field_set(p, from, of);
14291 
14292    /* ignore all fields but name */
14293    if (parse_uri(of, "sip:,sips:", &of, &dummy, &domain, &dummy, &dummy, NULL)) {
14294       ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
14295    }
14296 
14297    if (ast_strlen_zero(of)) {
14298       /* XXX note: the original code considered a missing @host
14299        * as a username-only URI. The SIP RFC (19.1.1) says that
14300        * this is wrong, and it should be considered as a domain-only URI.
14301        * For backward compatibility, we keep this block, but it is
14302        * really a mistake and should go away.
14303        */
14304       of = domain;
14305    } else {
14306       char *tmp = ast_strdupa(of);
14307       /* We need to be able to handle auth-headers looking like
14308          <sip:8164444422;phone-context=+1@1.2.3.4:5060;user=phone;tag=SDadkoa01-gK0c3bdb43>
14309       */
14310       tmp = strsep(&tmp, ";");
14311       if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
14312          ast_shrink_phone_number(tmp);
14313       ast_string_field_set(p, cid_num, tmp);
14314    }
14315 
14316    if (global_match_auth_username) {
14317       /*
14318        * XXX This is experimental code to grab the search key from the
14319        * Auth header's username instead of the 'From' name, if available.
14320        * Do not enable this block unless you understand the side effects (if any!)
14321        * Note, the search for "username" should be done in a more robust way.
14322        * Note2, at the moment we check both fields, though maybe we should
14323        * pick one or another depending on the request ? XXX
14324        */
14325       const char *hdr = get_header(req, "Authorization");
14326       if (ast_strlen_zero(hdr))
14327          hdr = get_header(req, "Proxy-Authorization");
14328 
14329       if ( !ast_strlen_zero(hdr) && (hdr = strstr(hdr, "username=\"")) ) {
14330          ast_copy_string(from, hdr + strlen("username=\""), sizeof(from));
14331          of = from;
14332          of = strsep(&of, "\"");
14333       }
14334    }
14335 
14336    res = check_peer_ok(p, of, req, sipmethod, sin,
14337          authpeer, reliable, rpid_num, calleridname, uri2);
14338    if (res != AUTH_DONT_KNOW)
14339       return res;
14340 
14341    /* Finally, apply the guest policy */
14342    if (sip_cfg.allowguest) {
14343       replace_cid(p, rpid_num, calleridname);
14344       res = AUTH_SUCCESSFUL;
14345    } else if (sip_cfg.alwaysauthreject)
14346       res = AUTH_FAKE_AUTH; /* reject with fake authorization request */
14347    else
14348       res = AUTH_SECRET_FAILED; /* we don't want any guests, authentication will fail */
14349 
14350 
14351    if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT)) {
14352       ast_set_flag(&p->flags[0], SIP_NAT_ROUTE);
14353    }
14354 
14355    return res;
14356 }
14357 
14358 /*! \brief  Find user 
14359    If we get a match, this will add a reference pointer to the user object in ASTOBJ, that needs to be unreferenced
14360 */
14361 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin)
14362 {
14363    return check_user_full(p, req, sipmethod, uri, reliable, sin, NULL);
14364 }
14365 
14366 /*! \brief  Get text out of a SIP MESSAGE packet */
14367 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline)
14368 {
14369    int x;
14370    int y;
14371 
14372    buf[0] = '\0';
14373    /*XXX isn't strlen(buf) going to always be 0? */
14374    y = len - strlen(buf) - 5;
14375    if (y < 0)
14376       y = 0;
14377    for (x = 0; x < req->lines; x++) {
14378       char *line = REQ_OFFSET_TO_STR(req, line[x]);
14379       strncat(buf, line, y); /* safe */
14380       y -= strlen(line) + 1;
14381       if (y < 0)
14382          y = 0;
14383       if (y != 0 && addnewline)
14384          strcat(buf, "\n"); /* safe */
14385    }
14386    return 0;
14387 }
14388 
14389 
14390 /*! \brief  Receive SIP MESSAGE method messages
14391 \note We only handle messages within current calls currently 
14392    Reference: RFC 3428 */
14393 static void receive_message(struct sip_pvt *p, struct sip_request *req)
14394 {
14395    char buf[1400];   
14396    struct ast_frame f;
14397    const char *content_type = get_header(req, "Content-Type");
14398 
14399    if (strncmp(content_type, "text/plain", strlen("text/plain"))) { /* No text/plain attachment */
14400       transmit_response(p, "415 Unsupported Media Type", req); /* Good enough, or? */
14401       if (!p->owner)
14402          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14403       return;
14404    }
14405 
14406    if (get_msg_text(buf, sizeof(buf), req, FALSE)) {
14407       ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
14408       transmit_response(p, "202 Accepted", req);
14409       if (!p->owner)
14410          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14411       return;
14412    }
14413 
14414    if (p->owner) {
14415       if (sip_debug_test_pvt(p))
14416          ast_verbose("SIP Text message received: '%s'\n", buf);
14417       memset(&f, 0, sizeof(f));
14418       f.frametype = AST_FRAME_TEXT;
14419       f.subclass = 0;
14420       f.offset = 0;
14421       f.data.ptr = buf;
14422       f.datalen = strlen(buf);
14423       ast_queue_frame(p->owner, &f);
14424       transmit_response(p, "202 Accepted", req); /* We respond 202 accepted, since we relay the message */
14425       return;
14426    }
14427 
14428    /* Message outside of a call, we do not support that */
14429    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);
14430    transmit_response(p, "405 Method Not Allowed", req);
14431    sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14432    return;
14433 }
14434 
14435 /*! \brief  CLI Command to show calls within limits set by call_limit */
14436 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14437 {
14438 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
14439 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
14440    char ilimits[40];
14441    char iused[40];
14442    int showall = FALSE;
14443    struct ao2_iterator i;
14444    struct sip_peer *peer;
14445    
14446    switch (cmd) {
14447    case CLI_INIT:
14448       e->command = "sip show inuse";
14449       e->usage =
14450          "Usage: sip show inuse [all]\n"
14451          "       List all SIP devices usage counters and limits.\n"
14452          "       Add option \"all\" to show all devices, not only those with a limit.\n";
14453       return NULL;
14454    case CLI_GENERATE:
14455       return NULL;
14456    }
14457 
14458    if (a->argc < 3) 
14459       return CLI_SHOWUSAGE;
14460 
14461    if (a->argc == 4 && !strcmp(a->argv[3], "all")) 
14462       showall = TRUE;
14463    
14464    ast_cli(a->fd, FORMAT, "* Peer name", "In use", "Limit");
14465 
14466    i = ao2_iterator_init(peers, 0);
14467    while ((peer = ao2_t_iterator_next(&i, "iterate thru peer table"))) {
14468       ao2_lock(peer);
14469       if (peer->call_limit)
14470          snprintf(ilimits, sizeof(ilimits), "%d", peer->call_limit);
14471       else 
14472          ast_copy_string(ilimits, "N/A", sizeof(ilimits));
14473       snprintf(iused, sizeof(iused), "%d/%d/%d", peer->inUse, peer->inRinging, peer->onHold);
14474       if (showall || peer->call_limit)
14475          ast_cli(a->fd, FORMAT2, peer->name, iused, ilimits);
14476       ao2_unlock(peer);
14477       unref_peer(peer, "toss iterator pointer");
14478    }
14479    ao2_iterator_destroy(&i);
14480 
14481    return CLI_SUCCESS;
14482 #undef FORMAT
14483 #undef FORMAT2
14484 }
14485 
14486 
14487 /*! \brief Convert transfer mode to text string */
14488 static char *transfermode2str(enum transfermodes mode)
14489 {
14490    if (mode == TRANSFER_OPENFORALL)
14491       return "open";
14492    else if (mode == TRANSFER_CLOSED)
14493       return "closed";
14494    return "strict";
14495 }
14496 
14497 static struct _map_x_s natmodes[] = {
14498    { SIP_NAT_NEVER,        "No"},
14499    { SIP_NAT_ROUTE,        "Route"},
14500    { SIP_NAT_ALWAYS,       "Always"},
14501    { SIP_NAT_RFC3581,      "RFC3581"},
14502    { -1,                   NULL}, /* terminator */
14503 };
14504 
14505 /*! \brief  Convert NAT setting to text string */
14506 static const char *nat2str(int nat)
14507 {
14508    return map_x_s(natmodes, nat, "Unknown");
14509 }
14510 
14511 #ifdef NOTUSED
14512 /* OEJ: This is not used, but may be useful in the future, so I don't want to 
14513    delete it. Keeping it enabled generates compiler warnings.
14514  */
14515 
14516 static struct _map_x_s natcfgmodes[] = {
14517    { SIP_NAT_NEVER,        "never"},
14518    { SIP_NAT_ROUTE,        "route"},
14519    { SIP_NAT_ALWAYS,       "yes"},
14520    { SIP_NAT_RFC3581,      "no"},
14521    { -1,                   NULL}, /* terminator */
14522 };
14523 
14524 /*! \brief  Convert NAT setting to text string appropriate for config files */
14525 static const char *nat2strconfig(int nat)
14526 {
14527    return map_x_s(natcfgmodes, nat, "Unknown");
14528 }
14529 #endif
14530 
14531 /*! \brief  Report Peer status in character string
14532  *  \return 0 if peer is unreachable, 1 if peer is online, -1 if unmonitored
14533  */
14534 
14535 
14536 /* Session-Timer Modes */
14537 static struct _map_x_s stmodes[] = {
14538         { SESSION_TIMER_MODE_ACCEPT,    "Accept"},
14539         { SESSION_TIMER_MODE_ORIGINATE, "Originate"},
14540         { SESSION_TIMER_MODE_REFUSE,    "Refuse"},
14541         { -1,                           NULL},
14542 };
14543 
14544 static const char *stmode2str(enum st_mode m)
14545 {
14546    return map_x_s(stmodes, m, "Unknown");
14547 }
14548 
14549 static enum st_mode str2stmode(const char *s)
14550 {
14551    return map_s_x(stmodes, s, -1);
14552 }
14553 
14554 /* Session-Timer Refreshers */
14555 static struct _map_x_s strefreshers[] = {
14556         { SESSION_TIMER_REFRESHER_AUTO,     "auto"},
14557         { SESSION_TIMER_REFRESHER_UAC,      "uac"},
14558         { SESSION_TIMER_REFRESHER_UAS,      "uas"},
14559         { -1,                               NULL},
14560 };
14561 
14562 static const char *strefresher2str(enum st_refresher r)
14563 {
14564    return map_x_s(strefreshers, r, "Unknown");
14565 }
14566 
14567 static enum st_refresher str2strefresher(const char *s)
14568 {
14569    return map_s_x(strefreshers, s, -1);
14570 }
14571 
14572 
14573 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
14574 {
14575    int res = 0;
14576    if (peer->maxms) {
14577       if (peer->lastms < 0) {
14578          ast_copy_string(status, "UNREACHABLE", statuslen);
14579       } else if (peer->lastms > peer->maxms) {
14580          snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
14581          res = 1;
14582       } else if (peer->lastms) {
14583          snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
14584          res = 1;
14585       } else {
14586          ast_copy_string(status, "UNKNOWN", statuslen);
14587       }
14588    } else { 
14589       ast_copy_string(status, "Unmonitored", statuslen);
14590       /* Checking if port is 0 */
14591       res = -1;
14592    }
14593    return res;
14594 }
14595 
14596 /*! \brief return Yes or No depending on the argument.
14597  * This is used in many places in CLI command, having a function to generate
14598  * this helps maintaining a consistent output (and possibly emitting the
14599  * output in other languages, at some point).
14600  */
14601 static const char *cli_yesno(int x)
14602 {
14603    return x ? "Yes" : "No";
14604 }
14605 
14606 /*! \brief  Show active TCP connections */
14607 static char *sip_show_tcp(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14608 {
14609    struct sip_threadinfo *th;
14610    struct ao2_iterator i;
14611 
14612 #define FORMAT2 "%-30.30s %3.6s %9.9s %6.6s\n"
14613 #define FORMAT  "%-30.30s %-6d %-9.9s %-6.6s\n"
14614 
14615    switch (cmd) {
14616    case CLI_INIT:
14617       e->command = "sip show tcp";
14618       e->usage =
14619          "Usage: sip show tcp\n"
14620          "       Lists all active TCP/TLS sessions.\n";
14621       return NULL;
14622    case CLI_GENERATE:
14623       return NULL;
14624    }
14625 
14626    if (a->argc != 3)
14627       return CLI_SHOWUSAGE;
14628 
14629    ast_cli(a->fd, FORMAT2, "Host", "Port", "Transport", "Type");
14630    i = ao2_iterator_init(threadt, 0);
14631    while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
14632       ast_cli(a->fd, FORMAT, ast_inet_ntoa(th->tcptls_session->remote_address.sin_addr), 
14633          ntohs(th->tcptls_session->remote_address.sin_port), 
14634          get_transport(th->type), 
14635          (th->tcptls_session->client ? "Client" : "Server"));
14636       ao2_t_ref(th, -1, "decrement ref from iterator");
14637    }
14638    ao2_iterator_destroy(&i);
14639    return CLI_SUCCESS;
14640 #undef FORMAT
14641 #undef FORMAT2
14642 }
14643 
14644 /*! \brief  CLI Command 'SIP Show Users' */
14645 static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14646 {
14647    regex_t regexbuf;
14648    int havepattern = FALSE;
14649    struct ao2_iterator user_iter;
14650    struct sip_peer *user;
14651 
14652 #define FORMAT  "%-25.25s  %-15.15s  %-15.15s  %-15.15s  %-5.5s%-10.10s\n"
14653 
14654    switch (cmd) {
14655    case CLI_INIT:
14656       e->command = "sip show users";
14657       e->usage =
14658          "Usage: sip show users [like <pattern>]\n"
14659          "       Lists all known SIP users.\n"
14660          "       Optional regular expression pattern is used to filter the user list.\n";
14661       return NULL;
14662    case CLI_GENERATE:
14663       return NULL;
14664    }
14665 
14666    switch (a->argc) {
14667    case 5:
14668       if (!strcasecmp(a->argv[3], "like")) {
14669          if (regcomp(&regexbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
14670             return CLI_SHOWUSAGE;
14671          havepattern = TRUE;
14672       } else
14673          return CLI_SHOWUSAGE;
14674    case 3:
14675       break;
14676    default:
14677       return CLI_SHOWUSAGE;
14678    }
14679 
14680    ast_cli(a->fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "NAT");
14681 
14682    user_iter = ao2_iterator_init(peers, 0);
14683    while ((user = ao2_iterator_next(&user_iter))) {
14684       ao2_lock(user);
14685       if (!(user->type & SIP_TYPE_USER)) {
14686          ao2_unlock(user);
14687          unref_peer(user, "sip show users");
14688          continue;
14689       }
14690 
14691       if (havepattern && regexec(&regexbuf, user->name, 0, NULL, 0)) {
14692          ao2_unlock(user);
14693          unref_peer(user, "sip show users");
14694          continue;
14695       }
14696 
14697       ast_cli(a->fd, FORMAT, user->name, 
14698          user->secret, 
14699          user->accountcode,
14700          user->context,
14701          cli_yesno(user->ha != NULL),
14702          nat2str(ast_test_flag(&user->flags[0], SIP_NAT)));
14703       ao2_unlock(user);
14704       unref_peer(user, "sip show users");
14705    }
14706    ao2_iterator_destroy(&user_iter);
14707 
14708    if (havepattern)
14709       regfree(&regexbuf);
14710 
14711    return CLI_SUCCESS;
14712 #undef FORMAT
14713 }
14714 
14715 /*! \brief Manager Action SIPShowRegistry description */
14716 static char mandescr_show_registry[] =
14717 "Description: Lists all registration requests and status\n"
14718 "Registrations will follow as separate events. followed by a final event called\n"
14719 "RegistrationsComplete.\n"
14720 "Variables: \n"
14721 "  ActionID: <id>       Action ID for this transaction. Will be returned.\n";
14722 
14723 /*! \brief Show SIP registrations in the manager API */
14724 static int manager_show_registry(struct mansession *s, const struct message *m)
14725 {
14726    const char *id = astman_get_header(m, "ActionID");
14727    char idtext[256] = "";
14728    int total = 0;
14729 
14730    if (!ast_strlen_zero(id))
14731       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
14732 
14733    astman_send_listack(s, m, "Registrations will follow", "start");
14734 
14735    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
14736       ASTOBJ_RDLOCK(iterator);
14737       astman_append(s,
14738          "Event: RegistryEntry\r\n"
14739          "%s"
14740          "Host: %s\r\n"
14741          "Port: %d\r\n"
14742          "Username: %s\r\n"
14743          "Refresh: %d\r\n"
14744          "State: %s\r\n"
14745          "RegistrationTime: %ld\r\n"
14746          "\r\n", idtext, iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT,
14747                  iterator->username, iterator->refresh, regstate2str(iterator->regstate), (long) iterator->regtime.tv_sec);
14748       ASTOBJ_UNLOCK(iterator);
14749       total++;
14750    } while(0));
14751 
14752    astman_append(s,
14753       "Event: RegistrationsComplete\r\n"
14754       "EventList: Complete\r\n"
14755       "ListItems: %d\r\n"
14756       "%s"
14757       "\r\n", total, idtext);
14758    
14759    return 0;
14760 }
14761 
14762 static char mandescr_show_peers[] = 
14763 "Description: Lists SIP peers in text format with details on current status.\n"
14764 "Peerlist will follow as separate events, followed by a final event called\n"
14765 "PeerlistComplete.\n"
14766 "Variables: \n"
14767 "  ActionID: <id> Action ID for this transaction. Will be returned.\n";
14768 
14769 /*! \brief  Show SIP peers in the manager API */
14770 /*    Inspired from chan_iax2 */
14771 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
14772 {
14773    const char *id = astman_get_header(m, "ActionID");
14774    const char *a[] = {"sip", "show", "peers"};
14775    char idtext[256] = "";
14776    int total = 0;
14777 
14778    if (!ast_strlen_zero(id))
14779       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
14780 
14781    astman_send_listack(s, m, "Peer status list will follow", "start");
14782    /* List the peers in separate manager events */
14783    _sip_show_peers(-1, &total, s, m, 3, a);
14784    /* Send final confirmation */
14785    astman_append(s,
14786    "Event: PeerlistComplete\r\n"
14787    "EventList: Complete\r\n"
14788    "ListItems: %d\r\n"
14789    "%s"
14790    "\r\n", total, idtext);
14791    return 0;
14792 }
14793 
14794 /*! \brief  CLI Show Peers command */
14795 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14796 {
14797    switch (cmd) {
14798    case CLI_INIT:
14799       e->command = "sip show peers";
14800       e->usage =
14801          "Usage: sip show peers [like <pattern>]\n"
14802          "       Lists all known SIP peers.\n"
14803          "       Optional regular expression pattern is used to filter the peer list.\n";
14804       return NULL;
14805    case CLI_GENERATE:
14806       return NULL;
14807    }
14808 
14809    return _sip_show_peers(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
14810 }
14811 
14812 int peercomparefunc(const void *a, const void *b);
14813 
14814 int peercomparefunc(const void *a, const void *b)
14815 {
14816    struct sip_peer **ap = (struct sip_peer **)a;
14817    struct sip_peer **bp = (struct sip_peer **)b;
14818    return strcmp((*ap)->name, (*bp)->name);
14819 }
14820 
14821 
14822 /*! \brief Execute sip show peers command */
14823 static char *_sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
14824 {
14825    regex_t regexbuf;
14826    int havepattern = FALSE;
14827    struct sip_peer *peer;
14828    struct ao2_iterator i;
14829    
14830 /* the last argument is left-aligned, so we don't need a size anyways */
14831 #define FORMAT2 "%-25.25s  %-15.15s %-3.3s %-3.3s %-3.3s %-8s %-10s %s\n"
14832 #define FORMAT  "%-25.25s  %-15.15s %-3.3s %-3.3s %-3.3s %-8d %-10s %s\n"
14833 
14834    char name[256];
14835    int total_peers = 0;
14836    int peers_mon_online = 0;
14837    int peers_mon_offline = 0;
14838    int peers_unmon_offline = 0;
14839    int peers_unmon_online = 0;
14840    const char *id;
14841    char idtext[256] = "";
14842    int realtimepeers;
14843    int objcount = ao2_container_count(peers);
14844    struct sip_peer **peerarray;
14845    int k;
14846    
14847    
14848    realtimepeers = ast_check_realtime("sippeers");
14849    peerarray = ast_calloc(sizeof(struct sip_peer *), objcount);
14850 
14851    if (s) { /* Manager - get ActionID */
14852       id = astman_get_header(m, "ActionID");
14853       if (!ast_strlen_zero(id))
14854          snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
14855    }
14856 
14857    switch (argc) {
14858    case 5:
14859       if (!strcasecmp(argv[3], "like")) {
14860          if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
14861             return CLI_SHOWUSAGE;
14862          havepattern = TRUE;
14863       } else
14864          return CLI_SHOWUSAGE;
14865    case 3:
14866       break;
14867    default:
14868       return CLI_SHOWUSAGE;
14869    }
14870 
14871    if (!s) /* Normal list */
14872       ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Nat", "ACL", "Port", "Status", (realtimepeers ? "Realtime" : ""));
14873    
14874 
14875    i = ao2_iterator_init(peers, 0);
14876    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {  
14877       ao2_lock(peer);
14878 
14879       if (!(peer->type & SIP_TYPE_PEER)) {
14880          ao2_unlock(peer);
14881          unref_peer(peer, "unref peer because it's actually a user");
14882          continue;
14883       }
14884 
14885       if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0)) {
14886          objcount--;
14887          ao2_unlock(peer);
14888          unref_peer(peer, "toss iterator peer ptr before continue");
14889          continue;
14890       }
14891 
14892       peerarray[total_peers++] = peer;
14893       ao2_unlock(peer);
14894    }
14895    ao2_iterator_destroy(&i);
14896    
14897    qsort(peerarray, total_peers, sizeof(struct sip_peer *), peercomparefunc);
14898 
14899    for(k=0; k < total_peers; k++) {
14900       char status[20] = "";
14901       char srch[2000];
14902       char pstatus;
14903       peer = peerarray[k];
14904       
14905       ao2_lock(peer);
14906       if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0)) {
14907          ao2_unlock(peer);
14908          unref_peer(peer, "toss iterator peer ptr before continue");
14909          continue;
14910       }
14911 
14912       if (!ast_strlen_zero(peer->username) && !s)
14913          snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
14914       else
14915          ast_copy_string(name, peer->name, sizeof(name));
14916       
14917       pstatus = peer_status(peer, status, sizeof(status));
14918       if (pstatus == 1)
14919          peers_mon_online++;
14920       else if (pstatus == 0)
14921          peers_mon_offline++;
14922       else {
14923          if (peer->addr.sin_port == 0)
14924             peers_unmon_offline++;
14925          else
14926             peers_unmon_online++;
14927       }
14928 
14929       snprintf(srch, sizeof(srch), FORMAT, name,
14930          peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
14931          peer->host_dynamic ? " D " : "   ",    /* Dynamic or not? */
14932          ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? " N " : "   ", /* NAT=yes? */
14933          peer->ha ? " A " : "   ",  /* permit/deny */
14934          ntohs(peer->addr.sin_port), status,
14935          realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
14936 
14937       if (!s)  {/* Normal CLI list */
14938          ast_cli(fd, FORMAT, name, 
14939          peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
14940          peer->host_dynamic ? " D " : "   ",    /* Dynamic or not? */
14941          ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? " N " : "   ", /* NAT=yes? */
14942          peer->ha ? " A " : "   ",       /* permit/deny */
14943          
14944          ntohs(peer->addr.sin_port), status,
14945          realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
14946       } else { /* Manager format */
14947          /* The names here need to be the same as other channels */
14948          astman_append(s, 
14949          "Event: PeerEntry\r\n%s"
14950          "Channeltype: SIP\r\n"
14951          "ObjectName: %s\r\n"
14952          "ChanObjectType: peer\r\n" /* "peer" or "user" */
14953          "IPaddress: %s\r\n"
14954          "IPport: %d\r\n"
14955          "Dynamic: %s\r\n"
14956          "Natsupport: %s\r\n"
14957          "VideoSupport: %s\r\n"
14958          "TextSupport: %s\r\n"
14959          "ACL: %s\r\n"
14960          "Status: %s\r\n"
14961          "RealtimeDevice: %s\r\n\r\n", 
14962          idtext,
14963          peer->name, 
14964          peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "-none-",
14965          ntohs(peer->addr.sin_port), 
14966          peer->host_dynamic ? "yes" : "no",  /* Dynamic or not? */
14967          ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? "yes" : "no",  /* NAT=yes? */
14968          ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no",  /* VIDEOSUPPORT=yes? */
14969          ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "yes" : "no",   /* TEXTSUPPORT=yes? */
14970          peer->ha ? "yes" : "no",       /* permit/deny */
14971          status,
14972          realtimepeers ? (peer->is_realtime ? "yes":"no") : "no");
14973       }
14974       ao2_unlock(peer);
14975       unref_peer(peer, "toss iterator peer ptr");
14976    }
14977    
14978    if (!s)
14979       ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
14980               total_peers, peers_mon_online, peers_mon_offline, peers_unmon_online, peers_unmon_offline);
14981 
14982    if (havepattern)
14983       regfree(&regexbuf);
14984 
14985    if (total)
14986       *total = total_peers;
14987    
14988    ast_free(peerarray);
14989    
14990    return CLI_SUCCESS;
14991 #undef FORMAT
14992 #undef FORMAT2
14993 }
14994 
14995 static int peer_dump_func(void *userobj, void *arg, int flags)
14996 {
14997    struct sip_peer *peer = userobj;
14998    int refc = ao2_t_ref(userobj, 0, "");
14999    int *fd = arg;
15000    
15001    ast_cli(*fd, "name: %s\ntype: peer\nobjflags: %d\nrefcount: %d\n\n", 
15002           peer->name, 0, refc);
15003    return 0;
15004 }
15005 
15006 static int dialog_dump_func(void *userobj, void *arg, int flags)
15007 {
15008    struct sip_pvt *pvt = userobj;
15009    int refc = ao2_t_ref(userobj, 0, "");
15010    int *fd = arg;
15011    
15012    ast_cli(*fd, "name: %s\ntype: dialog\nobjflags: %d\nrefcount: %d\n\n", 
15013           pvt->callid, 0, refc);
15014    return 0;
15015 }
15016 
15017 
15018 /*! \brief List all allocated SIP Objects (realtime or static) */
15019 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15020 {
15021    char tmp[256];
15022    
15023    switch (cmd) {
15024    case CLI_INIT:
15025       e->command = "sip show objects";
15026       e->usage =
15027          "Usage: sip show objects\n"
15028          "       Lists status of known SIP objects\n";
15029       return NULL;
15030    case CLI_GENERATE:
15031       return NULL;
15032    }  
15033 
15034    if (a->argc != 3)
15035       return CLI_SHOWUSAGE;
15036    ast_cli(a->fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
15037    ao2_t_callback(peers, OBJ_NODATA, peer_dump_func, &a->fd, "initiate ao2_callback to dump peers");
15038    ast_cli(a->fd, "-= Registry objects: %d =-\n\n", regobjs);
15039    ASTOBJ_CONTAINER_DUMP(a->fd, tmp, sizeof(tmp), &regl);
15040    ast_cli(a->fd, "-= Dialog objects:\n\n");
15041    ao2_t_callback(dialogs, OBJ_NODATA, dialog_dump_func, &a->fd, "initiate ao2_callback to dump dialogs");
15042    return CLI_SUCCESS;
15043 }
15044 /*! \brief Print call group and pickup group */
15045 static void  print_group(int fd, ast_group_t group, int crlf)
15046 {
15047    char buf[256];
15048    ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
15049 }
15050 
15051 /*! \brief mapping between dtmf flags and strings */
15052 static struct _map_x_s dtmfstr[] = {
15053    { SIP_DTMF_RFC2833,     "rfc2833" },
15054    { SIP_DTMF_INFO,        "info" },
15055    { SIP_DTMF_SHORTINFO,   "shortinfo" },
15056    { SIP_DTMF_INBAND,      "inband" },
15057    { SIP_DTMF_AUTO,        "auto" },
15058    { -1,                   NULL }, /* terminator */
15059 };
15060 
15061 /*! \brief Convert DTMF mode to printable string */
15062 static const char *dtmfmode2str(int mode)
15063 {
15064    return map_x_s(dtmfstr, mode, "<error>");
15065 }
15066 
15067 /*! \brief maps a string to dtmfmode, returns -1 on error */
15068 static int str2dtmfmode(const char *str)
15069 {
15070    return map_s_x(dtmfstr, str, -1);
15071 }
15072 
15073 static struct _map_x_s insecurestr[] = {
15074    { SIP_INSECURE_PORT,    "port" },
15075    { SIP_INSECURE_INVITE,  "invite" },
15076    { SIP_INSECURE_PORT | SIP_INSECURE_INVITE, "port,invite" },
15077    { 0,                    "no" },
15078    { -1,                   NULL }, /* terminator */
15079 };
15080 
15081 /*! \brief Convert Insecure setting to printable string */
15082 static const char *insecure2str(int mode)
15083 {
15084    return map_x_s(insecurestr, mode, "<error>");
15085 }
15086 
15087 /*! \brief Destroy disused contexts between reloads
15088    Only used in reload_config so the code for regcontext doesn't get ugly
15089 */
15090 static void cleanup_stale_contexts(char *new, char *old)
15091 {
15092    char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
15093 
15094    while ((oldcontext = strsep(&old, "&"))) {
15095       stalecontext = '\0';
15096       ast_copy_string(newlist, new, sizeof(newlist));
15097       stringp = newlist;
15098       while ((newcontext = strsep(&stringp, "&"))) {
15099          if (!strcmp(newcontext, oldcontext)) {
15100             /* This is not the context you're looking for */
15101             stalecontext = '\0';
15102             break;
15103          } else if (strcmp(newcontext, oldcontext)) {
15104             stalecontext = oldcontext;
15105          }
15106          
15107       }
15108       if (stalecontext)
15109          ast_context_destroy(ast_context_find(stalecontext), "SIP");
15110    }
15111 }
15112 
15113 /*! 
15114  * \brief Match dialogs that need to be destroyed
15115  *
15116  * \details This is used with ao2_callback to unlink/delete all dialogs that
15117  * are marked needdestroy. It will return CMP_MATCH for candidates, and they
15118  * will be unlinked.
15119  *
15120  * \todo Re-work this to improve efficiency.  Currently, this function is called
15121  * on _every_ dialog after processing _every_ incoming SIP/UDP packet, or
15122  * potentially even more often when the scheduler has entries to run.
15123  */
15124 
15125 static int dialog_needdestroy(void *dialogobj, void *arg, int flags) 
15126 {
15127    struct sip_pvt *dialog = dialogobj;
15128    time_t *t = arg;
15129 
15130    if (sip_pvt_trylock(dialog)) {
15131       /* Don't block the monitor thread.  This function is called often enough
15132        * that we can wait for the next time around. */
15133       return 0;
15134    }
15135    
15136    /* Check RTP timeouts and kill calls if we have a timeout set and do not get RTP */
15137    check_rtp_timeout(dialog, *t);
15138 
15139    /* If we have sessions that needs to be destroyed, do it now */
15140    /* Check if we have outstanding requests not responsed to or an active call
15141       - if that's the case, wait with destruction */
15142    if (dialog->needdestroy && !dialog->packets && !dialog->owner) {
15143       /* We absolutely cannot destroy the rtp struct while a bridge is active or we WILL crash */
15144       if (dialog->rtp && ast_rtp_get_bridged(dialog->rtp)) {
15145          ast_debug(2, "Bridge still active.  Delaying destruction of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
15146          sip_pvt_unlock(dialog);
15147          return 0;
15148       }
15149       
15150       if (dialog->vrtp && ast_rtp_get_bridged(dialog->vrtp)) {
15151          ast_debug(2, "Bridge still active.  Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
15152          sip_pvt_unlock(dialog);
15153          return 0;
15154       }
15155 
15156       sip_pvt_unlock(dialog);
15157       /* no, the unlink should handle this: dialog_unref(dialog, "needdestroy: one more refcount decrement to allow dialog to be destroyed"); */
15158       /* the CMP_MATCH will unlink this dialog from the dialog hash table */
15159       dialog_unlink_all(dialog, TRUE, FALSE);
15160       return 0; /* the unlink_all should unlink this from the table, so.... no need to return a match */
15161    }
15162 
15163    sip_pvt_unlock(dialog);
15164 
15165    return 0;
15166 }
15167 
15168 /*! \brief Remove temporary realtime objects from memory (CLI) */
15169 /*! \todo XXXX Propably needs an overhaul after removal of the devices */
15170 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15171 {
15172    struct sip_peer *peer, *pi;
15173    int prunepeer = FALSE;
15174    int multi = FALSE;
15175    char *name = NULL;
15176    regex_t regexbuf;
15177    struct ao2_iterator i;
15178    static char *choices[] = { "all", "like", NULL };
15179    char *cmplt;
15180    
15181    if (cmd == CLI_INIT) {
15182       e->command = "sip prune realtime [peer|all]";
15183       e->usage =
15184          "Usage: sip prune realtime [peer [<name>|all|like <pattern>]|all]\n"
15185          "       Prunes object(s) from the cache.\n"
15186          "       Optional regular expression pattern is used to filter the objects.\n";
15187       return NULL;
15188    } else if (cmd == CLI_GENERATE) {
15189       if (a->pos == 4 && !strcasecmp(a->argv[3], "peer")) {
15190          cmplt = ast_cli_complete(a->word, choices, a->n);
15191          if (!cmplt)
15192             cmplt = complete_sip_peer(a->word, a->n - sizeof(choices), SIP_PAGE2_RTCACHEFRIENDS);
15193          return cmplt;
15194       }
15195       if (a->pos == 5 && !strcasecmp(a->argv[4], "like"))
15196          return complete_sip_peer(a->word, a->n, SIP_PAGE2_RTCACHEFRIENDS);
15197       return NULL;
15198    }
15199    switch (a->argc) {
15200    case 4:
15201       name = a->argv[3];
15202       /* we accept a name in position 3, but keywords are not good. */
15203       if (!strcasecmp(name, "peer") || !strcasecmp(name, "like"))
15204          return CLI_SHOWUSAGE;
15205       prunepeer = TRUE;
15206       if (!strcasecmp(name, "all")) {
15207          multi = TRUE;
15208          name = NULL;
15209       }
15210       /* else a single name, already set */
15211       break;
15212    case 5:
15213       /* sip prune realtime {peer|like} name */
15214       name = a->argv[4];
15215       if (!strcasecmp(a->argv[3], "peer"))
15216          prunepeer = TRUE;
15217       else if (!strcasecmp(a->argv[3], "like")) {
15218          prunepeer = TRUE;
15219          multi = TRUE;
15220       } else
15221          return CLI_SHOWUSAGE;
15222       if (!strcasecmp(name, "like"))
15223          return CLI_SHOWUSAGE;
15224       if (!multi && !strcasecmp(name, "all")) {
15225          multi = TRUE;
15226          name = NULL;
15227       }
15228       break;
15229    case 6:
15230       name = a->argv[5];
15231       multi = TRUE;
15232       /* sip prune realtime {peer} like name */
15233       if (strcasecmp(a->argv[4], "like"))
15234          return CLI_SHOWUSAGE;
15235       if (!strcasecmp(a->argv[3], "peer")) {
15236          prunepeer = TRUE;
15237       } else
15238          return CLI_SHOWUSAGE;
15239       break;
15240    default:
15241       return CLI_SHOWUSAGE;
15242    }
15243 
15244    if (multi && name) {
15245       if (regcomp(&regexbuf, name, REG_EXTENDED | REG_NOSUB))
15246          return CLI_SHOWUSAGE;
15247    }
15248 
15249    if (multi) {
15250       if (prunepeer) {
15251          int pruned = 0;
15252          
15253          i = ao2_iterator_init(peers, 0);
15254          while ((pi = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
15255             ao2_lock(pi);
15256             if (name && regexec(&regexbuf, pi->name, 0, NULL, 0)) {
15257                unref_peer(pi, "toss iterator peer ptr before continue");
15258                ao2_unlock(pi);
15259                continue;
15260             };
15261             if (ast_test_flag(&pi->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
15262                pi->the_mark = 1;
15263                pruned++;
15264             }
15265             ao2_unlock(pi);
15266             unref_peer(pi, "toss iterator peer ptr");
15267          }
15268          ao2_iterator_destroy(&i);
15269          if (pruned) {
15270             unlink_marked_peers_from_tables();
15271             ast_cli(a->fd, "%d peers pruned.\n", pruned);
15272          } else
15273             ast_cli(a->fd, "No peers found to prune.\n");
15274       }
15275    } else {
15276       if (prunepeer) {
15277          struct sip_peer tmp;
15278          ast_copy_string(tmp.name, name, sizeof(tmp.name));
15279          if ((peer = ao2_t_find(peers, &tmp, OBJ_POINTER | OBJ_UNLINK, "finding to unlink from peers"))) {
15280             if (peer->addr.sin_addr.s_addr) {
15281                ao2_t_unlink(peers_by_ip, peer, "unlinking peer from peers_by_ip also");
15282             }
15283             if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
15284                ast_cli(a->fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
15285                /* put it back! */
15286                ao2_t_link(peers, peer, "link peer into peer table");
15287                if (peer->addr.sin_addr.s_addr) {
15288                   ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
15289                }
15290                
15291             } else
15292                ast_cli(a->fd, "Peer '%s' pruned.\n", name);
15293             unref_peer(peer, "sip_prune_realtime: unref_peer: tossing temp peer ptr");
15294          } else
15295             ast_cli(a->fd, "Peer '%s' not found.\n", name);
15296       }
15297    }
15298 
15299    return CLI_SUCCESS;
15300 }
15301 
15302 /*! \brief Print codec list from preference to CLI/manager */
15303 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
15304 {
15305    int x, codec;
15306 
15307    for(x = 0; x < 32 ; x++) {
15308       codec = ast_codec_pref_index(pref, x);
15309       if (!codec)
15310          break;
15311       ast_cli(fd, "%s", ast_getformatname(codec));
15312       ast_cli(fd, ":%d", pref->framing[x]);
15313       if (x < 31 && ast_codec_pref_index(pref, x + 1))
15314          ast_cli(fd, ",");
15315    }
15316    if (!x)
15317       ast_cli(fd, "none");
15318 }
15319 
15320 /*! \brief Print domain mode to cli */
15321 static const char *domain_mode_to_text(const enum domain_mode mode)
15322 {
15323    switch (mode) {
15324    case SIP_DOMAIN_AUTO:
15325       return "[Automatic]";
15326    case SIP_DOMAIN_CONFIG:
15327       return "[Configured]";
15328    }
15329 
15330    return "";
15331 }
15332 
15333 /*! \brief CLI command to list local domains */
15334 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15335 {
15336    struct domain *d;
15337 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
15338 
15339    switch (cmd) {
15340    case CLI_INIT:
15341       e->command = "sip show domains";
15342       e->usage =
15343          "Usage: sip show domains\n"
15344          "       Lists all configured SIP local domains.\n"
15345          "       Asterisk only responds to SIP messages to local domains.\n";
15346       return NULL;
15347    case CLI_GENERATE:
15348       return NULL;
15349    }
15350 
15351    if (AST_LIST_EMPTY(&domain_list)) {
15352       ast_cli(a->fd, "SIP Domain support not enabled.\n\n");
15353       return CLI_SUCCESS;
15354    } else {
15355       ast_cli(a->fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
15356       AST_LIST_LOCK(&domain_list);
15357       AST_LIST_TRAVERSE(&domain_list, d, list)
15358          ast_cli(a->fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
15359             domain_mode_to_text(d->mode));
15360       AST_LIST_UNLOCK(&domain_list);
15361       ast_cli(a->fd, "\n");
15362       return CLI_SUCCESS;
15363    }
15364 }
15365 #undef FORMAT
15366 
15367 static char mandescr_show_peer[] = 
15368 "Description: Show one SIP peer with details on current status.\n"
15369 "Variables: \n"
15370 "  Peer: <name>           The peer name you want to check.\n"
15371 "  ActionID: <id>   Optional action ID for this AMI transaction.\n";
15372 
15373 /*! \brief Show SIP peers in the manager API  */
15374 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
15375 {
15376    const char *a[4];
15377    const char *peer;
15378 
15379    peer = astman_get_header(m, "Peer");
15380    if (ast_strlen_zero(peer)) {
15381       astman_send_error(s, m, "Peer: <name> missing.");
15382       return 0;
15383    }
15384    a[0] = "sip";
15385    a[1] = "show";
15386    a[2] = "peer";
15387    a[3] = peer;
15388 
15389    _sip_show_peer(1, -1, s, m, 4, a);
15390    astman_append(s, "\r\n\r\n" );
15391    return 0;
15392 }
15393 
15394 /*! \brief Show one peer in detail */
15395 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15396 {
15397    switch (cmd) {
15398    case CLI_INIT:
15399       e->command = "sip show peer";
15400       e->usage =
15401          "Usage: sip show peer <name> [load]\n"
15402          "       Shows all details on one SIP peer and the current status.\n"
15403          "       Option \"load\" forces lookup of peer in realtime storage.\n";
15404       return NULL;
15405    case CLI_GENERATE:
15406       return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
15407    }
15408    return _sip_show_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
15409 }
15410 
15411 /*! \brief Send qualify message to peer from cli or manager. Mostly for debugging. */
15412 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
15413 {
15414    struct sip_peer *peer;
15415    int load_realtime;
15416 
15417    if (argc < 4)
15418       return CLI_SHOWUSAGE;
15419 
15420    load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
15421    if ((peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0))) {
15422       sip_poke_peer(peer, 1);
15423       unref_peer(peer, "qualify: done with peer");
15424    } else if (type == 0) {
15425       ast_cli(fd, "Peer '%s' not found\n", argv[3]);
15426    } else {
15427       astman_send_error(s, m, "Peer not found");
15428    }
15429    return CLI_SUCCESS;
15430 }
15431 
15432 /*! \brief Qualify SIP peers in the manager API  */
15433 static int manager_sip_qualify_peer(struct mansession *s, const struct message *m)
15434 {
15435    const char *a[4];
15436    const char *peer;
15437 
15438    peer = astman_get_header(m, "Peer");
15439    if (ast_strlen_zero(peer)) {
15440       astman_send_error(s, m, "Peer: <name> missing.");
15441       return 0;
15442    }
15443    a[0] = "sip";
15444    a[1] = "qualify";
15445    a[2] = "peer";
15446    a[3] = peer;
15447 
15448    _sip_qualify_peer(1, -1, s, m, 4, a);
15449    astman_append(s, "\r\n\r\n" );
15450    return 0;
15451 }
15452 
15453 /*! \brief Send an OPTIONS packet to a SIP peer */
15454 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15455 {
15456    switch (cmd) {
15457    case CLI_INIT:
15458       e->command = "sip qualify peer";
15459       e->usage =
15460          "Usage: sip qualify peer <name> [load]\n"
15461          "       Requests a response from one SIP peer and the current status.\n"
15462          "       Option \"load\" forces lookup of peer in realtime storage.\n";
15463       return NULL;
15464    case CLI_GENERATE:
15465       return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
15466    }
15467    return _sip_qualify_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
15468 }
15469 
15470 /*! \brief list peer mailboxes to CLI */
15471 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer)
15472 {
15473    struct sip_mailbox *mailbox;
15474 
15475    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
15476       ast_str_append(mailbox_str, 0, "%s%s%s%s",
15477          mailbox->mailbox,
15478          ast_strlen_zero(mailbox->context) ? "" : "@",
15479          S_OR(mailbox->context, ""),
15480          AST_LIST_NEXT(mailbox, entry) ? "," : "");
15481    }
15482 }
15483 
15484 static struct _map_x_s faxecmodes[] = {
15485    { SIP_PAGE2_T38SUPPORT_UDPTL,       "None"},
15486    { SIP_PAGE2_T38SUPPORT_UDPTL_FEC,      "FEC"},
15487    { SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY,  "Redundancy"},
15488    { -1,                NULL},
15489 };
15490 
15491 static const char *faxec2str(int faxec)
15492 {
15493    return map_x_s(faxecmodes, faxec, "Unknown");
15494 }
15495 
15496 /*! \brief Show one peer in detail (main function) */
15497 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
15498 {
15499    char status[30] = "";
15500    char cbuf[256];
15501    struct sip_peer *peer;
15502    char codec_buf[512];
15503    struct ast_codec_pref *pref;
15504    struct ast_variable *v;
15505    struct sip_auth *auth;
15506    int x = 0, codec = 0, load_realtime;
15507    int realtimepeers;
15508 
15509    realtimepeers = ast_check_realtime("sippeers");
15510 
15511    if (argc < 4)
15512       return CLI_SHOWUSAGE;
15513 
15514    load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
15515    peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0);
15516 
15517    if (s) {    /* Manager */
15518       if (peer) {
15519          const char *id = astman_get_header(m, "ActionID");
15520 
15521          astman_append(s, "Response: Success\r\n");
15522          if (!ast_strlen_zero(id))
15523             astman_append(s, "ActionID: %s\r\n", id);
15524       } else {
15525          snprintf (cbuf, sizeof(cbuf), "Peer %s not found.", argv[3]);
15526          astman_send_error(s, m, cbuf);
15527          return CLI_SUCCESS;
15528       }
15529    }
15530    if (peer && type==0 ) { /* Normal listing */
15531       struct ast_str *mailbox_str = ast_str_alloca(512);
15532       ast_cli(fd, "\n\n");
15533       ast_cli(fd, "  * Name       : %s\n", peer->name);
15534       if (realtimepeers) { /* Realtime is enabled */
15535          ast_cli(fd, "  Realtime peer: %s\n", peer->is_realtime ? "Yes, cached" : "No");
15536       }
15537       ast_cli(fd, "  Secret       : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
15538       ast_cli(fd, "  MD5Secret    : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
15539       ast_cli(fd, "  Remote Secret: %s\n", ast_strlen_zero(peer->remotesecret)?"<Not set>":"<Set>");
15540       for (auth = peer->auth; auth; auth = auth->next) {
15541          ast_cli(fd, "  Realm-auth   : Realm %-15.15s User %-10.20s ", auth->realm, auth->username);
15542          ast_cli(fd, "%s\n", !ast_strlen_zero(auth->secret)?"<Secret set>":(!ast_strlen_zero(auth->md5secret)?"<MD5secret set>" : "<Not set>"));
15543       }
15544       ast_cli(fd, "  Context      : %s\n", peer->context);
15545       ast_cli(fd, "  Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
15546       ast_cli(fd, "  Language     : %s\n", peer->language);
15547       if (!ast_strlen_zero(peer->accountcode))
15548          ast_cli(fd, "  Accountcode  : %s\n", peer->accountcode);
15549       ast_cli(fd, "  AMA flags    : %s\n", ast_cdr_flags2str(peer->amaflags));
15550       ast_cli(fd, "  Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
15551       ast_cli(fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(peer->callingpres));
15552       if (!ast_strlen_zero(peer->fromuser))
15553          ast_cli(fd, "  FromUser     : %s\n", peer->fromuser);
15554       if (!ast_strlen_zero(peer->fromdomain))
15555          ast_cli(fd, "  FromDomain   : %s\n", peer->fromdomain);
15556       ast_cli(fd, "  Callgroup    : ");
15557       print_group(fd, peer->callgroup, 0);
15558       ast_cli(fd, "  Pickupgroup  : ");
15559       print_group(fd, peer->pickupgroup, 0);
15560       peer_mailboxes_to_str(&mailbox_str, peer);
15561       ast_cli(fd, "  Mailbox      : %s\n", mailbox_str->str);
15562       ast_cli(fd, "  VM Extension : %s\n", peer->vmexten);
15563       ast_cli(fd, "  LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
15564       ast_cli(fd, "  Call limit   : %d\n", peer->call_limit);
15565       if (peer->busy_level)
15566          ast_cli(fd, "  Busy level   : %d\n", peer->busy_level);
15567       ast_cli(fd, "  Dynamic      : %s\n", cli_yesno(peer->host_dynamic));
15568       ast_cli(fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
15569       ast_cli(fd, "  MaxCallBR    : %d kbps\n", peer->maxcallbitrate);
15570       ast_cli(fd, "  Expire       : %ld\n", ast_sched_when(sched, peer->expire));
15571       ast_cli(fd, "  Insecure     : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
15572       ast_cli(fd, "  Nat          : %s\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
15573       ast_cli(fd, "  ACL          : %s\n", cli_yesno(peer->ha != NULL));
15574       ast_cli(fd, "  T.38 support : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
15575       ast_cli(fd, "  T.38 EC mode : %s\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
15576       ast_cli(fd, "  T.38 MaxDtgrm: %d\n", peer->t38_maxdatagram);
15577       ast_cli(fd, "  DirectMedia  : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)));
15578       ast_cli(fd, "  PromiscRedir : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)));
15579       ast_cli(fd, "  User=Phone   : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)));
15580       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)));
15581       ast_cli(fd, "  Text Support : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)));
15582       ast_cli(fd, "  Ign SDP ver  : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_IGNORESDPVERSION)));
15583       ast_cli(fd, "  Trust RPID   : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_TRUSTRPID)));
15584       ast_cli(fd, "  Send RPID    : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_SENDRPID)));
15585       ast_cli(fd, "  Subscriptions: %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
15586       ast_cli(fd, "  Overlap dial : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP)));
15587       ast_cli(fd, "  Forward Loop : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_FORWARD_LOOP_DETECTED)));
15588       if (peer->outboundproxy)
15589          ast_cli(fd, "  Outb. proxy  : %s %s\n", ast_strlen_zero(peer->outboundproxy->name) ? "<not set>" : peer->outboundproxy->name,
15590                      peer->outboundproxy->force ? "(forced)" : "");
15591 
15592       /* - is enumerated */
15593       ast_cli(fd, "  DTMFmode     : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
15594       ast_cli(fd, "  Timer T1     : %d\n", peer->timer_t1);
15595       ast_cli(fd, "  Timer B      : %d\n", peer->timer_b);
15596       ast_cli(fd, "  ToHost       : %s\n", peer->tohost);
15597       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));
15598       ast_cli(fd, "  Defaddr->IP  : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
15599       ast_cli(fd, "  Prim.Transp. : %s\n", get_transport(peer->socket.type));
15600       ast_cli(fd, "  Allowed.Trsp : %s\n", get_transport_list(peer->transports)); 
15601       if (!ast_strlen_zero(global_regcontext))
15602          ast_cli(fd, "  Reg. exten   : %s\n", peer->regexten);
15603       ast_cli(fd, "  Def. Username: %s\n", peer->username);
15604       ast_cli(fd, "  SIP Options  : ");
15605       if (peer->sipoptions) {
15606          int lastoption = -1;
15607          for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
15608             if (sip_options[x].id != lastoption) {
15609                if (peer->sipoptions & sip_options[x].id)
15610                   ast_cli(fd, "%s ", sip_options[x].text);
15611                lastoption = x;
15612             }
15613          }
15614       } else
15615          ast_cli(fd, "(none)");
15616 
15617       ast_cli(fd, "\n");
15618       ast_cli(fd, "  Codecs       : ");
15619       ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
15620       ast_cli(fd, "%s\n", codec_buf);
15621       ast_cli(fd, "  Codec Order  : (");
15622       print_codec_to_cli(fd, &peer->prefs);
15623       ast_cli(fd, ")\n");
15624 
15625       ast_cli(fd, "  Auto-Framing :  %s \n", cli_yesno(peer->autoframing));
15626       ast_cli(fd, "  100 on REG   : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_REGISTERTRYING) ? "Yes" : "No");
15627       ast_cli(fd, "  Status       : ");
15628       peer_status(peer, status, sizeof(status));
15629       ast_cli(fd, "%s\n", status);
15630       ast_cli(fd, "  Useragent    : %s\n", peer->useragent);
15631       ast_cli(fd, "  Reg. Contact : %s\n", peer->fullcontact);
15632       ast_cli(fd, "  Qualify Freq : %d ms\n", peer->qualifyfreq);
15633       if (peer->chanvars) {
15634          ast_cli(fd, "  Variables    :\n");
15635          for (v = peer->chanvars ; v ; v = v->next)
15636             ast_cli(fd, "                 %s = %s\n", v->name, v->value);
15637       }
15638 
15639       ast_cli(fd, "  Sess-Timers  : %s\n", stmode2str(peer->stimer.st_mode_oper));
15640       ast_cli(fd, "  Sess-Refresh : %s\n", strefresher2str(peer->stimer.st_ref));
15641       ast_cli(fd, "  Sess-Expires : %d secs\n", peer->stimer.st_max_se);
15642       ast_cli(fd, "  Min-Sess     : %d secs\n", peer->stimer.st_min_se);
15643       ast_cli(fd, "  Parkinglot   : %s\n", peer->parkinglot);
15644       ast_cli(fd, "\n");
15645       peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer ptr");
15646    } else  if (peer && type == 1) { /* manager listing */
15647       char buffer[256];
15648       struct ast_str *mailbox_str = ast_str_alloca(512);
15649       astman_append(s, "Channeltype: SIP\r\n");
15650       astman_append(s, "ObjectName: %s\r\n", peer->name);
15651       astman_append(s, "ChanObjectType: peer\r\n");
15652       astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
15653       astman_append(s, "RemoteSecretExist: %s\r\n", ast_strlen_zero(peer->remotesecret)?"N":"Y");
15654       astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
15655       astman_append(s, "Context: %s\r\n", peer->context);
15656       astman_append(s, "Language: %s\r\n", peer->language);
15657       if (!ast_strlen_zero(peer->accountcode))
15658          astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
15659       astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
15660       astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
15661       if (!ast_strlen_zero(peer->fromuser))
15662          astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
15663       if (!ast_strlen_zero(peer->fromdomain))
15664          astman_append(s, "SIP-FromDomain: %s\r\n", peer->fromdomain);
15665       astman_append(s, "Callgroup: ");
15666       astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->callgroup));
15667       astman_append(s, "Pickupgroup: ");
15668       astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->pickupgroup));
15669       peer_mailboxes_to_str(&mailbox_str, peer);
15670       astman_append(s, "VoiceMailbox: %s\r\n", mailbox_str->str);
15671       astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
15672       astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
15673       astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
15674       astman_append(s, "Busy-level: %d\r\n", peer->busy_level);
15675       astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
15676       astman_append(s, "Dynamic: %s\r\n", peer->host_dynamic?"Y":"N");
15677       astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
15678       astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched, peer->expire));
15679       astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
15680       astman_append(s, "SIP-NatSupport: %s\r\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
15681       astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
15682       astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
15683       astman_append(s, "SIP-DirectMedia: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
15684       astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
15685       astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
15686       astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
15687       astman_append(s, "SIP-TextSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)?"Y":"N"));
15688       astman_append(s, "SIP-T.38Support: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)?"Y":"N"));
15689       astman_append(s, "SIP-T.38EC: %s\r\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
15690       astman_append(s, "SIP-T.38MaxDtgrm: %d\r\n", peer->t38_maxdatagram);
15691       astman_append(s, "SIP-Sess-Timers: %s\r\n", stmode2str(peer->stimer.st_mode_oper));
15692       astman_append(s, "SIP-Sess-Refresh: %s\r\n", strefresher2str(peer->stimer.st_ref));
15693       astman_append(s, "SIP-Sess-Expires: %d\r\n", peer->stimer.st_max_se);
15694       astman_append(s, "SIP-Sess-Min: %d\r\n", peer->stimer.st_min_se);
15695 
15696       /* - is enumerated */
15697       astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
15698       astman_append(s, "ToHost: %s\r\n", peer->tohost);
15699       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));
15700       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));
15701       astman_append(s, "Default-Username: %s\r\n", peer->username);
15702       if (!ast_strlen_zero(global_regcontext))
15703          astman_append(s, "RegExtension: %s\r\n", peer->regexten);
15704       astman_append(s, "Codecs: ");
15705       ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
15706       astman_append(s, "%s\r\n", codec_buf);
15707       astman_append(s, "CodecOrder: ");
15708       pref = &peer->prefs;
15709       for(x = 0; x < 32 ; x++) {
15710          codec = ast_codec_pref_index(pref, x);
15711          if (!codec)
15712             break;
15713          astman_append(s, "%s", ast_getformatname(codec));
15714          if (x < 31 && ast_codec_pref_index(pref, x+1))
15715             astman_append(s, ",");
15716       }
15717 
15718       astman_append(s, "\r\n");
15719       astman_append(s, "Status: ");
15720       peer_status(peer, status, sizeof(status));
15721       astman_append(s, "%s\r\n", status);
15722       astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
15723       astman_append(s, "Reg-Contact: %s\r\n", peer->fullcontact);
15724       astman_append(s, "QualifyFreq: %d ms\r\n", peer->qualifyfreq);
15725       astman_append(s, "Parkinglot: %s\r\n", peer->parkinglot);
15726       if (peer->chanvars) {
15727          for (v = peer->chanvars ; v ; v = v->next) {
15728             astman_append(s, "ChanVariable: %s=%s\r\n", v->name, v->value);
15729          }
15730       }
15731 
15732       peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer");
15733 
15734    } else {
15735       ast_cli(fd, "Peer %s not found.\n", argv[3]);
15736       ast_cli(fd, "\n");
15737    }
15738 
15739    return CLI_SUCCESS;
15740 }
15741 
15742 /*! \brief Do completion on user name */
15743 static char *complete_sip_user(const char *word, int state)
15744 {
15745    char *result = NULL;
15746    int wordlen = strlen(word);
15747    int which = 0;
15748    struct ao2_iterator user_iter;
15749    struct sip_peer *user;
15750 
15751    user_iter = ao2_iterator_init(peers, 0);
15752    while ((user = ao2_iterator_next(&user_iter))) {
15753       ao2_lock(user);
15754       if (!(user->type & SIP_TYPE_USER)) {
15755          ao2_unlock(user);
15756          unref_peer(user, "complete sip user");
15757          continue;
15758       }
15759       /* locking of the object is not required because only the name and flags are being compared */
15760       if (!strncasecmp(word, user->name, wordlen) && ++which > state) {
15761          result = ast_strdup(user->name);
15762       }
15763       ao2_unlock(user);
15764       unref_peer(user, "complete sip user");
15765    }
15766    ao2_iterator_destroy(&user_iter);
15767    return result;
15768 }
15769 /*! \brief Support routine for 'sip show user' CLI */
15770 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
15771 {
15772    if (pos == 3)
15773       return complete_sip_user(word, state);
15774 
15775    return NULL;
15776 }
15777 
15778 /*! \brief Show one user in detail */
15779 static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15780 {
15781    char cbuf[256];
15782    struct sip_peer *user;
15783    struct ast_variable *v;
15784    int load_realtime;
15785 
15786    switch (cmd) {
15787    case CLI_INIT:
15788       e->command = "sip show user";
15789       e->usage =
15790          "Usage: sip show user <name> [load]\n"
15791          "       Shows all details on one SIP user and the current status.\n"
15792          "       Option \"load\" forces lookup of peer in realtime storage.\n";
15793       return NULL;
15794    case CLI_GENERATE:
15795       return complete_sip_show_user(a->line, a->word, a->pos, a->n);
15796    }
15797 
15798    if (a->argc < 4)
15799       return CLI_SHOWUSAGE;
15800 
15801    /* Load from realtime storage? */
15802    load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? TRUE : FALSE;
15803 
15804    if ((user = find_peer(a->argv[3], NULL, load_realtime, FINDUSERS, FALSE, 0))) {
15805       ao2_lock(user);
15806       ast_cli(a->fd, "\n\n");
15807       ast_cli(a->fd, "  * Name       : %s\n", user->name);
15808       ast_cli(a->fd, "  Secret       : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
15809       ast_cli(a->fd, "  MD5Secret    : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
15810       ast_cli(a->fd, "  Context      : %s\n", user->context);
15811       ast_cli(a->fd, "  Language     : %s\n", user->language);
15812       if (!ast_strlen_zero(user->accountcode))
15813          ast_cli(a->fd, "  Accountcode  : %s\n", user->accountcode);
15814       ast_cli(a->fd, "  AMA flags    : %s\n", ast_cdr_flags2str(user->amaflags));
15815       ast_cli(a->fd, "  Transfer mode: %s\n", transfermode2str(user->allowtransfer));
15816       ast_cli(a->fd, "  MaxCallBR    : %d kbps\n", user->maxcallbitrate);
15817       ast_cli(a->fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(user->callingpres));
15818       ast_cli(a->fd, "  Call limit   : %d\n", user->call_limit);
15819       ast_cli(a->fd, "  Callgroup    : ");
15820       print_group(a->fd, user->callgroup, 0);
15821       ast_cli(a->fd, "  Pickupgroup  : ");
15822       print_group(a->fd, user->pickupgroup, 0);
15823       ast_cli(a->fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
15824       ast_cli(a->fd, "  ACL          : %s\n", cli_yesno(user->ha != NULL));
15825       ast_cli(a->fd, "  Sess-Timers  : %s\n", stmode2str(user->stimer.st_mode_oper));
15826       ast_cli(a->fd, "  Sess-Refresh : %s\n", strefresher2str(user->stimer.st_ref));
15827       ast_cli(a->fd, "  Sess-Expires : %d secs\n", user->stimer.st_max_se);
15828       ast_cli(a->fd, "  Sess-Min-SE  : %d secs\n", user->stimer.st_min_se);
15829 
15830       ast_cli(a->fd, "  Codec Order  : (");
15831       print_codec_to_cli(a->fd, &user->prefs);
15832       ast_cli(a->fd, ")\n");
15833 
15834       ast_cli(a->fd, "  Auto-Framing:  %s \n", cli_yesno(user->autoframing));
15835       if (user->chanvars) {
15836          ast_cli(a->fd, "  Variables    :\n");
15837          for (v = user->chanvars ; v ; v = v->next)
15838             ast_cli(a->fd, "                 %s = %s\n", v->name, v->value);
15839       }
15840 
15841       ast_cli(a->fd, "\n");
15842 
15843       ao2_unlock(user);
15844       unref_peer(user, "sip show user");
15845    } else {
15846       ast_cli(a->fd, "User %s not found.\n", a->argv[3]);
15847       ast_cli(a->fd, "\n");
15848    }
15849 
15850    return CLI_SUCCESS;
15851 }
15852 
15853 
15854 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15855 {
15856    struct ast_str *cbuf;
15857    struct ast_cb_names cbnames = {9, { "retrans_pkt",
15858                                         "__sip_autodestruct",
15859                                         "expire_register",
15860                                         "auto_congest",
15861                                         "sip_reg_timeout",
15862                                         "sip_poke_peer_s",
15863                                         "sip_poke_noanswer",
15864                                         "sip_reregister",
15865                                         "sip_reinvite_retry"},
15866                            { retrans_pkt,
15867                                      __sip_autodestruct,
15868                                      expire_register,
15869                                      auto_congest,
15870                                      sip_reg_timeout,
15871                                      sip_poke_peer_s,
15872                                      sip_poke_noanswer,
15873                                      sip_reregister,
15874                                      sip_reinvite_retry}};
15875    
15876    switch (cmd) {
15877    case CLI_INIT:
15878       e->command = "sip show sched";
15879       e->usage =
15880          "Usage: sip show sched\n"
15881          "       Shows stats on what's in the sched queue at the moment\n";
15882       return NULL;
15883    case CLI_GENERATE:
15884       return NULL;
15885    }
15886 
15887    cbuf = ast_str_alloca(2048);
15888 
15889    ast_cli(a->fd, "\n");
15890    ast_sched_report(sched, &cbuf, &cbnames);
15891    ast_cli(a->fd, "%s", cbuf->str);
15892 
15893    return CLI_SUCCESS;
15894 }
15895 
15896 /*! \brief  Show SIP Registry (registrations with other SIP proxies */
15897 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15898 {
15899 #define FORMAT2 "%-30.30s %-6.6s %-12.12s  %8.8s %-20.20s %-25.25s\n"
15900 #define FORMAT  "%-30.30s %-6.6s %-12.12s  %8d %-20.20s %-25.25s\n"
15901    char host[80];
15902    char tmpdat[256];
15903    struct ast_tm tm;
15904    int counter = 0;
15905 
15906    switch (cmd) {
15907    case CLI_INIT:
15908       e->command = "sip show registry";
15909       e->usage =
15910          "Usage: sip show registry\n"
15911          "       Lists all registration requests and status.\n";
15912       return NULL;
15913    case CLI_GENERATE:
15914       return NULL;
15915    }
15916 
15917    if (a->argc != 3)
15918       return CLI_SHOWUSAGE;
15919    ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Refresh", "State", "Reg.Time");
15920    
15921    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
15922       ASTOBJ_RDLOCK(iterator);
15923       snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
15924       if (iterator->regtime.tv_sec) {
15925          ast_localtime(&iterator->regtime, &tm, NULL);
15926          ast_strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
15927       } else 
15928          tmpdat[0] = '\0';
15929       ast_cli(a->fd, FORMAT, host, (iterator->dnsmgr) ? "Y" : "N", iterator->username, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
15930       ASTOBJ_UNLOCK(iterator);
15931       counter++;
15932    } while(0));
15933    ast_cli(a->fd, "%d SIP registrations.\n", counter);
15934    return CLI_SUCCESS;
15935 #undef FORMAT
15936 #undef FORMAT2
15937 }
15938 
15939 /*! \brief Unregister (force expiration) a SIP peer in the registry via CLI 
15940    \note This function does not tell the SIP device what's going on,
15941    so use it with great care.
15942 */
15943 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15944 {
15945    struct sip_peer *peer;
15946    int load_realtime = 0;
15947 
15948    switch (cmd) {
15949    case CLI_INIT:
15950       e->command = "sip unregister";
15951       e->usage =
15952          "Usage: sip unregister <peer>\n"
15953          "       Unregister (force expiration) a SIP peer from the registry\n";
15954       return NULL;
15955    case CLI_GENERATE:
15956       return complete_sip_unregister(a->line, a->word, a->pos, a->n);
15957    }
15958    
15959    if (a->argc != 3)
15960       return CLI_SHOWUSAGE;
15961    
15962    if ((peer = find_peer(a->argv[2], NULL, load_realtime, FINDPEERS, TRUE, 0))) {
15963       if (peer->expire > 0) {
15964          AST_SCHED_DEL_UNREF(sched, peer->expire,
15965             unref_peer(peer, "remove register expire ref"));
15966          expire_register(ref_peer(peer, "ref for expire_register"));
15967          ast_cli(a->fd, "Unregistered peer \'%s\'\n\n", a->argv[2]);
15968       } else {
15969          ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
15970       }
15971       unref_peer(peer, "sip_unregister: unref_peer via sip_unregister: done with peer from find_peer call");
15972    } else {
15973       ast_cli(a->fd, "Peer unknown: \'%s\'. Not unregistered.\n", a->argv[2]);
15974    }
15975    
15976    return CLI_SUCCESS;
15977 }
15978 
15979 /*! \brief Callback for show_chanstats */
15980 static int show_chanstats_cb(void *__cur, void *__arg, int flags)
15981 {
15982 #define FORMAT2 "%-15.15s  %-11.11s  %-8.8s %-10.10s  %-10.10s (     %%) %-6.6s %-10.10s  %-10.10s (     %%) %-6.6s\n"
15983 #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"
15984    struct sip_pvt *cur = __cur;
15985    unsigned int rxcount, txcount, rxploss, txploss;
15986    char durbuf[10];
15987         int duration;
15988         int durh, durm, durs;
15989    struct ast_channel *c = cur->owner;
15990    struct __show_chan_arg *arg = __arg;
15991    int fd = arg->fd;
15992 
15993 
15994    if (cur->subscribed != NONE) /* Subscriptions */
15995       return 0;   /* don't care, we scan all channels */
15996 
15997    if (!cur->rtp) {
15998       if (sipdebug)
15999          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");
16000       return 0;   /* don't care, we scan all channels */
16001    }
16002    rxcount = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXCOUNT);
16003    txcount = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXCOUNT);
16004    rxploss = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXPLOSS);
16005    txploss = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXPLOSS);
16006 
16007    /* Find the duration of this channel */
16008    if (c && c->cdr && !ast_tvzero(c->cdr->start)) {
16009       duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
16010       durh = duration / 3600;
16011       durm = (duration % 3600) / 60;
16012       durs = duration % 60;
16013       snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
16014    } else {
16015       durbuf[0] = '\0';
16016    }
16017    /* Print stats for every call with RTP */
16018    ast_cli(fd, FORMAT, 
16019       ast_inet_ntoa(cur->sa.sin_addr), 
16020       cur->callid, 
16021       durbuf,
16022       rxcount > (unsigned int) 100000 ? (unsigned int) (rxcount)/(unsigned int) 1000 : rxcount,
16023       rxcount > (unsigned int) 100000 ? "K":" ",
16024       rxploss,
16025       (rxcount + rxploss) > 0 ? (double) rxploss / (rxcount + rxploss) * 100 : 0,
16026       ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXJITTER),
16027       txcount > (unsigned int) 100000 ? (unsigned int) (txcount)/(unsigned int) 1000 : txcount,
16028       txcount > (unsigned int) 100000 ? "K":" ",
16029       txploss,
16030       txcount > 0 ? (double) txploss / txcount * 100 : 0,
16031       ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXJITTER)
16032    );
16033    arg->numchans++;
16034 
16035    return 0;   /* don't care, we scan all channels */
16036 }
16037 
16038 /*! \brief SIP show channelstats CLI (main function) */
16039 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16040 {
16041    struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
16042 
16043    switch (cmd) {
16044    case CLI_INIT:
16045       e->command = "sip show channelstats";
16046       e->usage =
16047          "Usage: sip show channelstats\n"
16048          "       Lists all currently active SIP channel's RTCP statistics.\n"
16049          "       Note that calls in the much optimized RTP P2P bridge mode will not show any packets here.";
16050       return NULL;
16051    case CLI_GENERATE:
16052       return NULL;
16053    }
16054 
16055    if (a->argc != 3)
16056       return CLI_SHOWUSAGE;
16057 
16058    ast_cli(a->fd, FORMAT2, "Peer", "Call ID", "Duration", "Recv: Pack", "Lost", "Jitter", "Send: Pack", "Lost", "Jitter");
16059    /* iterate on the container and invoke the callback on each item */
16060    ao2_t_callback(dialogs, OBJ_NODATA, show_chanstats_cb, &arg, "callback to sip show chanstats");
16061    ast_cli(a->fd, "%d active SIP channel%s\n", arg.numchans, (arg.numchans != 1) ? "s" : ""); 
16062    return CLI_SUCCESS;
16063 }
16064 #undef FORMAT
16065 #undef FORMAT2
16066 
16067 /*! \brief List global settings for the SIP channel */
16068 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16069 {
16070    int realtimepeers;
16071    int realtimeregs;
16072    char codec_buf[SIPBUFSIZE];
16073    const char *msg;  /* temporary msg pointer */
16074 
16075    switch (cmd) {
16076    case CLI_INIT:
16077       e->command = "sip show settings";
16078       e->usage =
16079          "Usage: sip show settings\n"
16080          "       Provides detailed list of the configuration of the SIP channel.\n";
16081       return NULL;
16082    case CLI_GENERATE:
16083       return NULL;
16084    }
16085 
16086 
16087    realtimepeers = ast_check_realtime("sippeers");
16088    realtimeregs = ast_check_realtime("sipregs");
16089 
16090    if (a->argc != 3)
16091       return CLI_SHOWUSAGE;
16092    ast_cli(a->fd, "\n\nGlobal Settings:\n");
16093    ast_cli(a->fd, "----------------\n");
16094    ast_cli(a->fd, "  UDP SIP Port:           %d\n", ntohs(bindaddr.sin_port));
16095    ast_cli(a->fd, "  UDP Bindaddress:        %s\n", ast_inet_ntoa(bindaddr.sin_addr));
16096    ast_cli(a->fd, "  TCP SIP Port:           ");
16097    if (sip_tcp_desc.local_address.sin_family == AF_INET) {
16098       ast_cli(a->fd, "%d\n", ntohs(sip_tcp_desc.local_address.sin_port));
16099       ast_cli(a->fd, "  TCP Bindaddress:        %s\n", ast_inet_ntoa(sip_tcp_desc.local_address.sin_addr));
16100    } else {
16101       ast_cli(a->fd, "Disabled\n");
16102    }
16103    ast_cli(a->fd, "  TLS SIP Port:           ");
16104    if (default_tls_cfg.enabled != FALSE) {
16105       ast_cli(a->fd, "%d\n", ntohs(sip_tls_desc.local_address.sin_port));
16106       ast_cli(a->fd, "  TLS Bindaddress:        %s\n", ast_inet_ntoa(sip_tls_desc.local_address.sin_addr));
16107    } else {
16108       ast_cli(a->fd, "Disabled\n");
16109    }
16110    ast_cli(a->fd, "  Videosupport:           %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT)));
16111    ast_cli(a->fd, "  Textsupport:            %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT)));
16112    ast_cli(a->fd, "  Ignore SDP sess. ver.:  %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION)));
16113    ast_cli(a->fd, "  AutoCreate Peer:        %s\n", cli_yesno(sip_cfg.autocreatepeer));
16114    ast_cli(a->fd, "  Match Auth Username:    %s\n", cli_yesno(global_match_auth_username));
16115    ast_cli(a->fd, "  Allow unknown access:   %s\n", cli_yesno(sip_cfg.allowguest));
16116    ast_cli(a->fd, "  Allow subscriptions:    %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
16117    ast_cli(a->fd, "  Allow overlap dialing:  %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)));
16118    ast_cli(a->fd, "  Allow promsic. redir:   %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_PROMISCREDIR)));
16119    ast_cli(a->fd, "  Enable call counters:   %s\n", cli_yesno(global_callcounter));
16120    ast_cli(a->fd, "  SIP domain support:     %s\n", cli_yesno(!AST_LIST_EMPTY(&domain_list)));
16121    ast_cli(a->fd, "  Realm. auth:            %s\n", cli_yesno(authl != NULL));
16122    ast_cli(a->fd, "  Our auth realm          %s\n", sip_cfg.realm);
16123    ast_cli(a->fd, "  Call to non-local dom.: %s\n", cli_yesno(sip_cfg.allow_external_domains));
16124    ast_cli(a->fd, "  URI user is phone no:   %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_USEREQPHONE)));
16125    ast_cli(a->fd, "  Always auth rejects:    %s\n", cli_yesno(sip_cfg.alwaysauthreject));
16126    ast_cli(a->fd, "  Direct RTP setup:       %s\n", cli_yesno(sip_cfg.directrtpsetup));
16127    ast_cli(a->fd, "  User Agent:             %s\n", global_useragent);
16128    ast_cli(a->fd, "  SDP Session Name:       %s\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
16129    ast_cli(a->fd, "  SDP Owner Name:         %s\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner);
16130    ast_cli(a->fd, "  Reg. context:           %s\n", S_OR(global_regcontext, "(not set)"));
16131    ast_cli(a->fd, "  Regexten on Qualify:    %s\n", cli_yesno(sip_cfg.regextenonqualify));
16132    ast_cli(a->fd, "  Caller ID:              %s\n", default_callerid);
16133    ast_cli(a->fd, "  From: Domain:           %s\n", default_fromdomain);
16134    ast_cli(a->fd, "  Record SIP history:     %s\n", recordhistory ? "On" : "Off");
16135    ast_cli(a->fd, "  Call Events:            %s\n", sip_cfg.callevents ? "On" : "Off");
16136    ast_cli(a->fd, "  Auth. Failure Events:   %s\n", global_authfailureevents ? "On" : "Off");
16137 
16138    ast_cli(a->fd, "  T.38 support:           %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
16139    ast_cli(a->fd, "  T.38 EC mode:           %s\n", faxec2str(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
16140    ast_cli(a->fd, "  T.38 MaxDtgrm:          %d\n", global_t38_maxdatagram);
16141 
16142    if (!realtimepeers && !realtimeregs)
16143       ast_cli(a->fd, "  SIP realtime:           Disabled\n" );
16144    else
16145       ast_cli(a->fd, "  SIP realtime:           Enabled\n" );
16146    ast_cli(a->fd, "  Qualify Freq :          %d ms\n", global_qualifyfreq);
16147    ast_cli(a->fd, "\nNetwork QoS Settings:\n");
16148    ast_cli(a->fd, "---------------------------\n");
16149    ast_cli(a->fd, "  IP ToS SIP:             %s\n", ast_tos2str(global_tos_sip));
16150    ast_cli(a->fd, "  IP ToS RTP audio:       %s\n", ast_tos2str(global_tos_audio));
16151    ast_cli(a->fd, "  IP ToS RTP video:       %s\n", ast_tos2str(global_tos_video));
16152    ast_cli(a->fd, "  IP ToS RTP text:        %s\n", ast_tos2str(global_tos_text));
16153    ast_cli(a->fd, "  802.1p CoS SIP:         %d\n", global_cos_sip);
16154    ast_cli(a->fd, "  802.1p CoS RTP audio:   %d\n", global_cos_audio);
16155    ast_cli(a->fd, "  802.1p CoS RTP video:   %d\n", global_cos_video);
16156    ast_cli(a->fd, "  802.1p CoS RTP text:    %d\n", global_cos_text);
16157    ast_cli(a->fd, "  Jitterbuffer enabled:   %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_ENABLED)));
16158    ast_cli(a->fd, "  Jitterbuffer forced:    %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_FORCED)));
16159    ast_cli(a->fd, "  Jitterbuffer max size:  %ld\n", global_jbconf.max_size);
16160    ast_cli(a->fd, "  Jitterbuffer resync:    %ld\n", global_jbconf.resync_threshold);
16161    ast_cli(a->fd, "  Jitterbuffer impl:      %s\n", global_jbconf.impl);
16162    ast_cli(a->fd, "  Jitterbuffer log:       %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_LOG)));
16163 
16164    ast_cli(a->fd, "\nNetwork Settings:\n");
16165    ast_cli(a->fd, "---------------------------\n");
16166    /* determine if/how SIP address can be remapped */
16167    if (localaddr == NULL)
16168       msg = "Disabled, no localnet list";
16169    else if (externip.sin_addr.s_addr == 0)
16170       msg = "Disabled, externip is 0.0.0.0";
16171    else if (stunaddr.sin_addr.s_addr != 0)
16172       msg = "Enabled using STUN";
16173    else if (!ast_strlen_zero(externhost))
16174       msg = "Enabled using externhost";
16175    else
16176       msg = "Enabled using externip";
16177    ast_cli(a->fd, "  SIP address remapping:  %s\n", msg);
16178    ast_cli(a->fd, "  Externhost:             %s\n", S_OR(externhost, "<none>"));
16179    ast_cli(a->fd, "  Externip:               %s:%d\n", ast_inet_ntoa(externip.sin_addr), ntohs(externip.sin_port));
16180    ast_cli(a->fd, "  Externrefresh:          %d\n", externrefresh);
16181    ast_cli(a->fd, "  Internal IP:            %s:%d\n", ast_inet_ntoa(internip.sin_addr), ntohs(internip.sin_port));
16182    {
16183       struct ast_ha *d;
16184       const char *prefix = "Localnet:";
16185       char buf[INET_ADDRSTRLEN]; /* need to print two addresses */
16186 
16187       for (d = localaddr; d ; prefix = "", d = d->next) {
16188          ast_cli(a->fd, "  %-24s%s/%s\n",
16189              prefix, ast_inet_ntoa(d->netaddr),
16190              inet_ntop(AF_INET, &d->netmask, buf, sizeof(buf)) );
16191       }
16192    }
16193    ast_cli(a->fd, "  STUN server:            %s:%d\n", ast_inet_ntoa(stunaddr.sin_addr), ntohs(stunaddr.sin_port));
16194  
16195    ast_cli(a->fd, "\nGlobal Signalling Settings:\n");
16196    ast_cli(a->fd, "---------------------------\n");
16197    ast_cli(a->fd, "  Codecs:                 ");
16198    ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, global_capability);
16199    ast_cli(a->fd, "%s\n", codec_buf);
16200    ast_cli(a->fd, "  Codec Order:            ");
16201    print_codec_to_cli(a->fd, &default_prefs);
16202    ast_cli(a->fd, "\n");
16203    ast_cli(a->fd, "  Relax DTMF:             %s\n", cli_yesno(global_relaxdtmf));
16204    ast_cli(a->fd, "  RFC2833 Compensation:   %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE)));
16205    ast_cli(a->fd, "  Compact SIP headers:    %s\n", cli_yesno(sip_cfg.compactheaders));
16206    ast_cli(a->fd, "  RTP Keepalive:          %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
16207    ast_cli(a->fd, "  RTP Timeout:            %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
16208    ast_cli(a->fd, "  RTP Hold Timeout:       %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
16209    ast_cli(a->fd, "  MWI NOTIFY mime type:   %s\n", default_notifymime);
16210    ast_cli(a->fd, "  DNS SRV lookup:         %s\n", cli_yesno(sip_cfg.srvlookup));
16211    ast_cli(a->fd, "  Pedantic SIP support:   %s\n", cli_yesno(sip_cfg.pedanticsipchecking));
16212    ast_cli(a->fd, "  Reg. min duration       %d secs\n", min_expiry);
16213    ast_cli(a->fd, "  Reg. max duration:      %d secs\n", max_expiry);
16214    ast_cli(a->fd, "  Reg. default duration:  %d secs\n", default_expiry);
16215    ast_cli(a->fd, "  Outbound reg. timeout:  %d secs\n", global_reg_timeout);
16216    ast_cli(a->fd, "  Outbound reg. attempts: %d\n", global_regattempts_max);
16217    ast_cli(a->fd, "  Notify ringing state:   %s\n", cli_yesno(sip_cfg.notifyringing));
16218    if (sip_cfg.notifyringing) {
16219       ast_cli(a->fd, "    Include CID:          %s%s\n",
16220             cli_yesno(sip_cfg.notifycid),
16221             sip_cfg.notifycid == IGNORE_CONTEXT ? " (Ignoring context)" : "");
16222    }
16223    ast_cli(a->fd, "  Notify hold state:      %s\n", cli_yesno(sip_cfg.notifyhold));
16224    ast_cli(a->fd, "  SIP Transfer mode:      %s\n", transfermode2str(sip_cfg.allowtransfer));
16225    ast_cli(a->fd, "  Max Call Bitrate:       %d kbps\n", default_maxcallbitrate);
16226    ast_cli(a->fd, "  Auto-Framing:           %s\n", cli_yesno(global_autoframing));
16227    ast_cli(a->fd, "  Outb. proxy:            %s %s\n", ast_strlen_zero(sip_cfg.outboundproxy.name) ? "<not set>" : sip_cfg.outboundproxy.name,
16228                      sip_cfg.outboundproxy.force ? "(forced)" : "");
16229    ast_cli(a->fd, "  Session Timers:         %s\n", stmode2str(global_st_mode));
16230    ast_cli(a->fd, "  Session Refresher:      %s\n", strefresher2str (global_st_refresher));
16231    ast_cli(a->fd, "  Session Expires:        %d secs\n", global_max_se);
16232    ast_cli(a->fd, "  Session Min-SE:         %d secs\n", global_min_se);
16233    ast_cli(a->fd, "  Timer T1:               %d\n", global_t1);
16234    ast_cli(a->fd, "  Timer T1 minimum:       %d\n", global_t1min);
16235    ast_cli(a->fd, "  Timer B:                %d\n", global_timer_b);
16236    ast_cli(a->fd, "  No premature media:     %s\n", global_prematuremediafilter ? "Yes" : "No");
16237 
16238    ast_cli(a->fd, "\nDefault Settings:\n");
16239    ast_cli(a->fd, "-----------------\n");
16240    ast_cli(a->fd, "  Allowed transports:     %s\n", get_transport_list(default_transports)); 
16241    ast_cli(a->fd, "  Outbound transport:    %s\n", get_transport(default_primary_transport));
16242    ast_cli(a->fd, "  Context:                %s\n", sip_cfg.default_context);
16243    ast_cli(a->fd, "  Nat:                    %s\n", nat2str(ast_test_flag(&global_flags[0], SIP_NAT)));
16244    ast_cli(a->fd, "  DTMF:                   %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
16245    ast_cli(a->fd, "  Qualify:                %d\n", default_qualify);
16246    ast_cli(a->fd, "  Use ClientCode:         %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_USECLIENTCODE)));
16247    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" );
16248    ast_cli(a->fd, "  Language:               %s\n", default_language);
16249    ast_cli(a->fd, "  MOH Interpret:          %s\n", default_mohinterpret);
16250    ast_cli(a->fd, "  MOH Suggest:            %s\n", default_mohsuggest);
16251    ast_cli(a->fd, "  Voice Mail Extension:   %s\n", default_vmexten);
16252    ast_cli(a->fd, "  Forward Detected Loops: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_FORWARD_LOOP_DETECTED)));
16253    
16254    if (realtimepeers || realtimeregs) {
16255       ast_cli(a->fd, "\nRealtime SIP Settings:\n");
16256       ast_cli(a->fd, "----------------------\n");
16257       ast_cli(a->fd, "  Realtime Peers:         %s\n", cli_yesno(realtimepeers));
16258       ast_cli(a->fd, "  Realtime Regs:          %s\n", cli_yesno(realtimeregs));
16259       ast_cli(a->fd, "  Cache Friends:          %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)));
16260       ast_cli(a->fd, "  Update:                 %s\n", cli_yesno(sip_cfg.peer_rtupdate));
16261       ast_cli(a->fd, "  Ignore Reg. Expire:     %s\n", cli_yesno(sip_cfg.ignore_regexpire));
16262       ast_cli(a->fd, "  Save sys. name:         %s\n", cli_yesno(sip_cfg.rtsave_sysname));
16263       ast_cli(a->fd, "  Auto Clear:             %d\n", sip_cfg.rtautoclear);
16264    }
16265    ast_cli(a->fd, "\n----\n");
16266    return CLI_SUCCESS;
16267 }
16268 
16269 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16270 {
16271 #define FORMAT  "%-30.30s  %-12.12s  %-10.10s  %-10.10s\n"
16272    char host[80];
16273    
16274    switch (cmd) {
16275    case CLI_INIT:
16276       e->command = "sip show mwi";
16277       e->usage =
16278          "Usage: sip show mwi\n"
16279          "       Provides a list of MWI subscriptions and status.\n";
16280       return NULL;
16281    case CLI_GENERATE:
16282       return NULL;
16283    }
16284    
16285    ast_cli(a->fd, FORMAT, "Host", "Username", "Mailbox", "Subscribed");
16286    
16287    ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
16288       ASTOBJ_RDLOCK(iterator);
16289       snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
16290       ast_cli(a->fd, FORMAT, host, iterator->username, iterator->mailbox, iterator->subscribed ? "Yes" : "No");
16291       ASTOBJ_UNLOCK(iterator);
16292    } while(0));
16293 
16294    return CLI_SUCCESS;
16295 #undef FORMAT
16296 }
16297 
16298 
16299 /*! \brief Show subscription type in string format */
16300 static const char *subscription_type2str(enum subscriptiontype subtype)
16301 {
16302    int i;
16303 
16304    for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
16305       if (subscription_types[i].type == subtype) {
16306          return subscription_types[i].text;
16307       }
16308    }
16309    return subscription_types[0].text;
16310 }
16311 
16312 /*! \brief Find subscription type in array */
16313 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
16314 {
16315    int i;
16316 
16317    for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
16318       if (subscription_types[i].type == subtype) {
16319          return &subscription_types[i];
16320       }
16321    }
16322    return &subscription_types[0];
16323 }
16324 
16325 /*
16326  * We try to structure all functions that loop on data structures as
16327  * a handler for individual entries, and a mainloop that iterates
16328  * on the main data structure. This way, moving the code to containers
16329  * that support iteration through callbacks will be a lot easier.
16330  */
16331 
16332 #define FORMAT4 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-13.13s  %-15.15s %-10.10s %-6.6d\n"
16333 #define FORMAT3 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-13.13s  %-15.15s %-10.10s %-6.6s\n"
16334 #define FORMAT2 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-7.7s  %-15.15s %-6.6s\n"
16335 #define FORMAT  "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-3.3s %-3.3s  %-15.15s %-10.10s\n"
16336 
16337 /*! \brief callback for show channel|subscription */
16338 static int show_channels_cb(void *__cur, void *__arg, int flags)
16339 {
16340    struct sip_pvt *cur = __cur;
16341    struct __show_chan_arg *arg = __arg;
16342    const struct sockaddr_in *dst = sip_real_dst(cur);
16343    
16344    /* XXX indentation preserved to reduce diff. Will be fixed later */
16345    if (cur->subscribed == NONE && !arg->subscriptions) {
16346       /* set if SIP transfer in progress */
16347       const char *referstatus = cur->refer ? referstatus2str(cur->refer->status) : "";
16348       char formatbuf[SIPBUFSIZE/2];
16349       
16350       ast_cli(arg->fd, FORMAT, ast_inet_ntoa(dst->sin_addr), 
16351             S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
16352             cur->callid, 
16353             ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0),
16354             cli_yesno(ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD)),
16355             cur->needdestroy ? "(d)" : "",
16356             cur->lastmsg ,
16357             referstatus
16358          );
16359       arg->numchans++;
16360    }
16361    if (cur->subscribed != NONE && arg->subscriptions) {
16362       struct ast_str *mailbox_str = ast_str_alloca(512);
16363       if (cur->subscribed == MWI_NOTIFICATION && cur->relatedpeer)
16364          peer_mailboxes_to_str(&mailbox_str, cur->relatedpeer);
16365       ast_cli(arg->fd, FORMAT4, ast_inet_ntoa(dst->sin_addr),
16366             S_OR(cur->username, S_OR(cur->cid_num, "(None)")), 
16367                cur->callid,
16368             /* the 'complete' exten/context is hidden in the refer_to field for subscriptions */
16369             cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
16370             cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate), 
16371             subscription_type2str(cur->subscribed),
16372             cur->subscribed == MWI_NOTIFICATION ? S_OR(mailbox_str->str, "<none>") : "<none>",
16373             cur->expiry
16374          );
16375       arg->numchans++;
16376    }
16377    return 0;   /* don't care, we scan all channels */
16378 }
16379 
16380 /*! \brief CLI for show channels or subscriptions.
16381  * This is a new-style CLI handler so a single function contains
16382  * the prototype for the function, the 'generator' to produce multiple
16383  * entries in case it is required, and the actual handler for the command.
16384  */
16385 static char *sip_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16386 {
16387    struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
16388 
16389 
16390    if (cmd == CLI_INIT) {
16391       e->command = "sip show {channels|subscriptions}";
16392       e->usage =
16393          "Usage: sip show channels\n"
16394          "       Lists all currently active SIP calls (dialogs).\n"
16395          "Usage: sip show subscriptions\n"
16396          "       Lists active SIP subscriptions.\n";
16397       return NULL;
16398    } else if (cmd == CLI_GENERATE)
16399       return NULL;
16400 
16401    if (a->argc != e->args)
16402       return CLI_SHOWUSAGE;
16403    arg.subscriptions = !strcasecmp(a->argv[e->args - 1], "subscriptions");
16404    if (!arg.subscriptions)
16405       ast_cli(arg.fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Format", "Hold", "Last Message", "Expiry");
16406    else
16407       ast_cli(arg.fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox", "Expiry");
16408 
16409    /* iterate on the container and invoke the callback on each item */
16410    ao2_t_callback(dialogs, OBJ_NODATA, show_channels_cb, &arg, "callback to show channels");
16411    
16412    /* print summary information */
16413    ast_cli(arg.fd, "%d active SIP %s%s\n", arg.numchans,
16414       (arg.subscriptions ? "subscription" : "dialog"),
16415       ESS(arg.numchans));  /* ESS(n) returns an "s" if n>1 */
16416    return CLI_SUCCESS;
16417 #undef FORMAT
16418 #undef FORMAT2
16419 #undef FORMAT3
16420 }
16421 
16422 /*! \brief Support routine for 'sip show channel' and 'sip show history' CLI
16423  * This is in charge of generating all strings that match a prefix in the
16424  * given position. As many functions of this kind, each invokation has
16425  * O(state) time complexity so be careful in using it.
16426  */
16427 static char *complete_sipch(const char *line, const char *word, int pos, int state)
16428 {
16429    int which=0;
16430    struct sip_pvt *cur;
16431    char *c = NULL;
16432    int wordlen = strlen(word);
16433    struct ao2_iterator i;
16434 
16435    if (pos != 3) {
16436       return NULL;
16437    }
16438 
16439    i = ao2_iterator_init(dialogs, 0);
16440    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
16441       sip_pvt_lock(cur);
16442       if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
16443          c = ast_strdup(cur->callid);
16444          sip_pvt_unlock(cur);
16445          dialog_unref(cur, "drop ref in iterator loop break");
16446          break;
16447       }
16448       sip_pvt_unlock(cur);
16449       dialog_unref(cur, "drop ref in iterator loop");
16450    }
16451    ao2_iterator_destroy(&i);
16452    return c;
16453 }
16454 
16455 
16456 /*! \brief Do completion on peer name */
16457 static char *complete_sip_peer(const char *word, int state, int flags2)
16458 {
16459    char *result = NULL;
16460    int wordlen = strlen(word);
16461    int which = 0;
16462    struct ao2_iterator i = ao2_iterator_init(peers, 0);
16463    struct sip_peer *peer;
16464 
16465    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
16466       /* locking of the object is not required because only the name and flags are being compared */
16467       if (!strncasecmp(word, peer->name, wordlen) &&
16468             (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
16469             ++which > state)
16470          result = ast_strdup(peer->name);
16471       unref_peer(peer, "toss iterator peer ptr before break");
16472       if (result) {
16473          break;
16474       }
16475    }
16476    ao2_iterator_destroy(&i);
16477    return result;
16478 }
16479 
16480 /*! \brief Do completion on registered peer name */
16481 static char *complete_sip_registered_peer(const char *word, int state, int flags2)
16482 {
16483        char *result = NULL;
16484        int wordlen = strlen(word);
16485        int which = 0;
16486        struct ao2_iterator i;
16487        struct sip_peer *peer;
16488        
16489        i = ao2_iterator_init(peers, 0);
16490        while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
16491           if (!strncasecmp(word, peer->name, wordlen) &&
16492          (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
16493          ++which > state && peer->expire > 0)
16494              result = ast_strdup(peer->name);
16495           if (result) {
16496              unref_peer(peer, "toss iterator peer ptr before break");
16497              break;
16498           }
16499           unref_peer(peer, "toss iterator peer ptr");
16500        }
16501        ao2_iterator_destroy(&i);
16502        return result;
16503 }
16504 
16505 /*! \brief Support routine for 'sip show history' CLI */
16506 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state)
16507 {
16508    if (pos == 3)
16509       return complete_sipch(line, word, pos, state);
16510 
16511    return NULL;
16512 }
16513 
16514 /*! \brief Support routine for 'sip show peer' CLI */
16515 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
16516 {
16517    if (pos == 3) {
16518       return complete_sip_peer(word, state, 0);
16519    }
16520 
16521    return NULL;
16522 }
16523 
16524 /*! \brief Support routine for 'sip unregister' CLI */
16525 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state)
16526 {
16527        if (pos == 2)
16528                return complete_sip_registered_peer(word, state, 0);
16529 
16530        return NULL;
16531 }
16532 
16533 /*! \brief Support routine for 'sip notify' CLI */
16534 static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
16535 {
16536    char *c = NULL;
16537 
16538    if (pos == 2) {
16539       int which = 0;
16540       char *cat = NULL;
16541       int wordlen = strlen(word);
16542 
16543       /* do completion for notify type */
16544 
16545       if (!notify_types)
16546          return NULL;
16547       
16548       while ( (cat = ast_category_browse(notify_types, cat)) ) {
16549          if (!strncasecmp(word, cat, wordlen) && ++which > state) {
16550             c = ast_strdup(cat);
16551             break;
16552          }
16553       }
16554       return c;
16555    }
16556 
16557    if (pos > 2)
16558       return complete_sip_peer(word, state, 0);
16559 
16560    return NULL;
16561 }
16562 
16563 /*! \brief Show details of one active dialog */
16564 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16565 {
16566    struct sip_pvt *cur;
16567    size_t len;
16568    int found = 0;
16569    struct ao2_iterator i;
16570 
16571    switch (cmd) {
16572    case CLI_INIT:
16573       e->command = "sip show channel";
16574       e->usage =
16575          "Usage: sip show channel <call-id>\n"
16576          "       Provides detailed status on a given SIP dialog (identified by SIP call-id).\n";
16577       return NULL;
16578    case CLI_GENERATE:
16579       return complete_sipch(a->line, a->word, a->pos, a->n);
16580    }
16581 
16582    if (a->argc != 4)
16583       return CLI_SHOWUSAGE;
16584    len = strlen(a->argv[3]);
16585    
16586    i = ao2_iterator_init(dialogs, 0);
16587    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
16588       sip_pvt_lock(cur);
16589 
16590       if (!strncasecmp(cur->callid, a->argv[3], len)) {
16591          char formatbuf[SIPBUFSIZE/2];
16592          ast_cli(a->fd, "\n");
16593          if (cur->subscribed != NONE)
16594             ast_cli(a->fd, "  * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
16595          else
16596             ast_cli(a->fd, "  * SIP Call\n");
16597          ast_cli(a->fd, "  Curr. trans. direction:  %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
16598          ast_cli(a->fd, "  Call-ID:                %s\n", cur->callid);
16599          ast_cli(a->fd, "  Owner channel ID:       %s\n", cur->owner ? cur->owner->name : "<none>");
16600          ast_cli(a->fd, "  Our Codec Capability:   %d\n", cur->capability);
16601          ast_cli(a->fd, "  Non-Codec Capability (DTMF):   %d\n", cur->noncodeccapability);
16602          ast_cli(a->fd, "  Their Codec Capability:   %d\n", cur->peercapability);
16603          ast_cli(a->fd, "  Joint Codec Capability:   %d\n", cur->jointcapability);
16604          ast_cli(a->fd, "  Format:                 %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
16605          ast_cli(a->fd, "  T.38 support            %s\n", cli_yesno(cur->udptl != NULL));
16606          ast_cli(a->fd, "  Video support           %s\n", cli_yesno(cur->vrtp != NULL));
16607          ast_cli(a->fd, "  MaxCallBR:              %d kbps\n", cur->maxcallbitrate);
16608          ast_cli(a->fd, "  Theoretical Address:    %s:%d\n", ast_inet_ntoa(cur->sa.sin_addr), ntohs(cur->sa.sin_port));
16609          ast_cli(a->fd, "  Received Address:       %s:%d\n", ast_inet_ntoa(cur->recv.sin_addr), ntohs(cur->recv.sin_port));
16610          ast_cli(a->fd, "  SIP Transfer mode:      %s\n", transfermode2str(cur->allowtransfer));
16611          ast_cli(a->fd, "  NAT Support:            %s\n", nat2str(ast_test_flag(&cur->flags[0], SIP_NAT)));
16612          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)" );
16613          ast_cli(a->fd, "  Our Tag:                %s\n", cur->tag);
16614          ast_cli(a->fd, "  Their Tag:              %s\n", cur->theirtag);
16615          ast_cli(a->fd, "  SIP User agent:         %s\n", cur->useragent);
16616          if (!ast_strlen_zero(cur->username))
16617             ast_cli(a->fd, "  Username:               %s\n", cur->username);
16618          if (!ast_strlen_zero(cur->peername))
16619             ast_cli(a->fd, "  Peername:               %s\n", cur->peername);
16620          if (!ast_strlen_zero(cur->uri))
16621             ast_cli(a->fd, "  Original uri:           %s\n", cur->uri);
16622          if (!ast_strlen_zero(cur->cid_num))
16623             ast_cli(a->fd, "  Caller-ID:              %s\n", cur->cid_num);
16624          ast_cli(a->fd, "  Need Destroy:           %s\n", cli_yesno(cur->needdestroy));
16625          ast_cli(a->fd, "  Last Message:           %s\n", cur->lastmsg);
16626          ast_cli(a->fd, "  Promiscuous Redir:      %s\n", cli_yesno(ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR)));
16627          ast_cli(a->fd, "  Route:                  %s\n", cur->route ? cur->route->hop : "N/A");
16628          ast_cli(a->fd, "  DTMF Mode:              %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
16629          ast_cli(a->fd, "  SIP Options:            ");
16630          if (cur->sipoptions) {
16631             int x;
16632             for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
16633                if (cur->sipoptions & sip_options[x].id)
16634                   ast_cli(a->fd, "%s ", sip_options[x].text);
16635             }
16636             ast_cli(a->fd, "\n");
16637          } else
16638             ast_cli(a->fd, "(none)\n");
16639 
16640          if (!cur->stimer)
16641             ast_cli(a->fd, "  Session-Timer:          Uninitiallized\n");
16642          else {
16643             ast_cli(a->fd, "  Session-Timer:          %s\n", cur->stimer->st_active ? "Active" : "Inactive");
16644             if (cur->stimer->st_active == TRUE) {
16645                ast_cli(a->fd, "  S-Timer Interval:       %d\n", cur->stimer->st_interval);
16646                ast_cli(a->fd, "  S-Timer Refresher:      %s\n", strefresher2str(cur->stimer->st_ref));
16647                ast_cli(a->fd, "  S-Timer Expirys:        %d\n", cur->stimer->st_expirys);
16648                ast_cli(a->fd, "  S-Timer Sched Id:       %d\n", cur->stimer->st_schedid);
16649                ast_cli(a->fd, "  S-Timer Peer Sts:       %s\n", cur->stimer->st_active_peer_ua ? "Active" : "Inactive");
16650                ast_cli(a->fd, "  S-Timer Cached Min-SE:  %d\n", cur->stimer->st_cached_min_se);
16651                ast_cli(a->fd, "  S-Timer Cached SE:      %d\n", cur->stimer->st_cached_max_se);
16652                ast_cli(a->fd, "  S-Timer Cached Ref:     %s\n", strefresher2str(cur->stimer->st_cached_ref));
16653                ast_cli(a->fd, "  S-Timer Cached Mode:    %s\n", stmode2str(cur->stimer->st_cached_mode));
16654             }
16655          }
16656 
16657          ast_cli(a->fd, "\n\n");
16658 
16659          found++;
16660       }
16661 
16662       sip_pvt_unlock(cur);
16663 
16664       ao2_t_ref(cur, -1, "toss dialog ptr set by iterator_next");
16665    }
16666    ao2_iterator_destroy(&i);
16667 
16668    if (!found) 
16669       ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
16670 
16671    return CLI_SUCCESS;
16672 }
16673 
16674 /*! \brief Show history details of one dialog */
16675 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16676 {
16677    struct sip_pvt *cur;
16678    size_t len;
16679    int found = 0;
16680    struct ao2_iterator i;
16681 
16682    switch (cmd) {
16683    case CLI_INIT:
16684       e->command = "sip show history";
16685       e->usage =
16686          "Usage: sip show history <call-id>\n"
16687          "       Provides detailed dialog history on a given SIP call (specified by call-id).\n";
16688       return NULL;
16689    case CLI_GENERATE:
16690       return complete_sip_show_history(a->line, a->word, a->pos, a->n);
16691    }
16692 
16693    if (a->argc != 4)
16694       return CLI_SHOWUSAGE;
16695 
16696    if (!recordhistory)
16697       ast_cli(a->fd, "\n***Note: History recording is currently DISABLED.  Use 'sip set history on' to ENABLE.\n");
16698 
16699    len = strlen(a->argv[3]);
16700 
16701    i = ao2_iterator_init(dialogs, 0);
16702    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
16703       sip_pvt_lock(cur);
16704       if (!strncasecmp(cur->callid, a->argv[3], len)) {
16705          struct sip_history *hist;
16706          int x = 0;
16707 
16708          ast_cli(a->fd, "\n");
16709          if (cur->subscribed != NONE)
16710             ast_cli(a->fd, "  * Subscription\n");
16711          else
16712             ast_cli(a->fd, "  * SIP Call\n");
16713          if (cur->history)
16714             AST_LIST_TRAVERSE(cur->history, hist, list)
16715                ast_cli(a->fd, "%d. %s\n", ++x, hist->event);
16716          if (x == 0)
16717             ast_cli(a->fd, "Call '%s' has no history\n", cur->callid);
16718          found++;
16719       }
16720       sip_pvt_unlock(cur);
16721       ao2_t_ref(cur, -1, "toss dialog ptr from iterator_next");
16722    }
16723    ao2_iterator_destroy(&i);
16724 
16725    if (!found) 
16726       ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
16727 
16728    return CLI_SUCCESS;
16729 }
16730 
16731 /*! \brief Dump SIP history to debug log file at end of lifespan for SIP dialog */
16732 static void sip_dump_history(struct sip_pvt *dialog)
16733 {
16734    int x = 0;
16735    struct sip_history *hist;
16736    static int errmsg = 0;
16737 
16738    if (!dialog)
16739       return;
16740 
16741    if (!option_debug && !sipdebug) {
16742       if (!errmsg) {
16743          ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
16744          errmsg = 1;
16745       }
16746       return;
16747    }
16748 
16749    ast_debug(1, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
16750    if (dialog->subscribed)
16751       ast_debug(1, "  * Subscription\n");
16752    else
16753       ast_debug(1, "  * SIP Call\n");
16754    if (dialog->history)
16755       AST_LIST_TRAVERSE(dialog->history, hist, list)
16756          ast_debug(1, "  %-3.3d. %s\n", ++x, hist->event);
16757    if (!x)
16758       ast_debug(1, "Call '%s' has no history\n", dialog->callid);
16759    ast_debug(1, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
16760 }
16761 
16762 
16763 /*! \brief  Receive SIP INFO Message */
16764 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
16765 {
16766    char buf[1024];
16767    unsigned int event;
16768    const char *c = get_header(req, "Content-Type");
16769 
16770    /* Need to check the media/type */
16771    if (!strcasecmp(c, "application/dtmf-relay") ||
16772        !strcasecmp(c, "application/vnd.nortelnetworks.digits")) {
16773       unsigned int duration = 0;
16774 
16775       if (!p->owner) {  /* not a PBX call */
16776          transmit_response(p, "481 Call leg/transaction does not exist", req);
16777          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16778          return;
16779       }
16780 
16781       /* Try getting the "signal=" part */
16782       if (ast_strlen_zero(c = get_body(req, "Signal", '=')) && ast_strlen_zero(c = get_body(req, "d", '='))) {
16783          ast_log(LOG_WARNING, "Unable to retrieve DTMF signal from INFO message from %s\n", p->callid);
16784          transmit_response(p, "200 OK", req); /* Should return error */
16785          return;
16786       } else {
16787          ast_copy_string(buf, c, sizeof(buf));
16788       }
16789 
16790       if (!ast_strlen_zero((c = get_body(req, "Duration", '='))))
16791          duration = atoi(c);
16792       if (!duration)
16793          duration = 100; /* 100 ms */
16794 
16795 
16796       if (ast_strlen_zero(buf)) {
16797          transmit_response(p, "200 OK", req);
16798          return;
16799       }
16800 
16801       if (buf[0] == '*')
16802          event = 10;
16803       else if (buf[0] == '#')
16804          event = 11;
16805       else if ((buf[0] >= 'A') && (buf[0] <= 'D'))
16806          event = 12 + buf[0] - 'A';
16807       else if (buf[0] == '!')
16808          event = 16;
16809       else
16810          event = atoi(buf);
16811       if (event == 16) {
16812          /* send a FLASH event */
16813          struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
16814          ast_queue_frame(p->owner, &f);
16815          if (sipdebug)
16816             ast_verbose("* DTMF-relay event received: FLASH\n");
16817       } else {
16818          /* send a DTMF event */
16819          struct ast_frame f = { AST_FRAME_DTMF, };
16820          if (event < 10) {
16821             f.subclass = '0' + event;
16822          } else if (event < 11) {
16823             f.subclass = '*';
16824          } else if (event < 12) {
16825             f.subclass = '#';
16826          } else if (event < 16) {
16827             f.subclass = 'A' + (event - 12);
16828          }
16829          f.len = duration;
16830          ast_queue_frame(p->owner, &f);
16831          if (sipdebug)
16832             ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
16833       }
16834       transmit_response(p, "200 OK", req);
16835       return;
16836    } else if (!strcasecmp(c, "application/dtmf")) {
16837       /*! \todo Note: Doesn't read the duration of the DTMF. Should be fixed. */
16838       unsigned int duration = 0;
16839 
16840       if (!p->owner) {  /* not a PBX call */
16841          transmit_response(p, "481 Call leg/transaction does not exist", req);
16842          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16843          return;
16844       }
16845 
16846       get_msg_text(buf, sizeof(buf), req, TRUE);
16847       duration = 100; /* 100 ms */
16848 
16849       if (ast_strlen_zero(buf)) {
16850          transmit_response(p, "200 OK", req);
16851          return;
16852       }
16853       event = atoi(buf);
16854       if (event == 16) {
16855          /* send a FLASH event */
16856          struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
16857          ast_queue_frame(p->owner, &f);
16858          if (sipdebug)
16859             ast_verbose("* DTMF-relay event received: FLASH\n");
16860       } else {
16861          /* send a DTMF event */
16862          struct ast_frame f = { AST_FRAME_DTMF, };
16863          if (event < 10) {
16864             f.subclass = '0' + event;
16865          } else if (event < 11) {
16866             f.subclass = '*';
16867          } else if (event < 12) {
16868             f.subclass = '#';
16869          } else if (event < 16) {
16870             f.subclass = 'A' + (event - 12);
16871          }
16872          f.len = duration;
16873          ast_queue_frame(p->owner, &f);
16874          if (sipdebug)
16875             ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
16876       }
16877       transmit_response(p, "200 OK", req);
16878       return;
16879 
16880    } else if (!strcasecmp(c, "application/media_control+xml")) {
16881       /* Eh, we'll just assume it's a fast picture update for now */
16882       if (p->owner)
16883          ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
16884       transmit_response(p, "200 OK", req);
16885       return;
16886    } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
16887       /* Client code (from SNOM phone) */
16888       if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
16889          if (p->owner && p->owner->cdr)
16890             ast_cdr_setuserfield(p->owner, c);
16891          if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
16892             ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
16893          transmit_response(p, "200 OK", req);
16894       } else {
16895          transmit_response(p, "403 Forbidden", req);
16896       }
16897       return;
16898    } else if (!ast_strlen_zero(c = get_header(req, "Record"))) {
16899       /* INFO messages generated by some phones to start/stop recording
16900          on phone calls. 
16901          OEJ: I think this should be something that is enabled/disabled
16902          per device. I don't want incoming callers to record calls in my
16903          pbx.
16904       */
16905       /* first, get the feature string, if it exists */
16906       struct ast_call_feature *feat;
16907       int j;
16908       struct ast_frame f = { AST_FRAME_DTMF, };
16909 
16910       ast_rdlock_call_features();
16911       feat = ast_find_call_feature("automon");
16912       if (!feat || ast_strlen_zero(feat->exten)) {
16913          ast_log(LOG_WARNING, "Recording requested, but no One Touch Monitor registered. (See features.conf)\n");
16914          /* 403 means that we don't support this feature, so don't request it again */
16915          transmit_response(p, "403 Forbidden", req);
16916          ast_unlock_call_features();
16917          return;
16918       } 
16919       /* Send the feature code to the PBX as DTMF, just like the handset had sent it */
16920       f.len = 100;
16921       for (j=0; j < strlen(feat->exten); j++) {
16922          f.subclass = feat->exten[j];
16923          ast_queue_frame(p->owner, &f);
16924          if (sipdebug)
16925             ast_verbose("* DTMF-relay event faked: %c\n", f.subclass);
16926       }
16927       ast_unlock_call_features();
16928 
16929       ast_debug(1, "Got a Request to Record the channel, state %s\n", c);
16930       transmit_response(p, "200 OK", req);
16931       return;
16932    } else if (ast_strlen_zero(c = get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
16933       /* This is probably just a packet making sure the signalling is still up, just send back a 200 OK */
16934       transmit_response(p, "200 OK", req);
16935       return;
16936    }
16937 
16938    /* Other type of INFO message, not really understood by Asterisk */
16939    /* if (get_msg_text(buf, sizeof(buf), req)) { */
16940 
16941    ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
16942    transmit_response(p, "415 Unsupported media type", req);
16943    return;
16944 }
16945 
16946 /*! \brief Enable SIP Debugging for a single IP */
16947 static char *sip_do_debug_ip(int fd, char *arg)
16948 {
16949    struct hostent *hp;
16950    struct ast_hostent ahp;
16951    int port = 0;
16952    char *p;
16953 
16954    p = arg;
16955    strsep(&p, ":");
16956    if (p)
16957       port = atoi(p);
16958    hp = ast_gethostbyname(arg, &ahp);
16959    if (hp == NULL)
16960       return CLI_SHOWUSAGE;
16961 
16962    debugaddr.sin_family = AF_INET;
16963    memcpy(&debugaddr.sin_addr, hp->h_addr, sizeof(debugaddr.sin_addr));
16964    debugaddr.sin_port = htons(port);
16965    if (port == 0)
16966       ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_inet_ntoa(debugaddr.sin_addr));
16967    else
16968       ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), port);
16969 
16970    sipdebug |= sip_debug_console;
16971 
16972    return CLI_SUCCESS;
16973 }
16974 
16975 /*! \brief  Turn on SIP debugging for a given peer */
16976 static char *sip_do_debug_peer(int fd, char *arg)
16977 {
16978    struct sip_peer *peer = find_peer(arg, NULL, TRUE, FINDPEERS, FALSE, 0);
16979    if (!peer)
16980       ast_cli(fd, "No such peer '%s'\n", arg);
16981    else if (peer->addr.sin_addr.s_addr == 0)
16982       ast_cli(fd, "Unable to get IP address of peer '%s'\n", arg);
16983    else {
16984       debugaddr.sin_family = AF_INET;
16985       debugaddr.sin_addr = peer->addr.sin_addr;
16986       debugaddr.sin_port = peer->addr.sin_port;
16987       ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n",
16988          ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
16989       sipdebug |= sip_debug_console;
16990    }
16991    if (peer)
16992       unref_peer(peer, "sip_do_debug_peer: unref_peer, from find_peer call");
16993    return CLI_SUCCESS;
16994 }
16995 
16996 /*! \brief Turn on SIP debugging (CLI command) */
16997 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16998 {
16999    int oldsipdebug = sipdebug & sip_debug_console;
17000    char *what;
17001 
17002    if (cmd == CLI_INIT) {
17003       e->command = "sip set debug {on|off|ip|peer}";
17004       e->usage =
17005          "Usage: sip set debug {off|on|ip addr[:port]|peer peername}\n"
17006          "       Globally disables dumping of SIP packets,\n"
17007          "       or enables it either globally or for a (single)\n"
17008          "       IP address or registered peer.\n";
17009       return NULL;
17010    } else if (cmd == CLI_GENERATE) {
17011       if (a->pos == 4 && !strcasecmp(a->argv[3], "peer")) 
17012          return complete_sip_peer(a->word, a->n, 0);
17013       return NULL;
17014         }
17015 
17016    what = a->argv[e->args-1];      /* guaranteed to exist */
17017    if (a->argc == e->args) {       /* on/off */
17018       if (!strcasecmp(what, "on")) {
17019          sipdebug |= sip_debug_console;
17020          sipdebug_text = 1;   /*! \note this can be a special debug command - "sip debug text" or something */
17021          memset(&debugaddr, 0, sizeof(debugaddr));
17022          ast_cli(a->fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
17023          return CLI_SUCCESS;
17024       } else if (!strcasecmp(what, "off")) {
17025          sipdebug &= ~sip_debug_console;
17026          sipdebug_text = 0;
17027          ast_cli(a->fd, "SIP Debugging Disabled\n");
17028          return CLI_SUCCESS;
17029       }
17030    } else if (a->argc == e->args +1) {/* ip/peer */
17031       if (!strcasecmp(what, "ip"))
17032          return sip_do_debug_ip(a->fd, a->argv[e->args]);
17033       else if (!strcasecmp(what, "peer"))
17034          return sip_do_debug_peer(a->fd, a->argv[e->args]);
17035    }
17036    return CLI_SHOWUSAGE;   /* default, failure */
17037 }
17038 
17039 /*! \brief Cli command to send SIP notify to peer */
17040 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17041 {
17042    struct ast_variable *varlist;
17043    int i;
17044 
17045    switch (cmd) {
17046    case CLI_INIT:
17047       e->command = "sip notify";
17048       e->usage =
17049          "Usage: sip notify <type> <peer> [<peer>...]\n"
17050          "       Send a NOTIFY message to a SIP peer or peers\n"
17051          "       Message types are defined in sip_notify.conf\n";
17052       return NULL;
17053    case CLI_GENERATE:
17054       return complete_sipnotify(a->line, a->word, a->pos, a->n);
17055    }
17056 
17057    if (a->argc < 4)
17058       return CLI_SHOWUSAGE;
17059 
17060    if (!notify_types) {
17061       ast_cli(a->fd, "No %s file found, or no types listed there\n", notify_config);
17062       return CLI_FAILURE;
17063    }
17064 
17065    varlist = ast_variable_browse(notify_types, a->argv[2]);
17066 
17067    if (!varlist) {
17068       ast_cli(a->fd, "Unable to find notify type '%s'\n", a->argv[2]);
17069       return CLI_FAILURE;
17070    }
17071 
17072    for (i = 3; i < a->argc; i++) {
17073       struct sip_pvt *p;
17074 
17075       if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
17076          ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
17077          return CLI_FAILURE;
17078       }
17079 
17080       if (create_addr(p, a->argv[i], NULL, 1)) {
17081          /* Maybe they're not registered, etc. */
17082          dialog_unlink_all(p, TRUE, TRUE);
17083          dialog_unref(p, "unref dialog inside for loop" );
17084          /* sip_destroy(p); */
17085          ast_cli(a->fd, "Could not create address for '%s'\n", a->argv[i]);
17086          continue;
17087       }
17088 
17089       /* Notify is outgoing call */
17090       ast_set_flag(&p->flags[0], SIP_OUTGOING);
17091 
17092       /* Recalculate our side, and recalculate Call ID */
17093       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
17094       build_via(p);
17095       ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
17096       build_callid_pvt(p);
17097       ao2_t_link(dialogs, p, "Linking in new name");
17098       ast_cli(a->fd, "Sending NOTIFY of type '%s' to '%s'\n", a->argv[2], a->argv[i]);
17099       dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
17100       sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
17101       transmit_notify_custom(p, varlist);
17102    }
17103 
17104    return CLI_SUCCESS;
17105 }
17106 
17107 /*! \brief Enable/Disable SIP History logging (CLI) */
17108 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17109 {
17110    switch (cmd) {
17111    case CLI_INIT:
17112       e->command = "sip set history {on|off}";
17113       e->usage =
17114          "Usage: sip set history {on|off}\n"
17115          "       Enables/Disables recording of SIP dialog history for debugging purposes.\n"
17116          "       Use 'sip show history' to view the history of a call number.\n";
17117       return NULL;
17118    case CLI_GENERATE:
17119       return NULL;
17120    }
17121 
17122    if (a->argc != e->args)
17123       return CLI_SHOWUSAGE;
17124 
17125    if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
17126       recordhistory = TRUE;
17127       ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
17128    } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
17129       recordhistory = FALSE;
17130       ast_cli(a->fd, "SIP History Recording Disabled\n");
17131    } else {
17132       return CLI_SHOWUSAGE;
17133    }
17134    return CLI_SUCCESS;
17135 }
17136 
17137 /*! \brief Authenticate for outbound registration */
17138 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code)
17139 {
17140    char *header, *respheader;
17141    char digest[1024];
17142 
17143    p->authtries++;
17144    auth_headers(code, &header, &respheader);
17145    memset(digest, 0, sizeof(digest));
17146    if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
17147       /* There's nothing to use for authentication */
17148       /* No digest challenge in request */
17149       if (sip_debug_test_pvt(p) && p->registry)
17150          ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
17151          /* No old challenge */
17152       return -1;
17153    }
17154    if (p->do_history)
17155       append_history(p, "RegistryAuth", "Try: %d", p->authtries);
17156    if (sip_debug_test_pvt(p) && p->registry)
17157       ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
17158    return transmit_register(p->registry, SIP_REGISTER, digest, respheader); 
17159 }
17160 
17161 /*! \brief Add authentication on outbound SIP packet */
17162 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code, int sipmethod, int init)
17163 {
17164    char *header, *respheader;
17165    char digest[1024];
17166 
17167    if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
17168       return -2;
17169 
17170    p->authtries++;
17171    auth_headers(code, &header, &respheader);
17172    ast_debug(2, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
17173    memset(digest, 0, sizeof(digest));
17174    if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
17175       /* No way to authenticate */
17176       return -1;
17177    }
17178    /* Now we have a reply digest */
17179    p->options->auth = digest;
17180    p->options->authheader = respheader;
17181    return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init); 
17182 }
17183 
17184 /*! \brief  reply to authentication for outbound registrations
17185 \return  Returns -1 if we have no auth 
17186 \note This is used for register= servers in sip.conf, SIP proxies we register
17187    with  for receiving calls from.  */
17188 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod,  char *digest, int digest_len)
17189 {
17190    char tmp[512];
17191    char *c;
17192    char oldnonce[256];
17193 
17194    /* table of recognised keywords, and places where they should be copied */
17195    const struct x {
17196       const char *key;
17197       const ast_string_field *field;
17198    } *i, keys[] = {
17199       { "realm=", &p->realm },
17200       { "nonce=", &p->nonce },
17201       { "opaque=", &p->opaque },
17202       { "qop=", &p->qop },
17203       { "domain=", &p->domain },
17204       { NULL, 0 },
17205    };
17206 
17207    ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
17208    if (ast_strlen_zero(tmp)) 
17209       return -1;
17210    if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
17211       ast_log(LOG_WARNING, "missing Digest.\n");
17212       return -1;
17213    }
17214    c = tmp + strlen("Digest ");
17215    ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
17216    while (c && *(c = ast_skip_blanks(c))) {  /* lookup for keys */
17217       for (i = keys; i->key != NULL; i++) {
17218          char *src, *separator;
17219          if (strncasecmp(c, i->key, strlen(i->key)) != 0)
17220             continue;
17221          /* Found. Skip keyword, take text in quotes or up to the separator. */
17222          c += strlen(i->key);
17223          if (*c == '"') {
17224             src = ++c;
17225             separator = "\"";
17226          } else {
17227             src = c;
17228             separator = ",";
17229          }
17230          strsep(&c, separator); /* clear separator and move ptr */
17231          ast_string_field_ptr_set(p, i->field, src);
17232          break;
17233       }
17234       if (i->key == NULL) /* not found, try ',' */
17235          strsep(&c, ",");
17236    }
17237    /* Reset nonce count */
17238    if (strcmp(p->nonce, oldnonce)) 
17239       p->noncecount = 0;
17240 
17241    /* Save auth data for following registrations */
17242    if (p->registry) {
17243       struct sip_registry *r = p->registry;
17244 
17245       if (strcmp(r->nonce, p->nonce)) {
17246          ast_string_field_set(r, realm, p->realm);
17247          ast_string_field_set(r, nonce, p->nonce);
17248          ast_string_field_set(r, domain, p->domain);
17249          ast_string_field_set(r, opaque, p->opaque);
17250          ast_string_field_set(r, qop, p->qop);
17251          r->noncecount = 0;
17252       }
17253    }
17254    return build_reply_digest(p, sipmethod, digest, digest_len); 
17255 }
17256 
17257 /*! \brief  Build reply digest 
17258 \return  Returns -1 if we have no auth 
17259 \note Build digest challenge for authentication of registrations and calls
17260    Also used for authentication of BYE 
17261 */
17262 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
17263 {
17264    char a1[256];
17265    char a2[256];
17266    char a1_hash[256];
17267    char a2_hash[256];
17268    char resp[256];
17269    char resp_hash[256];
17270    char uri[256];
17271    char opaque[256] = "";
17272    char cnonce[80];
17273    const char *username;
17274    const char *secret;
17275    const char *md5secret;
17276    struct sip_auth *auth = NULL; /* Realm authentication */
17277 
17278    if (!ast_strlen_zero(p->domain))
17279       ast_copy_string(uri, p->domain, sizeof(uri));
17280    else if (!ast_strlen_zero(p->uri))
17281       ast_copy_string(uri, p->uri, sizeof(uri));
17282    else
17283       snprintf(uri, sizeof(uri), "sip:%s@%s", p->username, ast_inet_ntoa(p->sa.sin_addr));
17284 
17285    snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
17286 
17287    /* Check if we have separate auth credentials */
17288    if(!(auth = find_realm_authentication(p->peerauth, p->realm))) /* Start with peer list */
17289       auth = find_realm_authentication(authl, p->realm); /* If not, global list */
17290 
17291    if (auth) {
17292       ast_debug(3, "use realm [%s] from peer [%s][%s]\n", auth->username, p->peername, p->username);
17293       username = auth->username;
17294       secret = auth->secret;
17295       md5secret = auth->md5secret;
17296       if (sipdebug)
17297          ast_debug(1, "Using realm %s authentication for call %s\n", p->realm, p->callid);
17298    } else {
17299       /* No authentication, use peer or register= config */
17300       username = p->authname;
17301       secret =  p->peersecret;
17302       md5secret = p->peermd5secret;
17303    }
17304    if (ast_strlen_zero(username))   /* We have no authentication */
17305       return -1;
17306 
17307    /* Calculate SIP digest response */
17308    snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
17309    snprintf(a2, sizeof(a2), "%s:%s", sip_methods[method].text, uri);
17310    if (!ast_strlen_zero(md5secret))
17311       ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
17312    else
17313       ast_md5_hash(a1_hash, a1);
17314    ast_md5_hash(a2_hash, a2);
17315 
17316    p->noncecount++;
17317    if (!ast_strlen_zero(p->qop))
17318       snprintf(resp, sizeof(resp), "%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
17319    else
17320       snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, p->nonce, a2_hash);
17321    ast_md5_hash(resp_hash, resp);
17322 
17323    /* only include the opaque string if it's set */
17324    if (!ast_strlen_zero(p->opaque)) {
17325      snprintf(opaque, sizeof(opaque), ", opaque=\"%s\"", p->opaque);
17326    }
17327 
17328    /* XXX We hard code our qop to "auth" for now.  XXX */
17329    if (!ast_strlen_zero(p->qop))
17330       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);
17331    else
17332       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);
17333 
17334    append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
17335 
17336    return 0;
17337 }
17338    
17339 /*! \brief Read SIP header (dialplan function) */
17340 static int func_header_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len) 
17341 {
17342    struct sip_pvt *p;
17343    const char *content = NULL;
17344    AST_DECLARE_APP_ARGS(args,
17345       AST_APP_ARG(header);
17346       AST_APP_ARG(number);
17347    );
17348    int i, number, start = 0;
17349 
17350    if (ast_strlen_zero(data)) {
17351       ast_log(LOG_WARNING, "This function requires a header name.\n");
17352       return -1;
17353    }
17354 
17355    ast_channel_lock(chan);
17356    if (!IS_SIP_TECH(chan->tech)) {
17357       ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
17358       ast_channel_unlock(chan);
17359       return -1;
17360    }
17361 
17362    AST_STANDARD_APP_ARGS(args, data);
17363    if (!args.number) {
17364       number = 1;
17365    } else {
17366       sscanf(args.number, "%30d", &number);
17367       if (number < 1)
17368          number = 1;
17369    }
17370 
17371    p = chan->tech_pvt;
17372 
17373    /* If there is no private structure, this channel is no longer alive */
17374    if (!p) {
17375       ast_channel_unlock(chan);
17376       return -1;
17377    }
17378 
17379    for (i = 0; i < number; i++)
17380       content = __get_header(&p->initreq, args.header, &start);
17381 
17382    if (ast_strlen_zero(content)) {
17383       ast_channel_unlock(chan);
17384       return -1;
17385    }
17386 
17387    ast_copy_string(buf, content, len);
17388    ast_channel_unlock(chan);
17389 
17390    return 0;
17391 }
17392 
17393 static struct ast_custom_function sip_header_function = {
17394    .name = "SIP_HEADER",
17395    .read = func_header_read,
17396 };
17397 
17398 /*! \brief  Dial plan function to check if domain is local */
17399 static int func_check_sipdomain(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
17400 {
17401    if (ast_strlen_zero(data)) {
17402       ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
17403       return -1;
17404    }
17405    if (check_sip_domain(data, NULL, 0))
17406       ast_copy_string(buf, data, len);
17407    else
17408       buf[0] = '\0';
17409    return 0;
17410 }
17411 
17412 static struct ast_custom_function checksipdomain_function = {
17413    .name = "CHECKSIPDOMAIN",
17414    .read = func_check_sipdomain,
17415 };
17416 
17417 /*! \brief  ${SIPPEER()} Dialplan function - reads peer data */
17418 static int function_sippeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
17419 {
17420    struct sip_peer *peer;
17421    char *colname;
17422 
17423    if ((colname = strchr(data, ':'))) {   /*! \todo Will be deprecated after 1.4 */
17424       static int deprecation_warning = 0;
17425       *colname++ = '\0';
17426       if (deprecation_warning++ % 10 == 0)
17427          ast_log(LOG_WARNING, "SIPPEER(): usage of ':' to separate arguments is deprecated.  Please use ',' instead.\n");
17428    } else if ((colname = strchr(data, ',')))
17429       *colname++ = '\0';
17430    else
17431       colname = "ip";
17432 
17433    if (!(peer = find_peer(data, NULL, TRUE, FINDPEERS, FALSE, 0)))
17434       return -1;
17435 
17436    if (!strcasecmp(colname, "ip")) {
17437       ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len);
17438    } else  if (!strcasecmp(colname, "port")) {
17439       snprintf(buf, len, "%d", ntohs(peer->addr.sin_port));
17440    } else  if (!strcasecmp(colname, "status")) {
17441       peer_status(peer, buf, len);
17442    } else  if (!strcasecmp(colname, "language")) {
17443       ast_copy_string(buf, peer->language, len);
17444    } else  if (!strcasecmp(colname, "regexten")) {
17445       ast_copy_string(buf, peer->regexten, len);
17446    } else  if (!strcasecmp(colname, "limit")) {
17447       snprintf(buf, len, "%d", peer->call_limit);
17448    } else  if (!strcasecmp(colname, "busylevel")) {
17449       snprintf(buf, len, "%d", peer->busy_level);
17450    } else  if (!strcasecmp(colname, "curcalls")) {
17451       snprintf(buf, len, "%d", peer->inUse);
17452    } else  if (!strcasecmp(colname, "accountcode")) {
17453       ast_copy_string(buf, peer->accountcode, len);
17454    } else  if (!strcasecmp(colname, "callgroup")) {
17455       ast_print_group(buf, len, peer->callgroup);
17456    } else  if (!strcasecmp(colname, "pickupgroup")) {
17457       ast_print_group(buf, len, peer->pickupgroup);
17458    } else  if (!strcasecmp(colname, "useragent")) {
17459       ast_copy_string(buf, peer->useragent, len);
17460    } else  if (!strcasecmp(colname, "mailbox")) {
17461       struct ast_str *mailbox_str = ast_str_alloca(512);
17462       peer_mailboxes_to_str(&mailbox_str, peer);
17463       ast_copy_string(buf, mailbox_str->str, len);
17464    } else  if (!strcasecmp(colname, "context")) {
17465       ast_copy_string(buf, peer->context, len);
17466    } else  if (!strcasecmp(colname, "expire")) {
17467       snprintf(buf, len, "%d", peer->expire);
17468    } else  if (!strcasecmp(colname, "dynamic")) {
17469       ast_copy_string(buf, peer->host_dynamic ? "yes" : "no", len);
17470    } else  if (!strcasecmp(colname, "callerid_name")) {
17471       ast_copy_string(buf, peer->cid_name, len);
17472    } else  if (!strcasecmp(colname, "callerid_num")) {
17473       ast_copy_string(buf, peer->cid_num, len);
17474    } else  if (!strcasecmp(colname, "codecs")) {
17475       ast_getformatname_multiple(buf, len -1, peer->capability);
17476    } else  if (!strncasecmp(colname, "chanvar[", 8)) {
17477       char *chanvar=colname + 8;
17478       struct ast_variable *v;
17479    
17480       chanvar = strsep(&chanvar, "]");
17481       for (v = peer->chanvars ; v ; v = v->next) {
17482          if (!strcasecmp(v->name, chanvar)) {
17483             ast_copy_string(buf, v->value, len);
17484          }
17485       }
17486    } else  if (!strncasecmp(colname, "codec[", 6)) {
17487       char *codecnum;
17488       int codec = 0;
17489       
17490       codecnum = colname + 6; /* move past the '[' */
17491       codecnum = strsep(&codecnum, "]"); /* trim trailing ']' if any */
17492       if((codec = ast_codec_pref_index(&peer->prefs, atoi(codecnum)))) {
17493          ast_copy_string(buf, ast_getformatname(codec), len);
17494       } else {
17495          buf[0] = '\0';
17496       }
17497    } else {
17498       buf[0] = '\0';
17499    }
17500 
17501    unref_peer(peer, "unref_peer from function_sippeer, just before return");
17502 
17503    return 0;
17504 }
17505 
17506 /*! \brief Structure to declare a dialplan function: SIPPEER */
17507 static struct ast_custom_function sippeer_function = {
17508    .name = "SIPPEER",
17509    .read = function_sippeer,
17510 };
17511 
17512 /*! \brief ${SIPCHANINFO()} Dialplan function - reads sip channel data */
17513 static int function_sipchaninfo_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
17514 {
17515    struct sip_pvt *p;
17516    static int deprecated = 0;
17517 
17518    *buf = 0;
17519    
17520    if (!data) {
17521       ast_log(LOG_WARNING, "This function requires a parameter name.\n");
17522       return -1;
17523    }
17524 
17525    ast_channel_lock(chan);
17526    if (!IS_SIP_TECH(chan->tech)) {
17527       ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
17528       ast_channel_unlock(chan);
17529       return -1;
17530    }
17531 
17532    if (deprecated++ % 20 == 0) {
17533       /* Deprecated in 1.6.1 */
17534       ast_log(LOG_WARNING, "SIPCHANINFO() is deprecated.  Please transition to using CHANNEL().\n");
17535    }
17536 
17537    p = chan->tech_pvt;
17538 
17539    /* If there is no private structure, this channel is no longer alive */
17540    if (!p) {
17541       ast_channel_unlock(chan);
17542       return -1;
17543    }
17544 
17545    if (!strcasecmp(data, "peerip")) {
17546       ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", len);
17547    } else  if (!strcasecmp(data, "recvip")) {
17548       ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", len);
17549    } else  if (!strcasecmp(data, "from")) {
17550       ast_copy_string(buf, p->from, len);
17551    } else  if (!strcasecmp(data, "uri")) {
17552       ast_copy_string(buf, p->uri, len);
17553    } else  if (!strcasecmp(data, "useragent")) {
17554       ast_copy_string(buf, p->useragent, len);
17555    } else  if (!strcasecmp(data, "peername")) {
17556       ast_copy_string(buf, p->peername, len);
17557    } else if (!strcasecmp(data, "t38passthrough")) {
17558       if (p->t38.state == T38_DISABLED) {
17559          ast_copy_string(buf, "0", len);
17560       } else { /* T38 is offered or enabled in this call */
17561          ast_copy_string(buf, "1", len);
17562       }
17563    } else {
17564       ast_channel_unlock(chan);
17565       return -1;
17566    }
17567    ast_channel_unlock(chan);
17568 
17569    return 0;
17570 }
17571 
17572 /*! \brief Structure to declare a dialplan function: SIPCHANINFO */
17573 static struct ast_custom_function sipchaninfo_function = {
17574    .name = "SIPCHANINFO",
17575    .read = function_sipchaninfo_read,
17576 };
17577 
17578 /*! \brief Parse 302 Moved temporalily response 
17579    \todo XXX Doesn't redirect over TLS on sips: uri's.
17580       If we get a redirect to a SIPS: uri, this needs to be going back to the
17581       dialplan (this is a request for a secure signalling path).
17582       Note that transport=tls is deprecated, but we need to support it on incoming requests.
17583 */
17584 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req)
17585 {
17586    char tmp[SIPBUFSIZE];
17587    char *s, *e, *t, *trans;
17588    char *domain;
17589    enum sip_transport transport = SIP_TRANSPORT_UDP;
17590 
17591    ast_copy_string(tmp, get_header(req, "Contact"), sizeof(tmp));
17592    if ((t = strchr(tmp, ',')))
17593       *t = '\0';
17594 
17595    s = get_in_brackets(tmp);
17596    if ((trans = strcasestr(s, ";transport="))) do {
17597       trans += 11;
17598 
17599       if ((e = strchr(trans, ';')))
17600          *e = '\0';
17601 
17602       if (!strncasecmp(trans, "tcp", 3))
17603          transport = SIP_TRANSPORT_TCP;
17604       else if (!strncasecmp(trans, "tls", 3))
17605          transport = SIP_TRANSPORT_TLS;
17606       else {
17607          if (strncasecmp(trans, "udp", 3))
17608             ast_debug(1, "received contact with an invalid transport, '%s'\n", s);
17609          /* This will assume UDP for all unknown transports */
17610          transport = SIP_TRANSPORT_UDP;
17611       }
17612    } while(0);
17613    s = remove_uri_parameters(s);
17614 
17615    if (p->socket.tcptls_session) {
17616       ao2_ref(p->socket.tcptls_session, -1);
17617       p->socket.tcptls_session = NULL;
17618    }
17619 
17620    set_socket_transport(&p->socket, transport);
17621 
17622    if (ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
17623       char *host = NULL;
17624       if (!strncasecmp(s, "sip:", 4))
17625          s += 4;
17626       else if (!strncasecmp(s, "sips:", 5))
17627          s += 5;
17628       e = strchr(s, '/');
17629       if (e)
17630          *e = '\0';
17631       if ((host = strchr(s, '@'))) {
17632          *host++ = '\0';
17633          ast_debug(2, "Found promiscuous redirection to 'SIP/%s::::%s@%s'\n", s, get_transport(transport), host);
17634          if (p->owner)
17635             ast_string_field_build(p->owner, call_forward, "SIP/%s::::%s@%s", s, get_transport(transport), host);
17636       } else {
17637          ast_debug(2, "Found promiscuous redirection to 'SIP/::::%s@%s'\n", get_transport(transport), s);
17638          if (p->owner)
17639             ast_string_field_build(p->owner, call_forward, "SIP/::::%s@%s", get_transport(transport), s);
17640       }
17641    } else {
17642       e = strchr(tmp, '@');
17643       if (e) {
17644          *e++ = '\0';
17645          domain = e;
17646       } else {
17647          /* No username part */
17648          domain = tmp;
17649       }
17650       e = strchr(tmp, '/');   /* WHEN do we hae a forward slash in the URI? */
17651       if (e)
17652          *e = '\0';
17653 
17654       if (!strncasecmp(s, "sip:", 4))
17655          s += 4;
17656       else if (!strncasecmp(s, "sips:", 5))
17657          s += 5;
17658       e = strchr(s, ';');  /* And username ; parameters? */
17659       if (e)
17660          *e = '\0';  
17661       ast_uri_decode(s);
17662       ast_debug(2, "Received 302 Redirect to extension '%s' (domain %s)\n", s, domain);
17663       if (p->owner) {
17664          pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
17665          ast_string_field_set(p->owner, call_forward, s);
17666       }
17667    }
17668 }
17669 
17670 /*! \brief Check pending actions on SIP call */
17671 static void check_pendings(struct sip_pvt *p)
17672 {
17673    if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
17674       /* if we can't BYE, then this is really a pending CANCEL */
17675       if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA)
17676          transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
17677          /* Actually don't destroy us yet, wait for the 487 on our original 
17678             INVITE, but do set an autodestruct just in case we never get it. */
17679       else {
17680          /* We have a pending outbound invite, don't send something
17681             new in-transaction */
17682          if (p->pendinginvite)
17683             return;
17684 
17685          /* Perhaps there is an SD change INVITE outstanding */
17686          transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
17687       }
17688       ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);   
17689       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17690    } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
17691       /* if we can't REINVITE, hold it for later */
17692       if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
17693          ast_debug(2, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
17694       } else {
17695          ast_debug(2, "Sending pending reinvite on '%s'\n", p->callid);
17696          /* Didn't get to reinvite yet, so do it now */
17697          transmit_reinvite_with_sdp(p, (p->t38.state == T38_LOCAL_REINVITE ? TRUE : FALSE), FALSE);
17698          ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE); 
17699       }
17700    }
17701 }
17702 
17703 /*! \brief Reset the NEEDREINVITE flag after waiting when we get 491 on a Re-invite
17704    to avoid race conditions between asterisk servers.
17705    Called from the scheduler.
17706 */
17707 static int sip_reinvite_retry(const void *data)
17708 {
17709    struct sip_pvt *p = (struct sip_pvt *) data;
17710 
17711    sip_pvt_lock(p); /* called from schedule thread which requires a lock */
17712    ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
17713    p->waitid = -1;
17714    check_pendings(p);
17715    sip_pvt_unlock(p);
17716    dialog_unref(p, "unref the dialog ptr from sip_reinvite_retry, because it held a dialog ptr");
17717    return 0;
17718 }
17719 
17720 
17721 /*! \brief Handle SIP response to INVITE dialogue */
17722 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
17723 {
17724    int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
17725    int res = 0;
17726    int xmitres = 0;
17727    int reinvite = (p->owner && p->owner->_state == AST_STATE_UP);
17728    char *p_hdrval;
17729    int rtn;
17730 
17731    if (reinvite)
17732       ast_debug(4, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
17733    else
17734       ast_debug(4, "SIP response %d to standard invite\n", resp);
17735 
17736    if (p->alreadygone) { /* This call is already gone */
17737       ast_debug(1, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
17738       return;
17739    }
17740 
17741    /* Acknowledge sequence number - This only happens on INVITE from SIP-call */
17742    /* Don't auto congest anymore since we've gotten something useful back */
17743    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"));
17744 
17745    /* RFC3261 says we must treat every 1xx response (but not 100)
17746       that we don't recognize as if it was 183.
17747    */
17748    if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 182 && resp != 183)
17749       resp = 183;
17750 
17751    /* Any response between 100 and 199 is PROCEEDING */
17752    if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING)
17753       p->invitestate = INV_PROCEEDING;
17754  
17755    /* Final response, not 200 ? */
17756    if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA ))
17757       p->invitestate = INV_COMPLETED;
17758    
17759    /* Final response, clear out pending invite */
17760    if ((resp == 200 || resp >= 300) && p->pendinginvite && seqno == p->pendinginvite)
17761       p->pendinginvite = 0;
17762 
17763    switch (resp) {
17764    case 100:   /* Trying */
17765    case 101:   /* Dialog establishment */
17766       if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
17767          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
17768       check_pendings(p);
17769       break;
17770 
17771    case 180:   /* 180 Ringing */
17772    case 182:       /* 182 Queued */
17773       if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
17774          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
17775       if (!req->ignore && p->owner) {
17776          ast_queue_control(p->owner, AST_CONTROL_RINGING);
17777          if (p->owner->_state != AST_STATE_UP) {
17778             ast_setstate(p->owner, AST_STATE_RINGING);
17779          }
17780       }
17781       if (find_sdp(req)) {
17782          if (p->invitestate != INV_CANCELLED)
17783             p->invitestate = INV_EARLY_MEDIA;
17784          res = process_sdp(p, req, SDP_T38_NONE);
17785          if (!req->ignore && p->owner) {
17786             /* Queue a progress frame only if we have SDP in 180 or 182 */
17787             ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
17788          }
17789       }
17790       check_pendings(p);
17791       break;
17792 
17793    case 183:   /* Session progress */
17794       if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
17795          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
17796       if (find_sdp(req)) {
17797          if (p->invitestate != INV_CANCELLED)
17798             p->invitestate = INV_EARLY_MEDIA;
17799          res = process_sdp(p, req, SDP_T38_NONE);
17800          if (!req->ignore && p->owner) {
17801             /* Queue a progress frame */
17802             ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
17803          }
17804       } else {
17805          /* Alcatel PBXs are known to send 183s with no SDP after sending
17806           * a 100 Trying response. We're just going to treat this sort of thing
17807           * the same as we would treat a 180 Ringing
17808           */
17809          if (!req->ignore && p->owner) {
17810             ast_queue_control(p->owner, AST_CONTROL_RINGING);
17811          }
17812       }
17813       check_pendings(p);
17814       break;
17815 
17816    case 200:   /* 200 OK on invite - someone's answering our call */
17817       if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
17818          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
17819       p->authtries = 0;
17820       if (find_sdp(req)) {
17821          if ((res = process_sdp(p, req, SDP_T38_ACCEPT)) && !req->ignore)
17822             if (!reinvite)
17823                /* This 200 OK's SDP is not acceptable, so we need to ack, then hangup */
17824                /* For re-invites, we try to recover */
17825                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
17826       }
17827 
17828       /* Parse contact header for continued conversation */
17829       /* When we get 200 OK, we know which device (and IP) to contact for this call */
17830       /* This is important when we have a SIP proxy between us and the phone */
17831       if (outgoing) {
17832          update_call_counter(p, DEC_CALL_RINGING);
17833          parse_ok_contact(p, req);
17834          /* Save Record-Route for any later requests we make on this dialogue */
17835          if (!reinvite)
17836             build_route(p, req, 1);
17837 
17838          if(set_address_from_contact(p)) {
17839             /* Bad contact - we don't know how to reach this device */
17840             /* We need to ACK, but then send a bye */
17841             if (!p->route && !req->ignore)
17842                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
17843          } 
17844 
17845       }
17846 
17847       if (!req->ignore && p->owner) {
17848          if (!reinvite) {
17849             ast_queue_control(p->owner, AST_CONTROL_ANSWER);
17850             if (sip_cfg.callevents)
17851                manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
17852                   "Channel: %s\r\nChanneltype: %s\r\nUniqueid: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
17853                   p->owner->name, "SIP", p->owner->uniqueid, p->callid, p->fullcontact, p->peername);
17854          } else { /* RE-invite */
17855             ast_queue_frame(p->owner, &ast_null_frame);
17856          }
17857       } else {
17858           /* It's possible we're getting an 200 OK after we've tried to disconnect
17859               by sending CANCEL */
17860          /* First send ACK, then send bye */
17861          if (!req->ignore)
17862             ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
17863       }
17864 
17865       /* Check for Session-Timers related headers */
17866       if (st_get_mode(p) != SESSION_TIMER_MODE_REFUSE && p->outgoing_call == TRUE && !reinvite) {
17867          p_hdrval = (char*)get_header(req, "Session-Expires");
17868             if (!ast_strlen_zero(p_hdrval)) {
17869             /* UAS supports Session-Timers */
17870             enum st_refresher tmp_st_ref = SESSION_TIMER_REFRESHER_AUTO;
17871             int tmp_st_interval = 0;
17872             rtn = parse_session_expires(p_hdrval, &tmp_st_interval, &tmp_st_ref);
17873             if (rtn != 0) {
17874                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
17875             }
17876             if (tmp_st_ref == SESSION_TIMER_REFRESHER_UAC || 
17877                tmp_st_ref == SESSION_TIMER_REFRESHER_UAS) {
17878                p->stimer->st_ref = tmp_st_ref;
17879             } 
17880             if (tmp_st_interval) {
17881                p->stimer->st_interval = tmp_st_interval;
17882             }
17883             p->stimer->st_active = TRUE;
17884             p->stimer->st_active_peer_ua = TRUE;
17885             start_session_timer(p);
17886          } else {
17887             /* UAS doesn't support Session-Timers */
17888             if (st_get_mode(p) == SESSION_TIMER_MODE_ORIGINATE) {
17889                p->stimer->st_ref = SESSION_TIMER_REFRESHER_UAC;
17890                p->stimer->st_active_peer_ua = FALSE;
17891                start_session_timer(p);
17892             }
17893          }
17894       }
17895 
17896 
17897       /* If I understand this right, the branch is different for a non-200 ACK only */
17898       p->invitestate = INV_TERMINATED;
17899       ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
17900       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
17901       check_pendings(p);
17902       break;
17903 
17904    case 407: /* Proxy authentication */
17905    case 401: /* Www auth */
17906       /* First we ACK */
17907       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17908       if (p->options)
17909          p->options->auth_type = resp;
17910 
17911       /* Then we AUTH */
17912       ast_string_field_set(p, theirtag, NULL);  /* forget their old tag, so we don't match tags when getting response */
17913       if (!req->ignore) {
17914          if (p->authtries < MAX_AUTHTRIES)
17915             p->invitestate = INV_CALLING;
17916          if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, SIP_INVITE, 1)) {
17917             ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
17918             pvt_set_needdestroy(p, "failed to authenticate on INVITE");
17919             sip_alreadygone(p);
17920             if (p->owner)
17921                ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17922          }
17923       }
17924       break;
17925 
17926    case 403: /* Forbidden */
17927       /* First we ACK */
17928       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17929       ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
17930       if (!req->ignore && p->owner)
17931          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17932       pvt_set_needdestroy(p, "received 403 response");
17933       sip_alreadygone(p);
17934       break;
17935 
17936    case 404: /* Not found */
17937       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17938       if (p->owner && !req->ignore)
17939          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17940       sip_alreadygone(p);
17941       break;
17942 
17943    case 408: /* Request timeout */
17944    case 481: /* Call leg does not exist */
17945       /* Could be REFER caused INVITE with replaces */
17946       ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
17947       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17948       if (p->owner)
17949          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17950       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17951       break;
17952 
17953    case 422: /* Session-Timers: Session interval too small */
17954       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17955       ast_string_field_set(p, theirtag, NULL);
17956       proc_422_rsp(p, req);
17957       break;
17958 
17959    case 428: /* Use identity header - rfc 4474 - not supported by Asterisk yet */
17960       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17961       append_history(p, "Identity", "SIP identity is required. Not supported by Asterisk.");
17962       ast_log(LOG_WARNING, "SIP identity required by proxy. SIP dialog '%s'. Giving up.\n", p->callid);
17963       if (p->owner)
17964          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17965       break;
17966 
17967       
17968 
17969    case 487: /* Cancelled transaction */
17970       /* We have sent CANCEL on an outbound INVITE 
17971          This transaction is already scheduled to be killed by sip_hangup().
17972       */
17973       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17974       if (p->owner && !req->ignore) {
17975          ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_CLEARING);
17976          append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
17977       } else if (!req->ignore) {
17978          update_call_counter(p, DEC_CALL_LIMIT);
17979          append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
17980          pvt_set_needdestroy(p, "received 487 response");
17981          sip_alreadygone(p);
17982       }
17983       break;
17984    case 415: /* Unsupported media type */
17985    case 488: /* Not acceptable here */
17986    case 606: /* Not Acceptable */
17987       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17988       if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
17989          change_t38_state(p, T38_DISABLED);
17990          /* Try to reset RTP timers */
17991          ast_rtp_set_rtptimers_onhold(p->rtp);
17992 
17993          /* Trigger a reinvite back to audio */
17994          transmit_reinvite_with_sdp(p, FALSE, FALSE);
17995       } else {
17996          /* We can't set up this call, so give up */
17997          if (p->owner && !req->ignore)
17998             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17999          pvt_set_needdestroy(p, "received 488 response");
18000          /* If there's no dialog to end, then mark p as already gone */
18001          if (!reinvite)
18002             sip_alreadygone(p);
18003       }
18004       break;
18005    case 491: /* Pending */
18006       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18007       if (p->owner && !req->ignore) {
18008          if (p->owner->_state != AST_STATE_UP) {
18009             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18010             pvt_set_needdestroy(p, "received 491 response");
18011          } else {
18012             /* This is a re-invite that failed. */
18013             /* Reset the flag after a while 
18014              */
18015             int wait;
18016             /* RFC 3261, if owner of call, wait between 2.1 to 4 seconds,
18017              * if not owner of call, wait 0 to 2 seconds */
18018             if (p->outgoing_call) {
18019                wait = 2100 + ast_random() % 2000;
18020             } else {
18021                wait = ast_random() % 2000;
18022             }
18023             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."));
18024             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);
18025             ast_debug(2, "Reinvite race. Waiting %d secs before retry\n", wait);
18026          }
18027       }
18028       break;
18029 
18030    case 501: /* Not implemented */
18031       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18032       if (p->owner)
18033          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18034       break;
18035    }
18036    if (xmitres == XMIT_ERROR)
18037       ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
18038 }
18039 
18040 /* \brief Handle SIP response in NOTIFY transaction
18041        We've sent a NOTIFY, now handle responses to it
18042   */
18043 static void handle_response_notify(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18044 {
18045    switch (resp) {
18046    case 200:   /* Notify accepted */
18047       /* They got the notify, this is the end */
18048       if (p->owner) {
18049          if (!p->refer) {
18050             ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
18051             ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_UNSPECIFIED);
18052          } else {
18053             ast_debug(4, "Got OK on REFER Notify message\n");
18054          }
18055       } else {
18056          if (p->subscribed == NONE) {
18057             ast_debug(4, "Got 200 accepted on NOTIFY\n");
18058             pvt_set_needdestroy(p, "received 200 response");
18059          }
18060          if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
18061             /* Ready to send the next state we have on queue */
18062             ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
18063             cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
18064          }
18065       }
18066       break;
18067    case 401:   /* Not www-authorized on SIP method */
18068    case 407:   /* Proxy auth */
18069       if (!p->notify_headers) {
18070          break; /* Only device notify can use NOTIFY auth */
18071       }
18072       ast_string_field_set(p, theirtag, NULL);
18073       if (ast_strlen_zero(p->authname)) {
18074          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));
18075          pvt_set_needdestroy(p, "unable to authenticate NOTIFY");
18076       }
18077       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_NOTIFY, 0)) {
18078          ast_log(LOG_NOTICE, "Failed to authenticate on NOTIFY to '%s'\n", get_header(&p->initreq, "From"));
18079          pvt_set_needdestroy(p, "failed to authenticate NOTIFY");
18080       }
18081       break;
18082    }
18083 }
18084 
18085 /* \brief Handle SIP response in SUBSCRIBE transaction */
18086 static void handle_response_subscribe(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18087 {
18088    if (!p->mwi) {
18089       return;
18090    }
18091 
18092    switch (resp) {
18093    case 200: /* Subscription accepted */
18094       ast_debug(3, "Got 200 OK on subscription for MWI\n");
18095       if (p->options) {
18096          ast_free(p->options);
18097          p->options = NULL;
18098       }
18099       p->mwi->subscribed = 1;
18100       if ((p->mwi->resub = ast_sched_add(sched, mwi_expiry * 1000, sip_subscribe_mwi_do, ASTOBJ_REF(p->mwi))) < 0) {
18101          ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18102       }
18103       break;
18104    case 401:
18105    case 407:
18106       ast_string_field_set(p, theirtag, NULL);
18107       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_SUBSCRIBE, 0)) {
18108          ast_log(LOG_NOTICE, "Failed to authenticate on SUBSCRIBE to '%s'\n", get_header(&p->initreq, "From"));
18109          p->mwi->call = NULL;
18110          ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18111          pvt_set_needdestroy(p, "failed to authenticate SUBSCRIBE");
18112       }
18113       break;
18114    case 403:
18115       transmit_response_with_date(p, "200 OK", req);
18116       ast_log(LOG_WARNING, "Authentication failed while trying to subscribe for MWI.\n");
18117       p->mwi->call = NULL;
18118       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18119       pvt_set_needdestroy(p, "received 403 response");
18120       sip_alreadygone(p);
18121       break;
18122    case 404:
18123       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that a mailbox may not have been configured.\n");
18124       p->mwi->call = NULL;
18125       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18126       pvt_set_needdestroy(p, "received 404 response");
18127       break;
18128    case 481:
18129       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that our dialog did not exist.\n");
18130       p->mwi->call = NULL;
18131       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18132       pvt_set_needdestroy(p, "received 481 response");
18133       break;
18134    case 500:
18135    case 501:
18136       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side may have suffered a heart attack.\n");
18137       p->mwi->call = NULL;
18138       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18139       pvt_set_needdestroy(p, "received 500/501 response");
18140       break;
18141    }
18142 }
18143 
18144 /* \brief Handle SIP response in REFER transaction
18145    We've sent a REFER, now handle responses to it 
18146   */
18147 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18148 {
18149    /* If no refer structure exists, then do nothing */
18150    if (!p->refer)
18151       return;
18152 
18153    switch (resp) {
18154    case 202:   /* Transfer accepted */
18155       /* We need  to do something here */
18156       /* The transferee is now sending INVITE to target */
18157       p->refer->status = REFER_ACCEPTED;
18158       /* Now wait for next message */
18159       ast_debug(3, "Got 202 accepted on transfer\n");
18160       /* We should hang along, waiting for NOTIFY's here */
18161       break;
18162 
18163    case 401:   /* Not www-authorized on SIP method */
18164    case 407:   /* Proxy auth */
18165       if (ast_strlen_zero(p->authname)) {
18166          ast_log(LOG_WARNING, "Asked to authenticate REFER to %s:%d but we have no matching peer or realm auth!\n",
18167             ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
18168          pvt_set_needdestroy(p, "unable to authenticate REFER");
18169       }
18170       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_REFER, 0)) {
18171          ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
18172          p->refer->status = REFER_NOAUTH;
18173          pvt_set_needdestroy(p, "failed to authenticat REFER");
18174       }
18175       break;
18176    case 481: /* Call leg does not exist */
18177 
18178       /* A transfer with Replaces did not work */
18179       /* OEJ: We should Set flag, cancel the REFER, go back
18180       to original call - but right now we can't */
18181       ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
18182       if (p->owner)
18183          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18184       pvt_set_needdestroy(p, "received 481 response");
18185       break;
18186 
18187    case 500:   /* Server error */
18188    case 501:   /* Method not implemented */
18189       /* Return to the current call onhold */
18190       /* Status flag needed to be reset */
18191       ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
18192       pvt_set_needdestroy(p, "received 500/501 response");
18193       p->refer->status = REFER_FAILED;
18194       break;
18195    case 603:   /* Transfer declined */
18196       ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
18197       p->refer->status = REFER_FAILED;
18198       pvt_set_needdestroy(p, "received 603 response");
18199       break;
18200    }
18201 }
18202 
18203 /*! \brief Handle responses on REGISTER to services */
18204 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18205 {
18206    int expires, expires_ms;
18207    struct sip_registry *r;
18208    r=p->registry;
18209    
18210    switch (resp) {
18211    case 401:   /* Unauthorized */
18212       if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
18213          ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
18214          pvt_set_needdestroy(p, "failed to authenticate REGISTER");
18215       }
18216       break;
18217    case 403:   /* Forbidden */
18218       ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
18219       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 403"));
18220       r->regstate = REG_STATE_NOAUTH;
18221       pvt_set_needdestroy(p, "received 403 response");
18222       break;
18223    case 404:   /* Not found */
18224       ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username, p->registry->hostname);
18225       pvt_set_needdestroy(p, "received 404 response");
18226       if (r->call)
18227          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 404");
18228       r->regstate = REG_STATE_REJECTED;
18229       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 404"));
18230       break;
18231    case 407:   /* Proxy auth */
18232       if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
18233          ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
18234          pvt_set_needdestroy(p, "failed to authenticate REGISTER");
18235       }
18236       break;
18237    case 408:   /* Request timeout */
18238       /* Got a timeout response, so reset the counter of failed responses */
18239       if (r) {
18240          r->regattempts = 0;
18241       } else {
18242          ast_log(LOG_WARNING, "Got a 408 response to our REGISTER on call %s after we had destroyed the registry object\n", p->callid);
18243       }
18244       break;
18245    case 423:   /* Interval too brief */
18246       r->expiry = atoi(get_header(req, "Min-Expires"));
18247       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);
18248       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 423"));
18249       if (r->call) {
18250          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 423");
18251          pvt_set_needdestroy(p, "received 423 response");
18252       }
18253       if (r->expiry > max_expiry) {
18254          ast_log(LOG_WARNING, "Required expiration time from %s@%s is too high, giving up\n", p->registry->username, p->registry->hostname);
18255          r->expiry = r->configured_expiry;
18256          r->regstate = REG_STATE_REJECTED;
18257       } else {
18258          r->regstate = REG_STATE_UNREGISTERED;
18259          transmit_register(r, SIP_REGISTER, NULL, NULL);
18260       }
18261       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));
18262       break;
18263    case 479:   /* SER: Not able to process the URI - address is wrong in register*/
18264       ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username, p->registry->hostname);
18265       pvt_set_needdestroy(p, "received 479 response");
18266       if (r->call)
18267          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 479");
18268       r->regstate = REG_STATE_REJECTED;
18269       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 479"));
18270       break;
18271    case 200:   /* 200 OK */
18272       if (!r) {
18273          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));
18274          pvt_set_needdestroy(p, "received erroneous 200 response");
18275          return 0;
18276       }
18277       
18278       r->regstate = REG_STATE_REGISTERED;
18279       r->regtime = ast_tvnow();     /* Reset time of last succesful registration */
18280       manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
18281       r->regattempts = 0;
18282       ast_debug(1, "Registration successful\n");
18283       if (r->timeout > -1) {
18284          ast_debug(1, "Cancelling timeout %d\n", r->timeout);
18285       }
18286       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 200"));
18287       if (r->call)
18288          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 200");
18289       p->registry = registry_unref(p->registry, "unref registry entry p->registry");
18290       /* Let this one hang around until we have all the responses */
18291       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18292       /* p->needdestroy = 1; */
18293       
18294       /* set us up for re-registering
18295        * figure out how long we got registered for
18296        * according to section 6.13 of RFC, contact headers override
18297        * expires headers, so check those first */
18298       expires = 0;
18299 
18300       /* XXX todo: try to save the extra call */
18301       if (!ast_strlen_zero(get_header(req, "Contact"))) {
18302          const char *contact = NULL;
18303          const char *tmptmp = NULL;
18304          int start = 0;
18305          for(;;) {
18306             contact = __get_header(req, "Contact", &start);
18307             /* this loop ensures we get a contact header about our register request */
18308             if(!ast_strlen_zero(contact)) {
18309                if( (tmptmp=strstr(contact, p->our_contact))) {
18310                   contact=tmptmp;
18311                   break;
18312                }
18313             } else
18314                break;
18315          }
18316          tmptmp = strcasestr(contact, "expires=");
18317          if (tmptmp) {
18318             if (sscanf(tmptmp + 8, "%30d;", &expires) != 1)
18319                expires = 0;
18320          }
18321          
18322       }
18323       if (!expires) 
18324          expires=atoi(get_header(req, "expires"));
18325       if (!expires)
18326          expires=default_expiry;
18327       
18328       expires_ms = expires * 1000;
18329       if (expires <= EXPIRY_GUARD_LIMIT)
18330          expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT), EXPIRY_GUARD_MIN);
18331       else
18332          expires_ms -= EXPIRY_GUARD_SECS * 1000;
18333       if (sipdebug)
18334          ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000); 
18335       
18336       r->refresh= (int) expires_ms / 1000;
18337       
18338       /* Schedule re-registration before we expire */
18339       AST_SCHED_REPLACE_UNREF(r->expire, sched, expires_ms, sip_reregister, r, 
18340                         registry_unref(_data,"unref in REPLACE del fail"), 
18341                         registry_unref(r,"unref in REPLACE add fail"), 
18342                         registry_addref(r,"The Addition side of REPLACE")); 
18343    }
18344    return 1;
18345 }
18346 
18347 /*! \brief Handle qualification responses (OPTIONS) */
18348 static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
18349 {
18350    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! */
18351    int statechanged, is_reachable, was_reachable;
18352    int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
18353 
18354    /*
18355     * Compute the response time to a ping (goes in peer->lastms.)
18356     * -1 means did not respond, 0 means unknown,
18357     * 1..maxms is a valid response, >maxms means late response.
18358     */
18359    if (pingtime < 1) /* zero = unknown, so round up to 1 */
18360       pingtime = 1;
18361 
18362    /* Now determine new state and whether it has changed.
18363     * Use some helper variables to simplify the writing
18364     * of the expressions.
18365     */
18366    was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
18367    is_reachable = pingtime <= peer->maxms;
18368    statechanged = peer->lastms == 0 /* yes, unknown before */
18369       || was_reachable != is_reachable;
18370 
18371    peer->lastms = pingtime;
18372    peer->call = dialog_unref(peer->call, "unref dialog peer->call");
18373    if (statechanged) {
18374       const char *s = is_reachable ? "Reachable" : "Lagged";
18375       char str_lastms[20];
18376       snprintf(str_lastms, sizeof(str_lastms), "%d", pingtime);
18377 
18378       ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
18379          peer->name, s, pingtime, peer->maxms);
18380       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
18381       if (sip_cfg.peer_rtupdate) {
18382          ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", str_lastms, SENTINEL);
18383       }
18384       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
18385          "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
18386          peer->name, s, pingtime);
18387       if (is_reachable && sip_cfg.regextenonqualify)
18388          register_peer_exten(peer, TRUE);
18389    }
18390 
18391    pvt_set_needdestroy(p, "got OPTIONS response");
18392 
18393    /* Try again eventually */
18394    AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
18395          is_reachable ? peer->qualifyfreq : DEFAULT_FREQ_NOTOK,
18396          sip_poke_peer_s, peer,
18397          unref_peer(_data, "removing poke peer ref"),
18398          unref_peer(peer, "removing poke peer ref"),
18399          ref_peer(peer, "adding poke peer ref"));
18400 }
18401 
18402 /*! \brief Immediately stop RTP, VRTP and UDPTL as applicable */
18403 static void stop_media_flows(struct sip_pvt *p)
18404 {
18405    /* Immediately stop RTP, VRTP and UDPTL as applicable */
18406    if (p->rtp)
18407       ast_rtp_stop(p->rtp);
18408    if (p->vrtp)
18409       ast_rtp_stop(p->vrtp);
18410    if (p->trtp)
18411       ast_rtp_stop(p->trtp);
18412    if (p->udptl)
18413       ast_udptl_stop(p->udptl);
18414 }
18415 
18416 /*! \brief Handle SIP response in dialogue
18417    \note only called by handle_incoming */
18418 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18419 {
18420    struct ast_channel *owner;
18421    int sipmethod;
18422    int res = 1;
18423    const char *c = get_header(req, "Cseq");
18424    /* 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 */
18425    char *c_copy = ast_strdupa(c);
18426    /* Skip the Cseq and its subsequent spaces */
18427    const char *msg = ast_skip_blanks(ast_skip_nonblanks(c_copy));
18428 
18429    if (!msg)
18430       msg = "";
18431 
18432    sipmethod = find_sip_method(msg);
18433 
18434    owner = p->owner;
18435    if (owner) 
18436       owner->hangupcause = hangup_sip2cause(resp);
18437 
18438    if (p->socket.type == SIP_TRANSPORT_UDP) {
18439       int ack_res;
18440 
18441       /* Acknowledge whatever it is destined for */
18442       if ((resp >= 100) && (resp <= 199)) {
18443          ack_res = __sip_semi_ack(p, seqno, 0, sipmethod);
18444       } else {
18445          ack_res = __sip_ack(p, seqno, 0, sipmethod);
18446       }
18447 
18448       if (ack_res == FALSE) {
18449          append_history(p, "Ignore", "Ignoring this retransmit\n");
18450          return;
18451       }
18452    }
18453 
18454    /* If this is a NOTIFY for a subscription clear the flag that indicates that we have a NOTIFY pending */
18455    if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite) 
18456       p->pendinginvite = 0;
18457 
18458    /* Get their tag if we haven't already */
18459    if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
18460       char tag[128];
18461 
18462       gettag(req, "To", tag, sizeof(tag));
18463       ast_string_field_set(p, theirtag, tag);
18464    }
18465    /* This needs to be configurable on a channel/peer level,
18466       not mandatory for all communication. Sadly enough, NAT implementations
18467       are not so stable so we can always rely on these headers. 
18468       Temporarily disabled, while waiting for fix.
18469       Fix assigned to Rizzo :-)
18470    */
18471    /* check_via_response(p, req); */
18472 
18473    /* RFC 3261 Section 15 specifies that if we receive a 408 or 481
18474     * in response to a BYE, then we should end the current dialog
18475     * and session.  It is known that at least one phone manufacturer
18476     * potentially will send a 404 in response to a BYE, so we'll be
18477     * liberal in what we accept and end the dialog and session if we
18478     * receive any of those responses to a BYE.
18479     */
18480    if ((resp == 404 || resp == 408 || resp == 481) && sipmethod == SIP_BYE) {
18481       pvt_set_needdestroy(p, "received 4XX response to a BYE");
18482       return;
18483    }
18484 
18485    if (p->relatedpeer && p->method == SIP_OPTIONS) {
18486       /* We don't really care what the response is, just that it replied back. 
18487          Well, as long as it's not a 100 response...  since we might
18488          need to hang around for something more "definitive" */
18489       if (resp != 100)
18490          handle_response_peerpoke(p, resp, req);
18491    } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
18492       switch(resp) {
18493       case 100:   /* 100 Trying */
18494       case 101:   /* 101 Dialog establishment */
18495       case 183:   /* 183 Session Progress */
18496       case 180:   /* 180 Ringing */
18497       case 182:   /* 182 Queued */
18498          if (sipmethod == SIP_INVITE)
18499             handle_response_invite(p, resp, rest, req, seqno);
18500          break;
18501       case 200:   /* 200 OK */
18502          p->authtries = 0; /* Reset authentication counter */
18503          if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
18504             /* We successfully transmitted a message 
18505                or a video update request in INFO */
18506             /* Nothing happens here - the message is inside a dialog */
18507          } else if (sipmethod == SIP_INVITE) {
18508             handle_response_invite(p, resp, rest, req, seqno);
18509          } else if (sipmethod == SIP_NOTIFY) {
18510             handle_response_notify(p, resp, rest, req, seqno);
18511          } else if (sipmethod == SIP_REGISTER) {
18512             res = handle_response_register(p, resp, rest, req, seqno);
18513          } else if (sipmethod == SIP_SUBSCRIBE) {
18514             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
18515             handle_response_subscribe(p, resp, rest, req, seqno);
18516          } else if (sipmethod == SIP_BYE) {     /* Ok, we're ready to go */
18517             pvt_set_needdestroy(p, "received 200 response");
18518             ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
18519          }
18520          break;
18521       case 202:   /* Transfer accepted */
18522          if (sipmethod == SIP_REFER) 
18523             handle_response_refer(p, resp, rest, req, seqno);
18524          break;
18525       case 401: /* Not www-authorized on SIP method */
18526       case 407: /* Proxy auth required */
18527          if (sipmethod == SIP_INVITE)
18528             handle_response_invite(p, resp, rest, req, seqno);
18529          else if (sipmethod == SIP_NOTIFY)
18530             handle_response_notify(p, resp, rest, req, seqno);
18531          else if (sipmethod == SIP_REFER)
18532             handle_response_refer(p, resp, rest, req, seqno);
18533          else if (sipmethod == SIP_SUBSCRIBE)
18534             handle_response_subscribe(p, resp, rest, req, seqno);
18535          else if (p->registry && sipmethod == SIP_REGISTER)
18536             res = handle_response_register(p, resp, rest, req, seqno);
18537          else if (sipmethod == SIP_BYE) {
18538             if (p->options)
18539                p->options->auth_type = resp;
18540             if (ast_strlen_zero(p->authname)) {
18541                ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
18542                      msg, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
18543                pvt_set_needdestroy(p, "unable to authenticate BYE");
18544             } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp,  sipmethod, 0)) {
18545                ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
18546                pvt_set_needdestroy(p, "failed to authenticate BYE");
18547             }
18548          } else {
18549             ast_log(LOG_WARNING, "Got authentication request (%d) on %s to '%s'\n", resp, sip_methods[sipmethod].text, get_header(req, "To"));
18550             pvt_set_needdestroy(p, "received 407 response");
18551          }
18552          break;
18553       case 403: /* Forbidden - we failed authentication */
18554          if (sipmethod == SIP_INVITE)
18555             handle_response_invite(p, resp, rest, req, seqno);
18556          else if (sipmethod == SIP_SUBSCRIBE)
18557             handle_response_subscribe(p, resp, rest, req, seqno);
18558          else if (p->registry && sipmethod == SIP_REGISTER) 
18559             res = handle_response_register(p, resp, rest, req, seqno);
18560          else {
18561             ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
18562             pvt_set_needdestroy(p, "received 403 response");
18563          }
18564          break;
18565       case 404: /* Not found */
18566          if (p->registry && sipmethod == SIP_REGISTER)
18567             res = handle_response_register(p, resp, rest, req, seqno);
18568          else if (sipmethod == SIP_INVITE)
18569             handle_response_invite(p, resp, rest, req, seqno);
18570          else if (sipmethod == SIP_SUBSCRIBE)
18571             handle_response_subscribe(p, resp, rest, req, seqno);
18572          else if (owner)
18573             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18574          break;
18575       case 423: /* Interval too brief */
18576          if (sipmethod == SIP_REGISTER)
18577             res = handle_response_register(p, resp, rest, req, seqno);
18578          break;
18579       case 408: /* Request timeout - terminate dialog */
18580          if (sipmethod == SIP_INVITE)
18581             handle_response_invite(p, resp, rest, req, seqno);
18582          else if (sipmethod == SIP_REGISTER) 
18583             res = handle_response_register(p, resp, rest, req, seqno);
18584          else if (sipmethod == SIP_BYE) {
18585             pvt_set_needdestroy(p, "received 408 response");
18586             ast_debug(4, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
18587          } else {
18588             if (owner)
18589                ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18590             pvt_set_needdestroy(p, "received 408 response");
18591          }
18592          break;
18593 
18594       case 422: /* Session-Timers: Session Interval Too Small */
18595          if (sipmethod == SIP_INVITE) {
18596             handle_response_invite(p, resp, rest, req, seqno);
18597          }
18598          break;
18599 
18600       case 481: /* Call leg does not exist */
18601          if (sipmethod == SIP_INVITE) {
18602             handle_response_invite(p, resp, rest, req, seqno);
18603          } else if (sipmethod == SIP_REFER) {
18604             handle_response_refer(p, resp, rest, req, seqno);
18605          } else if (sipmethod == SIP_SUBSCRIBE) {
18606             handle_response_subscribe(p, resp, rest, req, seqno);
18607          } else if (sipmethod == SIP_BYE) {
18608             /* The other side has no transaction to bye,
18609             just assume it's all right then */
18610             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
18611          } else if (sipmethod == SIP_CANCEL) {
18612             /* The other side has no transaction to cancel,
18613             just assume it's all right then */
18614             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
18615          } else {
18616             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
18617             /* Guessing that this is not an important request */
18618          }
18619          break;
18620       case 487:
18621          if (sipmethod == SIP_INVITE)
18622             handle_response_invite(p, resp, rest, req, seqno);
18623          break;
18624       case 415: /* Unsupported media type */
18625       case 488: /* Not acceptable here - codec error */
18626       case 606: /* Not Acceptable */
18627          if (sipmethod == SIP_INVITE)
18628             handle_response_invite(p, resp, rest, req, seqno);
18629          break;
18630       case 491: /* Pending */
18631          if (sipmethod == SIP_INVITE)
18632             handle_response_invite(p, resp, rest, req, seqno);
18633          else {
18634             ast_debug(1, "Got 491 on %s, unsupported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
18635             pvt_set_needdestroy(p, "received 491 response");
18636          }
18637          break;
18638       case 501: /* Not Implemented */
18639          if (sipmethod == SIP_INVITE)
18640             handle_response_invite(p, resp, rest, req, seqno);
18641          else if (sipmethod == SIP_REFER)
18642             handle_response_refer(p, resp, rest, req, seqno);
18643          else
18644             ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_inet_ntoa(p->sa.sin_addr), msg);
18645          break;
18646       case 603:   /* Declined transfer */
18647          if (sipmethod == SIP_REFER) {
18648             handle_response_refer(p, resp, rest, req, seqno);
18649             break;
18650          }
18651          /* Fallthrough */
18652       default:
18653          if ((resp >= 300) && (resp < 700)) {
18654             /* Fatal response */
18655             if ((resp != 487))
18656                ast_verb(3, "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
18657    
18658             if (sipmethod == SIP_INVITE)
18659                stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
18660 
18661             /* XXX Locking issues?? XXX */
18662             switch(resp) {
18663             case 300: /* Multiple Choices */
18664             case 301: /* Moved permanently */
18665             case 302: /* Moved temporarily */
18666             case 305: /* Use Proxy */
18667                parse_moved_contact(p, req);
18668                /* Fall through */
18669             case 486: /* Busy here */
18670             case 600: /* Busy everywhere */
18671             case 603: /* Decline */
18672                if (p->owner)
18673                   ast_queue_control(p->owner, AST_CONTROL_BUSY);
18674                break;
18675             case 482: /* Loop Detected */
18676                /*
18677                   \note Asterisk has historically tried to do a call forward when it
18678                   gets a 482, but that behavior isn't necessarily the best course of
18679                   action. Go ahead and do it anyway by default, but allow the option
18680                   to immediately pass to the next line in the dialplan. */
18681                if (p->owner && ast_test_flag(&p->flags[1], SIP_PAGE2_FORWARD_LOOP_DETECTED)) {
18682                      ast_debug(1, "Hairpin detected, setting up call forward for what it's worth\n");
18683                      ast_string_field_build(p->owner, call_forward,
18684                            "Local/%s@%s", p->username, p->context);
18685                }
18686                /* Fall through */
18687             case 480: /* Temporarily Unavailable */
18688             case 404: /* Not Found */
18689             case 410: /* Gone */
18690             case 400: /* Bad Request */
18691             case 500: /* Server error */
18692                if (sipmethod == SIP_REFER) {
18693                   handle_response_refer(p, resp, rest, req, seqno);
18694                   break;
18695                } else if (sipmethod == SIP_SUBSCRIBE) {
18696                   handle_response_subscribe(p, resp, rest, req, seqno);
18697                   break;
18698                }
18699                /* Fall through */
18700             case 502: /* Bad gateway */
18701             case 503: /* Service Unavailable */
18702             case 504: /* Server Timeout */
18703                if (owner)
18704                   ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18705                break;
18706             default:
18707                /* Send hangup */ 
18708                if (owner && sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO && sipmethod != SIP_BYE)
18709                   ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
18710                break;
18711             }
18712             /* ACK on invite */
18713             if (sipmethod == SIP_INVITE) 
18714                transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18715             if (sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO) 
18716                sip_alreadygone(p);
18717             if (!p->owner) {
18718                pvt_set_needdestroy(p, "transaction completed");
18719             }
18720          } else if ((resp >= 100) && (resp < 200)) {
18721             if (sipmethod == SIP_INVITE) {
18722                if (!req->ignore && sip_cancel_destroy(p))
18723                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
18724                if (find_sdp(req))
18725                   process_sdp(p, req, SDP_T38_NONE);
18726                if (p->owner) {
18727                   /* Queue a progress frame */
18728                   ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
18729                }
18730             }
18731          } else
18732             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));
18733       }
18734    } else { 
18735       /* Responses to OUTGOING SIP requests on INCOMING calls 
18736          get handled here. As well as out-of-call message responses */
18737       if (req->debug)
18738          ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
18739 
18740       if (sipmethod == SIP_INVITE && resp == 200) {
18741          /* Tags in early session is replaced by the tag in 200 OK, which is 
18742          the final reply to our INVITE */
18743          char tag[128];
18744 
18745          gettag(req, "To", tag, sizeof(tag));
18746          ast_string_field_set(p, theirtag, tag);
18747       }
18748 
18749       switch(resp) {
18750       case 200:
18751          if (sipmethod == SIP_INVITE) {
18752             handle_response_invite(p, resp, rest, req, seqno);
18753          } else if (sipmethod == SIP_CANCEL) {
18754             ast_debug(1, "Got 200 OK on CANCEL\n");
18755 
18756             /* Wait for 487, then destroy */
18757          } else if (sipmethod == SIP_NOTIFY) {
18758             /* They got the notify, this is the end */
18759             if (p->owner) {
18760                if (p->refer) {
18761                   ast_debug(1, "Got 200 OK on NOTIFY for transfer\n");
18762                } else
18763                   ast_log(LOG_WARNING, "Notify answer on an owned channel?\n");
18764                /* ast_queue_hangup(p->owner); Disabled */
18765             } else {
18766                if (!p->subscribed && !p->refer) {
18767                   pvt_set_needdestroy(p, "transaction completed");
18768                }
18769                if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
18770                   /* Ready to send the next state we have on queue */
18771                   ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
18772                   cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
18773                }
18774             }
18775          } else if (sipmethod == SIP_BYE) {
18776             pvt_set_needdestroy(p, "transaction completed");
18777          } else if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
18778             /* We successfully transmitted a message or
18779                a video update request in INFO */
18780             ;
18781          }
18782          break;
18783       case 202:   /* Transfer accepted */
18784          if (sipmethod == SIP_REFER) 
18785             handle_response_refer(p, resp, rest, req, seqno);
18786          break;
18787       case 401:   /* www-auth */
18788       case 407:
18789          if (sipmethod == SIP_REFER)
18790             handle_response_refer(p, resp, rest, req, seqno);
18791          else if (sipmethod == SIP_INVITE) 
18792             handle_response_invite(p, resp, rest, req, seqno);
18793          else if (sipmethod == SIP_BYE) {
18794             if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, sipmethod, 0)) {
18795                ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
18796                pvt_set_needdestroy(p, "failed to authenticate BYE");
18797             }
18798          }
18799          break;
18800       case 481:   /* Call leg does not exist */
18801          if (sipmethod == SIP_INVITE) {
18802             /* Re-invite failed */
18803             handle_response_invite(p, resp, rest, req, seqno);
18804          } else if (sipmethod == SIP_BYE) {
18805             pvt_set_needdestroy(p, "received 481 response");
18806          } else if (sipdebug) {
18807             ast_debug(1, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
18808          }
18809          break;
18810       case 501: /* Not Implemented */
18811          if (sipmethod == SIP_INVITE) 
18812             handle_response_invite(p, resp, rest, req, seqno);
18813          else if (sipmethod == SIP_REFER) 
18814             handle_response_refer(p, resp, rest, req, seqno);
18815          break;
18816       case 603:   /* Declined transfer */
18817          if (sipmethod == SIP_REFER) {
18818             handle_response_refer(p, resp, rest, req, seqno);
18819             break;
18820          }
18821          /* Fallthrough */
18822       default: /* Errors without handlers */
18823          if ((resp >= 100) && (resp < 200)) {
18824             if (sipmethod == SIP_INVITE) {   /* re-invite */
18825                if (!req->ignore && sip_cancel_destroy(p))
18826                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
18827             }
18828          }
18829          if ((resp >= 300) && (resp < 700)) {
18830             if ((resp != 487))
18831                ast_verb(3, "Incoming call: Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
18832             switch(resp) {
18833             case 415: /* Unsupported media type */
18834             case 488: /* Not acceptable here - codec error */
18835             case 603: /* Decline */
18836             case 500: /* Server error */
18837             case 502: /* Bad gateway */
18838             case 503: /* Service Unavailable */
18839             case 504: /* Server timeout */
18840 
18841                /* re-invite failed */
18842                if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
18843                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
18844                break;
18845             }
18846          }
18847          break;
18848       }
18849    }
18850 }
18851 
18852 
18853 /*! \brief Park SIP call support function 
18854    Starts in a new thread, then parks the call
18855    XXX Should we add a wait period after streaming audio and before hangup?? Sometimes the
18856       audio can't be heard before hangup
18857 */
18858 static void *sip_park_thread(void *stuff)
18859 {
18860    struct ast_channel *transferee, *transferer; /* Chan1: The transferee, Chan2: The transferer */
18861    struct sip_dual *d;
18862    struct sip_request req = {0,};
18863    int ext;
18864    int res;
18865 
18866    d = stuff;
18867    transferee = d->chan1;
18868    transferer = d->chan2;
18869    copy_request(&req, &d->req);
18870 
18871    if (!transferee || !transferer) {
18872       ast_log(LOG_ERROR, "Missing channels for parking! Transferer %s Transferee %s\n", transferer ? "<available>" : "<missing>", transferee ? "<available>" : "<missing>" );
18873       deinit_req(&d->req);
18874       free(d);
18875       return NULL;
18876    }
18877    ast_debug(4, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);
18878 
18879    ast_channel_lock(transferee);
18880    if (ast_do_masquerade(transferee)) {
18881       ast_log(LOG_WARNING, "Masquerade failed.\n");
18882       transmit_response(transferer->tech_pvt, "503 Internal error", &req);
18883       ast_channel_unlock(transferee);
18884       deinit_req(&d->req);
18885       free(d);
18886       return NULL;
18887    } 
18888    ast_channel_unlock(transferee);
18889 
18890    res = ast_park_call(transferee, transferer, 0, &ext);
18891    
18892 
18893 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
18894    if (!res) {
18895       transmit_message_with_text(transferer->tech_pvt, "Unable to park call.\n");
18896    } else {
18897       /* Then tell the transferer what happened */
18898       sprintf(buf, "Call parked on extension '%d'", ext);
18899       transmit_message_with_text(transferer->tech_pvt, buf);
18900    }
18901 #endif
18902 
18903    /* Any way back to the current call??? */
18904    /* Transmit response to the REFER request */
18905    transmit_response(transferer->tech_pvt, "202 Accepted", &req);
18906    if (!res)   {
18907       /* Transfer succeeded */
18908       append_history(transferer->tech_pvt, "SIPpark", "Parked call on %d", ext);
18909       transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "200 OK", TRUE);
18910       transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
18911       ast_hangup(transferer); /* This will cause a BYE */
18912       ast_debug(1, "SIP Call parked on extension '%d'\n", ext);
18913    } else {
18914       transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "503 Service Unavailable", TRUE);
18915       append_history(transferer->tech_pvt, "SIPpark", "Parking failed\n");
18916       ast_debug(1, "SIP Call parked failed \n");
18917       /* Do not hangup call */
18918    }
18919    deinit_req(&d->req);
18920    free(d);
18921    return NULL;
18922 }
18923 
18924 /*! \brief Park a call using the subsystem in res_features.c 
18925    This is executed in a separate thread
18926 */
18927 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno)
18928 {
18929    struct sip_dual *d;
18930    struct ast_channel *transferee, *transferer;
18931       /* Chan2m: The transferer, chan1m: The transferee */
18932    pthread_t th;
18933 
18934    transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan1->accountcode, chan1->exten, chan1->context, chan1->amaflags, "Parking/%s", chan1->name);
18935    transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->amaflags, "SIPPeer/%s", chan2->name);
18936    if ((!transferer) || (!transferee)) {
18937       if (transferee) {
18938          transferee->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
18939          ast_hangup(transferee);
18940       }
18941       if (transferer) {
18942          transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
18943          ast_hangup(transferer);
18944       }
18945       return -1;
18946    }
18947 
18948    /* Make formats okay */
18949    transferee->readformat = chan1->readformat;
18950    transferee->writeformat = chan1->writeformat;
18951 
18952    /* Prepare for taking over the channel */
18953    ast_channel_masquerade(transferee, chan1);
18954 
18955    /* Setup the extensions and such */
18956    ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
18957    ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
18958    transferee->priority = chan1->priority;
18959       
18960    /* We make a clone of the peer channel too, so we can play
18961       back the announcement */
18962 
18963    /* Make formats okay */
18964    transferer->readformat = chan2->readformat;
18965    transferer->writeformat = chan2->writeformat;
18966    if (!ast_strlen_zero(chan2->parkinglot))
18967       ast_string_field_set(transferer, parkinglot, chan2->parkinglot);
18968 
18969    /* Prepare for taking over the channel.  Go ahead and grab this channel
18970     * lock here to avoid a deadlock with callbacks into the channel driver
18971     * that hold the channel lock and want the pvt lock.  */
18972    while (ast_channel_trylock(chan2)) {
18973       struct sip_pvt *pvt = chan2->tech_pvt;
18974       sip_pvt_unlock(pvt);
18975       usleep(1);
18976       sip_pvt_lock(pvt);
18977    }
18978    ast_channel_masquerade(transferer, chan2);
18979    ast_channel_unlock(chan2);
18980 
18981    /* Setup the extensions and such */
18982    ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
18983    ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
18984    transferer->priority = chan2->priority;
18985 
18986    ast_channel_lock(transferer);
18987    if (ast_do_masquerade(transferer)) {
18988       ast_log(LOG_WARNING, "Masquerade failed :(\n");
18989       ast_channel_unlock(transferer);
18990       transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
18991       ast_hangup(transferer);
18992       return -1;
18993    }
18994    ast_channel_unlock(transferer);
18995    if (!transferer || !transferee) {
18996       if (!transferer) { 
18997          ast_debug(1, "No transferer channel, giving up parking\n");
18998       }
18999       if (!transferee) {
19000          ast_debug(1, "No transferee channel, giving up parking\n");
19001       }
19002       return -1;
19003    }
19004    if ((d = ast_calloc(1, sizeof(*d)))) {
19005 
19006       /* Save original request for followup */
19007       copy_request(&d->req, req);
19008       d->chan1 = transferee;  /* Transferee */
19009       d->chan2 = transferer;  /* Transferer */
19010       d->seqno = seqno;
19011       if (ast_pthread_create_detached_background(&th, NULL, sip_park_thread, d) < 0) {
19012          /* Could not start thread */
19013          deinit_req(&d->req);
19014          ast_free(d);   /* We don't need it anymore. If thread is created, d will be free'd
19015                   by sip_park_thread() */
19016          return 0;
19017       }
19018    } 
19019    return -1;
19020 }
19021 
19022 /*! \brief Turn off generator data 
19023    XXX Does this function belong in the SIP channel?
19024 */
19025 static void ast_quiet_chan(struct ast_channel *chan) 
19026 {
19027    if (chan && chan->_state == AST_STATE_UP) {
19028       if (ast_test_flag(chan, AST_FLAG_MOH))
19029          ast_moh_stop(chan);
19030       else if (chan->generatordata)
19031          ast_deactivate_generator(chan);
19032    }
19033 }
19034 
19035 /*! \brief Attempt transfer of SIP call 
19036    This fix for attended transfers on a local PBX */
19037 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
19038 {
19039    int res = 0;
19040    struct ast_channel *peera = NULL,   
19041       *peerb = NULL,
19042       *peerc = NULL,
19043       *peerd = NULL;
19044 
19045 
19046    /* We will try to connect the transferee with the target and hangup
19047       all channels to the transferer */   
19048    ast_debug(4, "Sip transfer:--------------------\n");
19049    if (transferer->chan1)
19050       ast_debug(4, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
19051    else
19052       ast_debug(4, "-- No transferer first channel - odd??? \n");
19053    if (target->chan1)
19054       ast_debug(4, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
19055    else
19056       ast_debug(4, "-- No target first channel ---\n");
19057    if (transferer->chan2)
19058       ast_debug(4, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
19059    else
19060       ast_debug(4, "-- No bridged call to transferee\n");
19061    if (target->chan2)
19062       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)");
19063    else
19064       ast_debug(4, "-- No target second channel ---\n");
19065    ast_debug(4, "-- END Sip transfer:--------------------\n");
19066    if (transferer->chan2) { /* We have a bridge on the transferer's channel */
19067       peera = transferer->chan1; /* Transferer - PBX -> transferee channel * the one we hangup */
19068       peerb = target->chan1;     /* Transferer - PBX -> target channel - This will get lost in masq */
19069       peerc = transferer->chan2; /* Asterisk to Transferee */
19070       peerd = target->chan2;     /* Asterisk to Target */
19071       ast_debug(3, "SIP transfer: Four channels to handle\n");
19072    } else if (target->chan2) {   /* Transferer has no bridge (IVR), but transferee */
19073       peera = target->chan1;     /* Transferer to PBX -> target channel */
19074       peerb = transferer->chan1; /* Transferer to IVR*/
19075       peerc = target->chan2;     /* Asterisk to Target */
19076       peerd = transferer->chan2; /* Nothing */
19077       ast_debug(3, "SIP transfer: Three channels to handle\n");
19078    }
19079 
19080    if (peera && peerb && peerc && (peerb != peerc)) {
19081       ast_quiet_chan(peera);     /* Stop generators */
19082       ast_quiet_chan(peerb);  
19083       ast_quiet_chan(peerc);
19084       if (peerd)
19085          ast_quiet_chan(peerd);
19086 
19087       ast_debug(4, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
19088       if (ast_channel_masquerade(peerb, peerc)) {
19089          ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
19090          res = -1;
19091       } else
19092          ast_debug(4, "SIP transfer: Succeeded to masquerade channels.\n");
19093       return res;
19094    } else {
19095       ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
19096       if (transferer->chan1)
19097          ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
19098       if (target->chan1)
19099          ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
19100       return -1;
19101    }
19102    return 0;
19103 }
19104 
19105 /*! \brief Get tag from packet 
19106  *
19107  * \return Returns the pointer to the provided tag buffer,
19108  *         or NULL if the tag was not found.
19109  */
19110 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
19111 {
19112    const char *thetag;
19113 
19114    if (!tagbuf)
19115       return NULL;
19116    tagbuf[0] = '\0';    /* reset the buffer */
19117    thetag = get_header(req, header);
19118    thetag = strcasestr(thetag, ";tag=");
19119    if (thetag) {
19120       thetag += 5;
19121       ast_copy_string(tagbuf, thetag, tagbufsize);
19122       return strsep(&tagbuf, ";");
19123    }
19124    return NULL;
19125 }
19126 
19127 /*! \brief Handle incoming notifications */
19128 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
19129 {
19130    /* This is mostly a skeleton for future improvements */
19131    /* Mostly created to return proper answers on notifications on outbound REFER's */
19132    int res = 0;
19133    const char *event = get_header(req, "Event");
19134    char *eventid = NULL;
19135    char *sep;
19136 
19137    if( (sep = strchr(event, ';')) ) {  /* XXX bug here - overwriting string ? */
19138       *sep++ = '\0';
19139       eventid = sep;
19140    }
19141    
19142    if (sipdebug)
19143       ast_debug(2, "Got NOTIFY Event: %s\n", event);
19144 
19145    if (!strcmp(event, "refer")) {
19146       /* Save nesting depth for now, since there might be other events we will
19147          support in the future */
19148 
19149       /* Handle REFER notifications */
19150 
19151       char buf[1024];
19152       char *cmd, *code;
19153       int respcode;
19154       int success = TRUE;
19155 
19156       /* EventID for each transfer... EventID is basically the REFER cseq 
19157 
19158        We are getting notifications on a call that we transfered
19159        We should hangup when we are getting a 200 OK in a sipfrag
19160        Check if we have an owner of this event */
19161       
19162       /* Check the content type */
19163       if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
19164          /* We need a sipfrag */
19165          transmit_response(p, "400 Bad request", req);
19166          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19167          return -1;
19168       }
19169 
19170       /* Get the text of the attachment */
19171       if (get_msg_text(buf, sizeof(buf), req, TRUE)) {
19172          ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
19173          transmit_response(p, "400 Bad request", req);
19174          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19175          return -1;
19176       }
19177 
19178       /*
19179       From the RFC...
19180       A minimal, but complete, implementation can respond with a single
19181       NOTIFY containing either the body:
19182          SIP/2.0 100 Trying
19183       
19184       if the subscription is pending, the body:
19185          SIP/2.0 200 OK
19186       if the reference was successful, the body:
19187          SIP/2.0 503 Service Unavailable
19188       if the reference failed, or the body:
19189          SIP/2.0 603 Declined
19190 
19191       if the REFER request was accepted before approval to follow the
19192       reference could be obtained and that approval was subsequently denied
19193       (see Section 2.4.7).
19194       
19195       If there are several REFERs in the same dialog, we need to
19196       match the ID of the event header...
19197       */
19198       ast_debug(3, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
19199       cmd = ast_skip_blanks(buf);
19200       code = cmd;
19201       /* We are at SIP/2.0 */
19202       while(*code && (*code > 32)) {   /* Search white space */
19203          code++;
19204       }
19205       *code++ = '\0';
19206       code = ast_skip_blanks(code);
19207       sep = code;
19208       sep++;
19209       while(*sep && (*sep > 32)) {  /* Search white space */
19210          sep++;
19211       }
19212       *sep++ = '\0';       /* Response string */
19213       respcode = atoi(code);
19214       switch (respcode) {
19215       case 100:   /* Trying: */
19216       case 101:   /* dialog establishment */
19217          /* Don't do anything yet */
19218          break;
19219       case 183:   /* Ringing: */
19220          /* Don't do anything yet */
19221          break;
19222       case 200:   /* OK: The new call is up, hangup this call */
19223          /* Hangup the call that we are replacing */
19224          break;
19225       case 301: /* Moved permenantly */
19226       case 302: /* Moved temporarily */
19227          /* Do we get the header in the packet in this case? */
19228          success = FALSE;
19229          break;
19230       case 503:   /* Service Unavailable: The new call failed */
19231             /* Cancel transfer, continue the call */
19232          success = FALSE;
19233          break;
19234       case 603:   /* Declined: Not accepted */
19235             /* Cancel transfer, continue the current call */
19236          success = FALSE;
19237          break;
19238       }
19239       if (!success) {
19240          ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
19241       }
19242       
19243       /* Confirm that we received this packet */
19244       transmit_response(p, "200 OK", req);
19245    } else if (p->mwi && !strcmp(event, "message-summary")) {
19246       char *c = ast_strdupa(get_body(req, "Voice-Message", ':'));
19247 
19248       if (!ast_strlen_zero(c)) {
19249          char *old = strsep(&c, " ");
19250          char *new = strsep(&old, "/");
19251          struct ast_event *event;
19252 
19253          if ((event = ast_event_new(AST_EVENT_MWI,
19254                      AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, p->mwi->mailbox,
19255                      AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, "SIP_Remote",
19256                      AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(new),
19257                      AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(old),
19258                      AST_EVENT_IE_END))) {
19259             ast_event_queue_and_cache(event);
19260          }
19261       }
19262 
19263       transmit_response(p, "200 OK", req);
19264    } else if (!strcmp(event, "keep-alive")) {
19265        /* Used by Sipura/Linksys for NAT pinhole,
19266         * just confirm that we recieved the packet. */
19267       transmit_response(p, "200 OK", req);
19268    } else {
19269       /* We don't understand this event. */
19270       transmit_response(p, "489 Bad event", req);
19271       res = -1;
19272    }
19273 
19274    if (!p->lastinvite)
19275       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19276 
19277    return res;
19278 }
19279 
19280 /*! \brief Handle incoming OPTIONS request 
19281    An OPTIONS request should be answered like an INVITE from the same UA, including SDP
19282 */
19283 static int handle_request_options(struct sip_pvt *p, struct sip_request *req)
19284 {
19285    int res;
19286 
19287    /*! XXX get_destination assumes we're already authenticated. This means that a request from
19288       a known device (peer) will end up in the wrong context if this is out-of-dialog.
19289       However, we want to handle OPTIONS as light as possible, so we might want to have
19290       a configuration option whether we care or not. Some devices use this for testing
19291       capabilities, which means that we need to match device to answer with proper 
19292       capabilities (including SDP).
19293       \todo Fix handle_request_options device handling with optional authentication
19294          (this needs to be fixed in 1.4 as well)
19295    */
19296 
19297    if (p->lastinvite) {
19298       /* if this is a request in an active dialog, just confirm that the dialog exists. */
19299       transmit_response_with_allow(p, "200 OK", req, 0);
19300       return 0;
19301    }
19302 
19303    res = get_destination(p, req);
19304    build_contact(p);
19305 
19306    if (ast_strlen_zero(p->context))
19307       ast_string_field_set(p, context, sip_cfg.default_context);
19308 
19309    if (ast_shutting_down())
19310       transmit_response_with_allow(p, "503 Unavailable", req, 0);
19311    else if (res < 0)
19312       transmit_response_with_allow(p, "404 Not Found", req, 0);
19313    else 
19314       transmit_response_with_allow(p, "200 OK", req, 0);
19315 
19316    /* Destroy if this OPTIONS was the opening request, but not if
19317       it's in the middle of a normal call flow. */
19318    sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19319 
19320    return res;
19321 }
19322 
19323 /*! \brief Handle the transfer part of INVITE with a replaces: header, 
19324     meaning a target pickup or an attended transfer.
19325     Used only once.
19326    XXX 'ignore' is unused.
19327 
19328    \note this function is called by handle_request_invite(). Four locks
19329    held at the beginning of this function, p, p->owner, p->refer->refer_call->owner...
19330    only p's lock should remain at the end of this function.  p's lock is held by sipsock_read()
19331  */
19332 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *nounlock)
19333 {
19334    int earlyreplace = 0;
19335    int oneleggedreplace = 0;     /* Call with no bridge, propably IVR or voice message */
19336    struct ast_channel *c = p->owner;   /* Our incoming call */
19337    struct ast_channel *replacecall = p->refer->refer_call->owner; /* The channel we're about to take over */
19338    struct ast_channel *targetcall;     /* The bridge to the take-over target */
19339 
19340    struct ast_channel *test;
19341 
19342    /* Check if we're in ring state */
19343    if (replacecall->_state == AST_STATE_RING)
19344       earlyreplace = 1;
19345 
19346    /* Check if we have a bridge */
19347    if (!(targetcall = ast_bridged_channel(replacecall))) {
19348       /* We have no bridge */
19349       if (!earlyreplace) {
19350          ast_debug(2, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
19351          oneleggedreplace = 1;
19352       }
19353    } 
19354    if (targetcall && targetcall->_state == AST_STATE_RINGING)
19355       ast_debug(4, "SIP transfer: Target channel is in ringing state\n");
19356 
19357    if (targetcall) 
19358       ast_debug(4, "SIP transfer: Invite Replace incoming channel should bridge to channel %s while hanging up channel %s\n", targetcall->name, replacecall->name); 
19359    else
19360       ast_debug(4, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name); 
19361 
19362    if (req->ignore) {
19363       ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
19364       /* We should answer something here. If we are here, the
19365          call we are replacing exists, so an accepted 
19366          can't harm */
19367       transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE);
19368       /* Do something more clever here */
19369       if (c) {
19370          *nounlock = 1;
19371          ast_channel_unlock(c);
19372       }
19373       ast_channel_unlock(replacecall);
19374       sip_pvt_unlock(p->refer->refer_call);
19375       return 1;
19376    } 
19377    if (!c) {
19378       /* What to do if no channel ??? */
19379       ast_log(LOG_ERROR, "Unable to create new channel.  Invite/replace failed.\n");
19380       transmit_response_reliable(p, "503 Service Unavailable", req);
19381       append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
19382       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19383       ast_channel_unlock(replacecall);
19384       sip_pvt_unlock(p->refer->refer_call);
19385       return 1;
19386    }
19387    append_history(p, "Xfer", "INVITE/Replace received");
19388    /* We have three channels to play with
19389       channel c: New incoming call
19390       targetcall: Call from PBX to target
19391       p->refer->refer_call: SIP pvt dialog from transferer to pbx.
19392       replacecall: The owner of the previous
19393       We need to masq C into refer_call to connect to 
19394       targetcall;
19395       If we are talking to internal audio stream, target call is null.
19396    */
19397 
19398    /* Fake call progress */
19399    transmit_response(p, "100 Trying", req);
19400    ast_setstate(c, AST_STATE_RING);
19401 
19402    /* Masquerade the new call into the referred call to connect to target call 
19403       Targetcall is not touched by the masq */
19404 
19405    /* Answer the incoming call and set channel to UP state */
19406    transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE);
19407       
19408    ast_setstate(c, AST_STATE_UP);
19409    
19410    /* Stop music on hold and other generators */
19411    ast_quiet_chan(replacecall);
19412    ast_quiet_chan(targetcall);
19413    ast_debug(4, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);
19414 
19415    /* Make sure that the masq does not free our PVT for the old call */
19416    if (! earlyreplace && ! oneleggedreplace )
19417       ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER);  /* Delay hangup */
19418 
19419    /* Prepare the masquerade - if this does not happen, we will be gone */
19420    if(ast_channel_masquerade(replacecall, c))
19421       ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
19422    else
19423       ast_debug(4, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);
19424 
19425    /* C should now be in place of replacecall */
19426    if (ast_do_masquerade(replacecall)) {
19427       ast_log(LOG_WARNING, "Failed to perform masquerade with INVITE replaces\n");
19428    }
19429 
19430    if (earlyreplace || oneleggedreplace ) {
19431       c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
19432    }
19433 
19434    ast_setstate(c, AST_STATE_DOWN);
19435    ast_debug(4, "After transfer:----------------------------\n");
19436    ast_debug(4, " -- C:        %s State %s\n", c->name, ast_state2str(c->_state));
19437    if (replacecall)
19438       ast_debug(4, " -- replacecall:        %s State %s\n", replacecall->name, ast_state2str(replacecall->_state));
19439    if (p->owner) {
19440       ast_debug(4, " -- P->owner: %s State %s\n", p->owner->name, ast_state2str(p->owner->_state));
19441       test = ast_bridged_channel(p->owner);
19442       if (test)
19443          ast_debug(4, " -- Call bridged to P->owner: %s State %s\n", test->name, ast_state2str(test->_state));
19444       else
19445          ast_debug(4, " -- No call bridged to C->owner \n");
19446    } else 
19447       ast_debug(4, " -- No channel yet \n");
19448    ast_debug(4, "End After transfer:----------------------------\n");
19449 
19450    /* unlock sip pvt and owner so hangup can do its thing */
19451    ast_channel_unlock(replacecall);
19452    ast_channel_unlock(c);
19453    sip_pvt_unlock(p->refer->refer_call);
19454    sip_pvt_unlock(p);
19455    *nounlock = 1;
19456 
19457    /* The call should be down with no ast_channel, so hang it up */
19458    c->tech_pvt = dialog_unref(c->tech_pvt, "unref dialog c->tech_pvt");
19459    ast_hangup(c);
19460    sip_pvt_lock(p); /* lock PVT structure again after hangup */
19461 
19462    return 0;
19463 }
19464 
19465 /*! \brief helper routine for sip_uri_cmp to compare URI parameters
19466  *
19467  * This takes the parameters from two SIP URIs and determines
19468  * if the URIs match. The rules for parameters *suck*. Here's a breakdown
19469  * 1. If a parameter appears in both URIs, then they must have the same value
19470  *    in order for the URIs to match
19471  * 2. If one URI has a user, maddr, ttl, or method parameter, then the other
19472  *    URI must also have that parameter and must have the same value
19473  *    in order for the URIs to match
19474  * 3. All other headers appearing in only one URI are not considered when
19475  *    determining if URIs match
19476  *
19477  * \param input1 Parameters from URI 1
19478  * \param input2 Parameters from URI 2
19479  * \retval 0 URIs' parameters match
19480  * \retval nonzero URIs' parameters do not match
19481  */
19482 static int sip_uri_params_cmp(const char *input1, const char *input2)
19483 {
19484    char *params1 = NULL;
19485    char *params2 = NULL;
19486    char *pos1;
19487    char *pos2;
19488    int zerolength1 = 0;
19489    int zerolength2 = 0;
19490    int maddrmatch = 0;
19491    int ttlmatch = 0;
19492    int usermatch = 0;
19493    int methodmatch = 0;
19494 
19495    if (ast_strlen_zero(input1)) {
19496       zerolength1 = 1;
19497    } else {
19498       params1 = ast_strdupa(input1);
19499    }
19500    if (ast_strlen_zero(input2)) {
19501       zerolength2 = 1;
19502    } else {
19503       params2 = ast_strdupa(input2);
19504    }
19505 
19506    /* Quick optimization. If both params are zero-length, then
19507     * they match
19508     */
19509    if (zerolength1 && zerolength2) {
19510       return 0;
19511    }
19512 
19513    for (pos1 = strsep(&params1, ";"); pos1; pos1 = strsep(&params1, ";")) {
19514       char *value1 = pos1;
19515       char *name1 = strsep(&value1, "=");
19516       char *params2dup = NULL;
19517       int matched = 0;
19518       if (!value1) {
19519          value1 = "";
19520       }
19521       /* Checkpoint reached. We have the name and value parsed for param1
19522        * We have to duplicate params2 each time through this loop
19523        * or else the inner loop below will not work properly.
19524        */
19525       if (!zerolength2) {
19526          params2dup = ast_strdupa(params2);
19527       }
19528       for (pos2 = strsep(&params2dup, ";"); pos2; pos2 = strsep(&params2dup, ";")) {
19529          char *name2 = pos2;
19530          char *value2 = strchr(pos2, '=');
19531          if (!value2) {
19532             value2 = "";
19533          } else {
19534             *value2++ = '\0';
19535          }
19536          if (!strcasecmp(name1, name2)) {
19537             if (strcasecmp(value1, value2)) {
19538                goto fail;
19539             } else {
19540                matched = 1;
19541                break;
19542             }
19543          }
19544       }
19545       /* Check to see if the parameter is one of the 'must-match' parameters */
19546       if (!strcasecmp(name1, "maddr")) {
19547          if (matched) {
19548             maddrmatch = 1;
19549          } else {
19550             goto fail;
19551          }
19552       } else if (!strcasecmp(name1, "ttl")) {
19553          if (matched) {
19554             ttlmatch = 1;
19555          } else {
19556             goto fail;
19557          }
19558       } else if (!strcasecmp(name1, "user")) {
19559          if (matched) {
19560             usermatch = 1;
19561          } else {
19562             goto fail;
19563          }
19564       } else if (!strcasecmp(name1, "method")) {
19565          if (matched) {
19566             methodmatch = 1;
19567          } else {
19568             goto fail;
19569          }
19570       }
19571    }
19572 
19573    /* We've made it out of that horrible O(m*n) construct and there are no
19574     * failures yet. We're not done yet, though, because params2 could have
19575     * an maddr, ttl, user, or method header and params1 did not.
19576     */
19577    for (pos2 = strsep(&params2, ";"); pos2; pos2 = strsep(&params2, ";")) {
19578       char *value2 = pos2;
19579       char *name2 = strsep(&value2, "=");
19580       if (!value2) {
19581          value2 = "";
19582       }
19583       if ((!strcasecmp(name2, "maddr") && !maddrmatch) ||
19584             (!strcasecmp(name2, "ttl") && !ttlmatch) ||
19585             (!strcasecmp(name2, "user") && !usermatch) ||
19586             (!strcasecmp(name2, "method") && !methodmatch)) {
19587          goto fail;
19588       }
19589    }
19590    return 0;
19591 
19592 fail:
19593    return 1;
19594 }
19595 
19596 /*! \brief helper routine for sip_uri_cmp
19597  *
19598  * This takes the "headers" from two SIP URIs and determines
19599  * if the URIs match. The rules for headers is simple. If a header
19600  * appears in one URI, then it must also appear in the other URI. The
19601  * order in which the headers appear does not matter.
19602  *
19603  * \param input1 Headers from URI 1
19604  * \param input2 Headers from URI 2
19605  * \return Return 0 if the URIs' headers match, 1 if they do not
19606  */
19607 static int sip_uri_headers_cmp(const char *input1, const char *input2)
19608 {
19609    char *headers1 = NULL;
19610    char *headers2 = NULL;
19611    int zerolength1 = 0;
19612    int zerolength2 = 0;
19613    int different = 0;
19614    char *header1;
19615 
19616    if (ast_strlen_zero(input1)) {
19617       zerolength1 = 1;
19618    } else {
19619       headers1 = ast_strdupa(input1);
19620    }
19621    
19622    if (ast_strlen_zero(input2)) {
19623       zerolength2 = 1;
19624    } else {
19625       headers2 = ast_strdupa(input2);
19626    }
19627 
19628    if ((zerolength1 && !zerolength2) ||
19629          (zerolength2 && !zerolength1))
19630       return 1;
19631 
19632    if (zerolength1 && zerolength2)
19633       return 0;
19634 
19635    /* At this point, we can definitively state that both inputs are
19636     * not zero-length. First, one more optimization. If the length
19637     * of the headers is not equal, then we definitely have no match
19638     */
19639    if (strlen(headers1) != strlen(headers2)) {
19640       return 1;
19641    }
19642 
19643    for (header1 = strsep(&headers1, "&"); header1; header1 = strsep(&headers1, "&")) {
19644       if (!strcasestr(headers2, header1)) {
19645          different = 1;
19646          break;
19647       }
19648    }
19649 
19650    return different;
19651 }
19652 
19653 static int sip_uri_cmp(const char *input1, const char *input2)
19654 {
19655    char *uri1 = ast_strdupa(input1);
19656    char *uri2 = ast_strdupa(input2);
19657    char *host1;
19658    char *host2;
19659    char *params1;
19660    char *params2;
19661    char *headers1;
19662    char *headers2;
19663 
19664    /* Strip off "sip:" from the URI. We know this is present
19665     * because it was checked back in parse_request()
19666     */
19667    strsep(&uri1, ":");
19668    strsep(&uri2, ":");
19669 
19670    if ((host1 = strchr(uri1, '@'))) {
19671       *host1++ = '\0';
19672    }
19673    if ((host2 = strchr(uri2, '@'))) {
19674       *host2++ = '\0';
19675    }
19676 
19677    /* Check for mismatched username and passwords. This is the
19678     * only case-sensitive comparison of a SIP URI
19679     */
19680    if ((host1 && !host2) ||
19681          (host2 && !host1) ||
19682          (host1 && host2 && strcmp(uri1, uri2))) {
19683       return 1;
19684    }
19685 
19686    if (!host1)
19687       host1 = uri1;
19688    if (!host2)
19689       host2 = uri2;
19690 
19691    /* Strip off the parameters and headers so we can compare
19692     * host and port
19693     */
19694 
19695    if ((params1 = strchr(host1, ';'))) {
19696       *params1++ = '\0';
19697    }
19698    if ((params2 = strchr(host2, ';'))) {
19699       *params2++ = '\0';
19700    }
19701 
19702    /* Headers come after parameters, but there may be headers without
19703     * parameters, thus the S_OR
19704     */
19705    if ((headers1 = strchr(S_OR(params1, host1), '?'))) {
19706       *headers1++ = '\0';
19707    }
19708    if ((headers2 = strchr(S_OR(params2, host2), '?'))) {
19709       *headers2++ = '\0';
19710    }
19711 
19712    /* Now the host/port are properly isolated. We can get by with a string comparison
19713     * because the SIP URI checking rules have some interesting exceptions that make
19714     * this possible. I will note 2 in particular
19715     * 1. hostnames which resolve to the same IP address as well as a hostname and its
19716     *    IP address are not considered a match with SIP URI's.
19717     * 2. If one URI specifies a port and the other does not, then the URIs do not match.
19718     *    This includes if one URI explicitly contains port 5060 and the other implies it
19719     *    by not having a port specified.
19720     */
19721 
19722    if (strcasecmp(host1, host2)) {
19723       return 1;
19724    }
19725 
19726    /* Headers have easier rules to follow, so do those first */
19727    if (sip_uri_headers_cmp(headers1, headers2)) {
19728       return 1;
19729    }
19730 
19731    /* And now the parameters. Ugh */
19732    return sip_uri_params_cmp(params1, params2);
19733 }
19734 
19735 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context)
19736 {
19737    struct ast_str *str = ast_str_alloca(AST_MAX_EXTENSION + AST_MAX_CONTEXT + 2);
19738    struct ast_app *pickup = pbx_findapp("Pickup");
19739 
19740    if (!pickup) {
19741       ast_log(LOG_ERROR, "Unable to perform pickup: Application 'Pickup' not loaded (app_directed_pickup.so).\n");
19742       return -1;
19743    }
19744 
19745    ast_str_set(&str, 0, "%s@%s", extension, sip_cfg.notifycid == IGNORE_CONTEXT ? "PICKUPMARK" : context);
19746 
19747    ast_debug(2, "About to call Pickup(%s)\n", str->str);
19748 
19749    /* There is no point in capturing the return value since pickup_exec
19750       doesn't return anything meaningful unless the passed data is an empty
19751       string (which in our case it will not be) */
19752    pbx_exec(channel, pickup, str->str);
19753 
19754    return 0;
19755 }
19756 
19757 /*! \brief Called to deny a T38 reinvite if the core does not respond to our request */
19758 static int sip_t38_abort(const void *data)
19759 {
19760    struct sip_pvt *p = (struct sip_pvt *) data;
19761 
19762    sip_pvt_lock(p);
19763    /* an application may have taken ownership of the T.38 negotiation on this
19764     * channel while we were waiting to grab the lock... if it did, the scheduler
19765     * id will have been reset to -1, which is our indication that we do *not*
19766     * want to abort the negotiation process
19767     */
19768    if (p->t38id != -1) {
19769       change_t38_state(p, T38_DISABLED);
19770       transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
19771       p->t38id = -1;
19772       dialog_unref(p, "unref the dialog ptr from sip_t38_abort, because it held a dialog ptr");
19773    }
19774    sip_pvt_unlock(p);
19775    return 0;
19776 }
19777 
19778 /*! \brief Handle incoming INVITE request
19779 \note    If the INVITE has a Replaces header, it is part of an
19780  * attended transfer. If so, we do not go through the dial
19781  * plan but tries to find the active call and masquerade
19782  * into it 
19783  */
19784 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)
19785 {
19786    int res = 1;
19787    int gotdest;
19788    const char *p_replaces;
19789    char *replace_id = NULL;
19790    int refer_locked = 0;
19791    const char *required;
19792    unsigned int required_profile = 0;
19793    struct ast_channel *c = NULL;    /* New channel */
19794    int reinvite = 0;
19795    int rtn;
19796 
19797    const char *p_uac_se_hdr;       /* UAC's Session-Expires header string                      */
19798    const char *p_uac_min_se;       /* UAC's requested Min-SE interval (char string)            */
19799    int uac_max_se = -1;            /* UAC's Session-Expires in integer format                  */
19800    int uac_min_se = -1;            /* UAC's Min-SE in integer format                           */
19801    int st_active = FALSE;          /* Session-Timer on/off boolean                             */
19802    int st_interval = 0;            /* Session-Timer negotiated refresh interval                */
19803    enum st_refresher st_ref;       /* Session-Timer session refresher                          */
19804    int dlg_min_se = -1;
19805    struct {
19806       char exten[AST_MAX_EXTENSION];
19807       char context[AST_MAX_CONTEXT];
19808    } pickup = {
19809       .exten = "",
19810    };
19811    st_ref = SESSION_TIMER_REFRESHER_AUTO;
19812 
19813    /* Find out what they support */
19814    if (!p->sipoptions) {
19815       const char *supported = get_header(req, "Supported");
19816       if (!ast_strlen_zero(supported))
19817          parse_sip_options(p, supported);
19818    }
19819 
19820    /* Find out what they require */
19821    required = get_header(req, "Require");
19822    if (!ast_strlen_zero(required)) {
19823       required_profile = parse_sip_options(NULL, required);
19824       if (required_profile && !(required_profile & (SIP_OPT_REPLACES | SIP_OPT_TIMER))) {
19825          /* At this point we only support REPLACES and Session-Timer */
19826          transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, required);
19827          ast_log(LOG_WARNING, "Received SIP INVITE with unsupported required extension: %s\n", required);
19828          p->invitestate = INV_COMPLETED;
19829          if (!p->lastinvite)
19830             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19831          res = -1;
19832          goto request_invite_cleanup;
19833       }
19834    }
19835 
19836    /* The option tags may be present in Supported: or Require: headers.
19837    Include the Require: option tags for further processing as well */
19838    p->sipoptions |= required_profile;
19839    p->reqsipoptions = required_profile;
19840 
19841    /* Check if this is a loop */
19842    if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && p->owner && (p->invitestate != INV_TERMINATED && p->invitestate != INV_CONFIRMED)) {
19843       /* This is a call to ourself.  Send ourselves an error code and stop
19844          processing immediately, as SIP really has no good mechanism for
19845          being able to call yourself */
19846       /* If pedantic is on, we need to check the tags. If they're different, this is
19847          in fact a forked call through a SIP proxy somewhere. */
19848       int different;
19849       char *initial_rlPart2 = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
19850       char *this_rlPart2 = REQ_OFFSET_TO_STR(req, rlPart2);
19851       if (sip_cfg.pedanticsipchecking)
19852          different = sip_uri_cmp(initial_rlPart2, this_rlPart2);
19853       else
19854          different = strcmp(initial_rlPart2, this_rlPart2);
19855       if (!different) {
19856          transmit_response(p, "482 Loop Detected", req);
19857          p->invitestate = INV_COMPLETED;
19858          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19859          res = 0;
19860          goto request_invite_cleanup;
19861       } else {
19862          /*! This is a spiral. What we need to do is to just change the outgoing INVITE
19863           * so that it now routes to the new Request URI. Since we created the INVITE ourselves
19864           * that should be all we need to do.
19865           * 
19866           * \todo XXX This needs to be reviewed.  YOu don't change the request URI really, you route the packet
19867           * correctly instead...
19868           */
19869          char *uri = ast_strdupa(this_rlPart2);
19870          char *at = strchr(uri, '@');
19871          char *peerorhost;
19872          ast_debug(2, "Potential spiral detected. Original RURI was %s, new RURI is %s\n", initial_rlPart2, this_rlPart2);
19873          transmit_response(p, "100 Trying", req);
19874          if (at) {
19875             *at = '\0';
19876          }
19877          /* Parse out "sip:" */
19878          if ((peerorhost = strchr(uri, ':'))) {
19879             *peerorhost++ = '\0';
19880          }
19881          ast_string_field_set(p, theirtag, NULL);
19882          /* Treat this as if there were a call forward instead...
19883           */
19884          ast_string_field_set(p->owner, call_forward, peerorhost);
19885          ast_queue_control(p->owner, AST_CONTROL_BUSY);
19886          res = 0;
19887          goto request_invite_cleanup;
19888       }
19889    }
19890 
19891    if (!req->ignore && p->pendinginvite) {
19892       if (!ast_test_flag(&p->flags[0], SIP_OUTGOING) && (p->invitestate == INV_COMPLETED || p->invitestate == INV_TERMINATED)) {
19893          /* What do these circumstances mean? We have received an INVITE for an "incoming" dialog for which we
19894           * have sent a final response. We have not yet received an ACK, though (which is why p->pendinginvite is non-zero).
19895           * We also know that the INVITE is not a retransmission, because otherwise the "ignore" flag would be set.
19896           * This means that either we are receiving a reinvite for a terminated dialog, or we are receiving an INVITE with
19897           * credentials based on one we challenged earlier.
19898           *
19899           * The action to take in either case is to treat the INVITE as though it contains an implicit ACK for the previous
19900           * transaction. Calling __sip_ack will take care of this by clearing the p->pendinginvite and removing the response
19901           * from the previous transaction from the list of outstanding packets.
19902           */
19903          __sip_ack(p, p->pendinginvite, 1, 0);
19904       } else {
19905          /* We already have a pending invite. Sorry. You are on hold. */
19906          p->glareinvite = seqno;     /* must hold on to this seqno to process ack and retransmit correctly */
19907          if (p->rtp && find_sdp(req)) {
19908             struct sockaddr_in sin;
19909             if (get_ip_and_port_from_sdp(req, SDP_AUDIO, &sin)) {
19910                ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Audio may not work properly on this call.\n");
19911             } else {
19912                ast_rtp_set_alt_peer(p->rtp, &sin);
19913             }
19914             if (p->vrtp) {
19915                if (get_ip_and_port_from_sdp(req, SDP_VIDEO, &sin)) {
19916                   ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Video may not work properly on this call.\n");
19917                } else {
19918                   ast_rtp_set_alt_peer(p->vrtp, &sin);
19919                }
19920             }
19921          }
19922          transmit_response_reliable(p, "491 Request Pending", req);
19923          ast_debug(1, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
19924          /* Don't destroy dialog here */
19925          res = 0;
19926          goto request_invite_cleanup;
19927       }
19928    }
19929 
19930    p_replaces = get_header(req, "Replaces");
19931    if (!ast_strlen_zero(p_replaces)) {
19932       /* We have a replaces header */
19933       char *ptr;
19934       char *fromtag = NULL;
19935       char *totag = NULL;
19936       char *start, *to;
19937       int error = 0;
19938 
19939       if (p->owner) {
19940          ast_debug(3, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
19941          transmit_response_reliable(p, "400 Bad request", req);   /* The best way to not not accept the transfer */
19942          /* Do not destroy existing call */
19943          res = -1;
19944          goto request_invite_cleanup;
19945       }
19946 
19947       if (sipdebug)
19948          ast_debug(3, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
19949       /* Create a buffer we can manipulate */
19950       replace_id = ast_strdupa(p_replaces);
19951       ast_uri_decode(replace_id);
19952 
19953       if (!p->refer && !sip_refer_allocate(p)) {
19954          transmit_response_reliable(p, "500 Server Internal Error", req);
19955          append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
19956          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19957          p->invitestate = INV_COMPLETED;
19958          res = -1;
19959          goto request_invite_cleanup;
19960       }
19961 
19962       /*  Todo: (When we find phones that support this)
19963          if the replaces header contains ";early-only"
19964          we can only replace the call in early
19965          stage, not after it's up.
19966 
19967          If it's not in early mode, 486 Busy.
19968       */
19969 
19970       /* Skip leading whitespace */
19971       replace_id = ast_skip_blanks(replace_id);
19972 
19973       start = replace_id;
19974       while ( (ptr = strsep(&start, ";")) ) {
19975          ptr = ast_skip_blanks(ptr); /* XXX maybe unnecessary ? */
19976          if ( (to = strcasestr(ptr, "to-tag=") ) )
19977             totag = to + 7;   /* skip the keyword */
19978          else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
19979             fromtag = to + 9; /* skip the keyword */
19980             fromtag = strsep(&fromtag, "&"); /* trim what ? */
19981          }
19982       }
19983 
19984       if (sipdebug)
19985          ast_debug(4, "Invite/replaces: Will use Replace-Call-ID : %s Fromtag: %s Totag: %s\n",
19986                  replace_id,
19987                  fromtag ? fromtag : "<no from tag>",
19988                  totag ? totag : "<no to tag>");
19989 
19990       /* Try to find call that we are replacing.
19991          If we have a Replaces header, we need to cancel that call if we succeed with this call.
19992          First we cheat a little and look for a magic call-id from phones that support
19993          dialog-info+xml so we can do technology independent pickup... */
19994       if (strncmp(replace_id, "pickup-", 7) == 0) {
19995          struct sip_pvt *subscription = NULL;
19996          replace_id += 7; /* Worst case we are looking at \0 */
19997 
19998          if ((subscription = get_sip_pvt_byid_locked(replace_id, NULL, NULL)) == NULL) {
19999             ast_log(LOG_NOTICE, "Unable to find subscription with call-id: %s\n", replace_id);
20000             transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
20001             error = 1;
20002          } else {
20003             ast_log(LOG_NOTICE, "Trying to pick up %s@%s\n", subscription->exten, subscription->context);
20004             ast_copy_string(pickup.exten, subscription->exten, sizeof(pickup.exten));
20005             ast_copy_string(pickup.context, subscription->context, sizeof(pickup.context));
20006             sip_pvt_unlock(subscription);
20007             if (subscription->owner) {
20008                ast_channel_unlock(subscription->owner);
20009             }
20010          }
20011       }
20012 
20013       /* This locks both refer_call pvt and refer_call pvt's owner!!!*/
20014       if (!error && ast_strlen_zero(pickup.exten) && (p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
20015          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
20016          transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
20017          error = 1;
20018       } else {
20019          refer_locked = 1;
20020       }
20021 
20022       /* The matched call is the call from the transferer to Asterisk .
20023          We want to bridge the bridged part of the call to the 
20024          incoming invite, thus taking over the refered call */
20025 
20026       if (p->refer->refer_call == p) {
20027          ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
20028          p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
20029          transmit_response_reliable(p, "400 Bad request", req);   /* The best way to not not accept the transfer */
20030          error = 1;
20031       }
20032 
20033       if (!error && ast_strlen_zero(pickup.exten) && !p->refer->refer_call->owner) {
20034          /* Oops, someting wrong anyway, no owner, no call */
20035          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
20036          /* Check for better return code */
20037          transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replace)", req);
20038          error = 1;
20039       }
20040 
20041       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) {
20042          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
20043          transmit_response_reliable(p, "603 Declined (Replaces)", req);
20044          error = 1;
20045       }
20046 
20047       if (error) {   /* Give up this dialog */
20048          append_history(p, "Xfer", "INVITE/Replace Failed.");
20049          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20050          sip_pvt_unlock(p);
20051          if (p->refer->refer_call) {
20052             sip_pvt_unlock(p->refer->refer_call);
20053             if (p->refer->refer_call->owner) {
20054                ast_channel_unlock(p->refer->refer_call->owner);
20055             }
20056          }
20057          refer_locked = 0;
20058          p->invitestate = INV_COMPLETED;
20059          res = -1;
20060          goto request_invite_cleanup;
20061       }
20062    }
20063 
20064    /* Check if this is an INVITE that sets up a new dialog or
20065       a re-invite in an existing dialog */
20066 
20067    if (!req->ignore) {
20068       int newcall = (p->initreq.headers ? TRUE : FALSE);
20069 
20070       if (sip_cancel_destroy(p))
20071          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
20072       /* This also counts as a pending invite */
20073       p->pendinginvite = seqno;
20074       check_via(p, req);
20075 
20076       copy_request(&p->initreq, req);     /* Save this INVITE as the transaction basis */
20077       if (sipdebug)
20078          ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
20079       if (!p->owner) {  /* Not a re-invite */
20080          if (debug)
20081             ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
20082          if (newcall)
20083             append_history(p, "Invite", "New call: %s", p->callid);
20084          parse_ok_contact(p, req);
20085       } else { /* Re-invite on existing call */
20086          ast_clear_flag(&p->flags[0], SIP_OUTGOING);  /* This is now an inbound dialog */
20087          /* Handle SDP here if we already have an owner */
20088          if (find_sdp(req)) {
20089             if (process_sdp(p, req, SDP_T38_INITIATE)) {
20090                transmit_response_reliable(p, "488 Not acceptable here", req);
20091                if (!p->lastinvite)
20092                   sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20093                res = -1;
20094                goto request_invite_cleanup;
20095             }
20096             ast_queue_control(p->owner, AST_CONTROL_SRCUPDATE);
20097          } else {
20098             p->jointcapability = p->capability;
20099             ast_debug(1, "Hm....  No sdp for the moment\n");
20100          }
20101          if (p->do_history) /* This is a response, note what it was for */
20102             append_history(p, "ReInv", "Re-invite received");
20103       }
20104    } else if (debug)
20105       ast_verbose("Ignoring this INVITE request\n");
20106 
20107    if (!p->lastinvite && !req->ignore && !p->owner) {
20108       /* This is a new invite */
20109       /* Handle authentication if this is our first invite */
20110       res = check_user(p, req, SIP_INVITE, e, XMIT_RELIABLE, sin);
20111       if (res == AUTH_CHALLENGE_SENT) {
20112          p->invitestate = INV_COMPLETED;     /* Needs to restart in another INVITE transaction */
20113          res = 0;
20114          goto request_invite_cleanup;
20115       }
20116       if (res < 0) { /* Something failed in authentication */
20117          if (res == AUTH_FAKE_AUTH) {
20118             ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
20119             transmit_fake_auth_response(p, SIP_INVITE, req, XMIT_RELIABLE);
20120          } else {
20121             ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
20122             transmit_response_reliable(p, "403 Forbidden", req);
20123          }
20124          p->invitestate = INV_COMPLETED;
20125          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20126          ast_string_field_set(p, theirtag, NULL);
20127          res = 0;
20128          goto request_invite_cleanup;
20129       }
20130 
20131       /* If T38 is needed but not present, then make it magically appear */
20132       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && !p->udptl) {
20133          if ((p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr))) {
20134             p->t38_maxdatagram = global_t38_maxdatagram;
20135             set_t38_capabilities(p);
20136          } else {
20137             /* udptl creation failed, T38 can not be supported on this dialog */
20138             ast_debug(1, "UDPTL creation failed on dialog.\n");
20139             ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
20140          }
20141       }
20142 
20143       /* We have a succesful authentication, process the SDP portion if there is one */
20144       if (find_sdp(req)) {
20145          if (process_sdp(p, req, SDP_T38_INITIATE)) {
20146             /* Unacceptable codecs */
20147             transmit_response_reliable(p, "488 Not acceptable here", req);
20148             p->invitestate = INV_COMPLETED;
20149             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20150             ast_debug(1, "No compatible codecs for this SIP call.\n");
20151             res = -1;
20152             goto request_invite_cleanup;
20153          }
20154       } else { /* No SDP in invite, call control session */
20155          p->jointcapability = p->capability;
20156          ast_debug(2, "No SDP in Invite, third party call control\n");
20157       }
20158 
20159       /* Queue NULL frame to prod ast_rtp_bridge if appropriate */
20160       /* This seems redundant ... see !p-owner above */
20161       if (p->owner)
20162          ast_queue_frame(p->owner, &ast_null_frame);
20163 
20164 
20165       /* Initialize the context if it hasn't been already */
20166       if (ast_strlen_zero(p->context))
20167          ast_string_field_set(p, context, sip_cfg.default_context);
20168 
20169 
20170       /* Check number of concurrent calls -vs- incoming limit HERE */
20171       ast_debug(1, "Checking SIP call limits for device %s\n", p->username);
20172       if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
20173          if (res < 0) {
20174             ast_log(LOG_NOTICE, "Failed to place call for device %s, too many calls\n", p->username);
20175             transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
20176             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20177             p->invitestate = INV_COMPLETED;
20178          }
20179          res = 0;
20180          goto request_invite_cleanup;
20181       }
20182       gotdest = get_destination(p, NULL); /* Get destination right away */
20183       get_rdnis(p, NULL);        /* Get redirect information */
20184       extract_uri(p, req);       /* Get the Contact URI */
20185       build_contact(p);       /* Build our contact header */
20186 
20187       if (p->rtp) {
20188          ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
20189          ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
20190       }
20191 
20192       if (!replace_id && gotdest) { /* No matching extension found */
20193          if (gotdest == 1 && ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP))
20194             transmit_response_reliable(p, "484 Address Incomplete", req);
20195          else {
20196             char *decoded_exten = ast_strdupa(p->exten);
20197 
20198             transmit_response_reliable(p, "404 Not Found", req);
20199             ast_uri_decode(decoded_exten);
20200             ast_log(LOG_NOTICE, "Call from '%s' to extension"
20201                " '%s' rejected because extension not found in context '%s'.\n",
20202                S_OR(p->username, p->peername), decoded_exten, p->context);
20203          }
20204          p->invitestate = INV_COMPLETED;
20205          update_call_counter(p, DEC_CALL_LIMIT);
20206          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20207          res = 0;
20208          goto request_invite_cleanup;
20209       } else {
20210 
20211          /* If no extension was specified, use the s one */
20212          /* Basically for calling to IP/Host name only */
20213          if (ast_strlen_zero(p->exten))
20214             ast_string_field_set(p, exten, "s");
20215          /* Initialize our tag */
20216 
20217          make_our_tag(p->tag, sizeof(p->tag));
20218          /* First invitation - create the channel */
20219          c = sip_new(p, AST_STATE_DOWN, S_OR(p->peername, NULL));
20220          *recount = 1;
20221 
20222          /* Save Record-Route for any later requests we make on this dialogue */
20223          build_route(p, req, 0);
20224 
20225          if (c) {
20226             /* Pre-lock the call */
20227             ast_channel_lock(c);
20228          }
20229       }
20230    } else {
20231       if (sipdebug) {
20232          if (!req->ignore)
20233             ast_debug(2, "Got a SIP re-invite for call %s\n", p->callid);
20234          else
20235             ast_debug(2, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
20236       }
20237       if (!req->ignore)
20238          reinvite = 1;
20239       c = p->owner;
20240    }
20241 
20242    /* Session-Timers */
20243    if (p->sipoptions & SIP_OPT_TIMER) {
20244       /* The UAC has requested session-timers for this session. Negotiate
20245       the session refresh interval and who will be the refresher */
20246       ast_debug(2, "Incoming INVITE with 'timer' option enabled\n");
20247 
20248       /* Allocate Session-Timers struct w/in the dialog */
20249       if (!p->stimer)
20250          sip_st_alloc(p);
20251 
20252       /* Parse the Session-Expires header */
20253       p_uac_se_hdr = get_header(req, "Session-Expires");
20254       if (!ast_strlen_zero(p_uac_se_hdr)) {
20255          rtn = parse_session_expires(p_uac_se_hdr, &uac_max_se, &st_ref);
20256          if (rtn != 0) {
20257             transmit_response_reliable(p, "400 Session-Expires Invalid Syntax", req);
20258             p->invitestate = INV_COMPLETED;
20259             if (!p->lastinvite) {
20260                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20261             }
20262             res = -1;
20263             goto request_invite_cleanup;
20264          }
20265       }
20266 
20267       /* Parse the Min-SE header */
20268       p_uac_min_se = get_header(req, "Min-SE");
20269       if (!ast_strlen_zero(p_uac_min_se)) {
20270          rtn = parse_minse(p_uac_min_se, &uac_min_se); 
20271          if (rtn != 0) {
20272             transmit_response_reliable(p, "400 Min-SE Invalid Syntax", req);
20273             p->invitestate = INV_COMPLETED;
20274             if (!p->lastinvite) {
20275                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20276             }
20277             res = -1;
20278             goto request_invite_cleanup;
20279          }
20280       }
20281 
20282       dlg_min_se = st_get_se(p, FALSE);
20283       switch (st_get_mode(p)) {
20284       case SESSION_TIMER_MODE_ACCEPT:
20285       case SESSION_TIMER_MODE_ORIGINATE:
20286          if (uac_max_se > 0 && uac_max_se < dlg_min_se) {
20287             transmit_response_with_minse(p, "422 Session Interval Too Small", req, dlg_min_se);
20288             p->invitestate = INV_COMPLETED;
20289             if (!p->lastinvite) {
20290                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20291             }
20292             res = -1;
20293             goto request_invite_cleanup;
20294          }
20295 
20296          p->stimer->st_active_peer_ua = TRUE;
20297          st_active = TRUE;
20298          if (st_ref == SESSION_TIMER_REFRESHER_AUTO) {
20299             st_ref = st_get_refresher(p);
20300          }
20301 
20302          if (uac_max_se > 0) {
20303             int dlg_max_se = st_get_se(p, TRUE);
20304             if (dlg_max_se >= uac_min_se) {
20305                st_interval = (uac_max_se < dlg_max_se) ? uac_max_se : dlg_max_se;
20306             } else {
20307                st_interval = uac_max_se;
20308             }
20309          } else {
20310             /* Set to default max value */
20311             st_interval = global_max_se;
20312          }
20313          break;
20314 
20315       case SESSION_TIMER_MODE_REFUSE:
20316          if (p->reqsipoptions & SIP_OPT_TIMER) {
20317             transmit_response_with_unsupported(p, "420 Option Disabled", req, required);
20318             ast_log(LOG_WARNING, "Received SIP INVITE with supported but disabled option: %s\n", required);
20319             p->invitestate = INV_COMPLETED;
20320             if (!p->lastinvite) {
20321                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20322             }
20323             res = -1;
20324             goto request_invite_cleanup;
20325          }
20326          break;
20327 
20328       default:
20329          ast_log(LOG_ERROR, "Internal Error %d at %s:%d\n", st_get_mode(p), __FILE__, __LINE__);
20330          break;
20331       }
20332    } else {
20333       /* The UAC did not request session-timers.  Asterisk (UAS), will now decide
20334       (based on session-timer-mode in sip.conf) whether to run session-timers for
20335       this session or not. */
20336       switch (st_get_mode(p)) {
20337       case SESSION_TIMER_MODE_ORIGINATE:
20338          st_active = TRUE;
20339          st_interval = st_get_se(p, TRUE);
20340          st_ref = SESSION_TIMER_REFRESHER_UAS;
20341          p->stimer->st_active_peer_ua = FALSE;
20342          break;
20343 
20344       default:
20345          break;
20346       }
20347    }
20348 
20349    if (reinvite == 0) {
20350       /* Session-Timers: Start session refresh timer based on negotiation/config */
20351       if (st_active == TRUE) {
20352          p->stimer->st_active   = TRUE;
20353          p->stimer->st_interval = st_interval;
20354          p->stimer->st_ref      = st_ref;
20355          start_session_timer(p);
20356       }
20357    } else {
20358       if (p->stimer->st_active == TRUE) {
20359          /* Session-Timers:  A re-invite request sent within a dialog will serve as 
20360          a refresh request, no matter whether the re-invite was sent for refreshing 
20361          the session or modifying it.*/
20362          ast_debug (2, "Restarting session-timers on a refresh - %s\n", p->callid);
20363 
20364          /* The UAC may be adjusting the session-timers mid-session */
20365          if (st_interval > 0) {
20366             p->stimer->st_interval = st_interval;
20367             p->stimer->st_ref      = st_ref;
20368          }
20369 
20370          restart_session_timer(p);
20371          if (p->stimer->st_expirys > 0) {
20372             p->stimer->st_expirys--;
20373          }
20374       }
20375    }
20376 
20377    if (!req->ignore && p)
20378       p->lastinvite = seqno;
20379 
20380    if (replace_id) { /* Attended transfer or call pickup - we're the target */
20381       if (!ast_strlen_zero(pickup.exten)) {
20382          append_history(p, "Xfer", "INVITE/Replace received");
20383 
20384          /* Let the caller know we're giving it a shot */
20385          transmit_response(p, "100 Trying", req);
20386          p->invitestate = INV_PROCEEDING;
20387          ast_setstate(c, AST_STATE_RING);
20388 
20389          /* Do the pickup itself */
20390          ast_channel_unlock(c);
20391          *nounlock = 1;
20392          do_magic_pickup(c, pickup.exten, pickup.context);
20393 
20394          /* Now we're either masqueraded or we failed to pickup, in either case we... */
20395          sip_pvt_unlock(p);
20396          ast_hangup(c);
20397          sip_pvt_lock(p);
20398 
20399          res = 0;
20400          goto request_invite_cleanup;
20401       } else {
20402          /* Go and take over the target call */
20403          if (sipdebug)
20404             ast_debug(4, "Sending this call to the invite/replcaes handler %s\n", p->callid);
20405          res = handle_invite_replaces(p, req, debug, seqno, sin, nounlock);
20406          refer_locked = 0;
20407          goto request_invite_cleanup;
20408       }
20409    }
20410 
20411 
20412    if (c) { /* We have a call  -either a new call or an old one (RE-INVITE) */
20413       enum ast_channel_state c_state = c->_state;
20414 
20415       if (c_state != AST_STATE_UP && reinvite &&
20416          (p->invitestate == INV_TERMINATED || p->invitestate == INV_CONFIRMED)) {
20417          /* If these conditions are true, and the channel is still in the 'ringing'
20418           * state, then this likely means that we have a situation where the initial
20419           * INVITE transaction has completed *but* the channel's state has not yet been
20420           * changed to UP. The reason this could happen is if the reinvite is received
20421           * on the SIP socket prior to an application calling ast_read on this channel
20422           * to read the answer frame we earlier queued on it. In this case, the reinvite
20423           * is completely legitimate so we need to handle this the same as if the channel 
20424           * were already UP. Thus we are purposely falling through to the AST_STATE_UP case.
20425           */
20426          c_state = AST_STATE_UP;
20427       }
20428 
20429       switch(c_state) {
20430       case AST_STATE_DOWN:
20431          ast_debug(2, "%s: New call is still down.... Trying... \n", c->name);
20432          transmit_provisional_response(p, "100 Trying", req, 0);
20433          p->invitestate = INV_PROCEEDING;
20434          ast_setstate(c, AST_STATE_RING);
20435          if (strcmp(p->exten, ast_pickup_ext())) { /* Call to extension -start pbx on this call */
20436             enum ast_pbx_result result;
20437 
20438             result = ast_pbx_start(c);
20439 
20440             switch(result) {
20441             case AST_PBX_FAILED:
20442                ast_log(LOG_WARNING, "Failed to start PBX :(\n");
20443                p->invitestate = INV_COMPLETED;
20444                transmit_response_reliable(p, "503 Unavailable", req);
20445                break;
20446             case AST_PBX_CALL_LIMIT:
20447                ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
20448                p->invitestate = INV_COMPLETED;
20449                transmit_response_reliable(p, "480 Temporarily Unavailable", req);
20450                break;
20451             case AST_PBX_SUCCESS:
20452                /* nothing to do */
20453                break;
20454             }
20455 
20456             if (result) {
20457 
20458                /* Unlock locks so ast_hangup can do its magic */
20459                ast_channel_unlock(c);
20460                sip_pvt_unlock(p);
20461                ast_hangup(c);
20462                sip_pvt_lock(p);
20463                c = NULL;
20464             }
20465          } else { /* Pickup call in call group */
20466             ast_channel_unlock(c);
20467             *nounlock = 1;
20468             if (ast_pickup_call(c)) {
20469                ast_log(LOG_NOTICE, "Nothing to pick up for %s\n", p->callid);
20470                transmit_response_reliable(p, "503 Unavailable", req);
20471                sip_alreadygone(p);
20472                /* Unlock locks so ast_hangup can do its magic */
20473                sip_pvt_unlock(p);
20474                c->hangupcause = AST_CAUSE_CALL_REJECTED;
20475             } else {
20476                sip_pvt_unlock(p);
20477                ast_setstate(c, AST_STATE_DOWN);
20478                c->hangupcause = AST_CAUSE_NORMAL_CLEARING;
20479             }
20480             p->invitestate = INV_COMPLETED;
20481             ast_hangup(c);
20482             sip_pvt_lock(p);
20483             c = NULL;
20484          }
20485          break;
20486       case AST_STATE_RING:
20487          transmit_provisional_response(p, "100 Trying", req, 0);
20488          p->invitestate = INV_PROCEEDING;
20489          break;
20490       case AST_STATE_RINGING:
20491          transmit_provisional_response(p, "180 Ringing", req, 0);
20492          p->invitestate = INV_PROCEEDING;
20493          break;
20494       case AST_STATE_UP:
20495          ast_debug(2, "%s: This call is UP.... \n", c->name);
20496 
20497          transmit_response(p, "100 Trying", req);
20498 
20499          if (p->t38.state == T38_PEER_REINVITE) {
20500             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."));
20501          } else if (p->t38.state == T38_ENABLED) {
20502             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
20503             transmit_response_with_t38_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ?  XMIT_UNRELIABLE : XMIT_CRITICAL)));
20504          } else if (p->t38.state == T38_DISABLED) {
20505             /* If this is not a re-invite or something to ignore - it's critical */
20506             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
20507             transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ?  XMIT_UNRELIABLE : XMIT_CRITICAL)), p->session_modify == TRUE ? FALSE:TRUE); 
20508          }
20509 
20510          p->invitestate = INV_TERMINATED;
20511          break;
20512       default:
20513          ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
20514          transmit_response(p, "100 Trying", req);
20515          break;
20516       }
20517    } else {
20518       if (p && (p->autokillid == -1)) {
20519          const char *msg;
20520 
20521          if (!p->jointcapability)
20522             msg = "488 Not Acceptable Here (codec error)";
20523          else {
20524             ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
20525             msg = "503 Unavailable";
20526          }
20527          transmit_response_reliable(p, msg, req);
20528          p->invitestate = INV_COMPLETED;
20529          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20530       }
20531    }
20532 
20533 request_invite_cleanup:
20534 
20535    if (refer_locked && p->refer && p->refer->refer_call) {
20536       sip_pvt_unlock(p->refer->refer_call);
20537       if (p->refer->refer_call->owner) {
20538          ast_channel_unlock(p->refer->refer_call->owner);
20539       }
20540    }
20541 
20542    return res;
20543 }
20544 
20545 /*! \brief  Find all call legs and bridge transferee with target 
20546  * called from handle_request_refer */
20547 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno)
20548 {
20549    struct sip_dual target;    /* Chan 1: Call from tranferer to Asterisk */
20550                /* Chan 2: Call from Asterisk to target */
20551    int res = 0;
20552    struct sip_pvt *targetcall_pvt;
20553 
20554    /* Check if the call ID of the replaces header does exist locally */
20555    if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag, 
20556       transferer->refer->replaces_callid_fromtag))) {
20557       if (transferer->refer->localtransfer) {
20558          /* We did not find the refered call. Sorry, can't accept then */
20559          transmit_response(transferer, "202 Accepted", req);
20560          /* Let's fake a response from someone else in order
20561             to follow the standard */
20562          transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
20563          append_history(transferer, "Xfer", "Refer failed");
20564          ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);  
20565          transferer->refer->status = REFER_FAILED;
20566          return -1;
20567       }
20568       /* Fall through for remote transfers that we did not find locally */
20569       ast_debug(3, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
20570       return 0;
20571    }
20572 
20573    /* Ok, we can accept this transfer */
20574    transmit_response(transferer, "202 Accepted", req);
20575    append_history(transferer, "Xfer", "Refer accepted");
20576    if (!targetcall_pvt->owner) { /* No active channel */
20577       ast_debug(4, "SIP attended transfer: Error: No owner of target call\n");
20578       /* Cancel transfer */
20579       transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
20580       append_history(transferer, "Xfer", "Refer failed");
20581       ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
20582       transferer->refer->status = REFER_FAILED;
20583       sip_pvt_unlock(targetcall_pvt);
20584       if (targetcall_pvt)
20585          ao2_t_ref(targetcall_pvt, -1, "Drop targetcall_pvt pointer");
20586       return -1;
20587    }
20588 
20589    /* We have a channel, find the bridge */
20590    target.chan1 = targetcall_pvt->owner;           /* Transferer to Asterisk */
20591    target.chan2 = ast_bridged_channel(targetcall_pvt->owner);  /* Asterisk to target */
20592 
20593    if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
20594       /* Wrong state of new channel */
20595       if (target.chan2) 
20596          ast_debug(4, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
20597       else if (target.chan1->_state != AST_STATE_RING)
20598          ast_debug(4, "SIP attended transfer: Error: No target channel\n");
20599       else
20600          ast_debug(4, "SIP attended transfer: Attempting transfer in ringing state\n");
20601    }
20602 
20603    /* Transfer */
20604    if (sipdebug) {
20605       if (current->chan2)  /* We have two bridges */
20606          ast_debug(4, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
20607       else        /* One bridge, propably transfer of IVR/voicemail etc */
20608          ast_debug(4, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
20609    }
20610 
20611    ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);   /* Delay hangup */
20612 
20613    /* Perform the transfer */
20614    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",
20615       transferer->owner->name,
20616       transferer->owner->uniqueid,
20617       transferer->callid,
20618       target.chan1->name,
20619       target.chan1->uniqueid);
20620    res = attempt_transfer(current, &target);
20621    sip_pvt_unlock(targetcall_pvt);
20622    if (res) {
20623       /* Failed transfer */
20624       transmit_notify_with_sipfrag(transferer, seqno, "486 Busy Here", TRUE);
20625       append_history(transferer, "Xfer", "Refer failed");
20626       if (targetcall_pvt->owner)
20627          ast_channel_unlock(targetcall_pvt->owner);
20628       ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
20629    } else {
20630       /* Transfer succeeded! */
20631       const char *xfersound = pbx_builtin_getvar_helper(target.chan1, "ATTENDED_TRANSFER_COMPLETE_SOUND");
20632 
20633       /* Tell transferer that we're done. */
20634       transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
20635       append_history(transferer, "Xfer", "Refer succeeded");
20636       transferer->refer->status = REFER_200OK;
20637       if (target.chan2 && !ast_strlen_zero(xfersound) && ast_streamfile(target.chan2, xfersound, target.chan2->language) >= 0) {
20638          ast_waitstream(target.chan2, "");
20639       }
20640       if (targetcall_pvt->owner) {
20641          ast_debug(1, "SIP attended transfer: Unlocking channel %s\n", targetcall_pvt->owner->name);
20642          ast_channel_unlock(targetcall_pvt->owner);
20643       }
20644    }
20645    if (targetcall_pvt)
20646       ao2_t_ref(targetcall_pvt, -1, "drop targetcall_pvt");
20647    return 1;
20648 }
20649 
20650 
20651 /*! \brief Handle incoming REFER request */
20652 /*! \page SIP_REFER SIP transfer Support (REFER)
20653 
20654    REFER is used for call transfer in SIP. We get a REFER
20655    to place a new call with an INVITE somwhere and then
20656    keep the transferor up-to-date of the transfer. If the
20657    transfer fails, get back on line with the orginal call. 
20658 
20659    - REFER can be sent outside or inside of a dialog.
20660      Asterisk only accepts REFER inside of a dialog.
20661 
20662    - If we get a replaces header, it is an attended transfer
20663 
20664    \par Blind transfers
20665    The transferor provides the transferee
20666    with the transfer targets contact. The signalling between
20667    transferer or transferee should not be cancelled, so the
20668    call is recoverable if the transfer target can not be reached 
20669    by the transferee.
20670 
20671    In this case, Asterisk receives a TRANSFER from
20672    the transferor, thus is the transferee. We should
20673    try to set up a call to the contact provided
20674    and if that fails, re-connect the current session.
20675    If the new call is set up, we issue a hangup.
20676    In this scenario, we are following section 5.2
20677    in the SIP CC Transfer draft. (Transfer without
20678    a GRUU)
20679 
20680    \par Transfer with consultation hold
20681    In this case, the transferor
20682    talks to the transfer target before the transfer takes place.
20683    This is implemented with SIP hold and transfer.
20684    Note: The invite From: string could indicate a transfer.
20685    (Section 6. Transfer with consultation hold)
20686    The transferor places the transferee on hold, starts a call
20687    with the transfer target to alert them to the impending
20688    transfer, terminates the connection with the target, then
20689    proceeds with the transfer (as in Blind transfer above)
20690 
20691    \par Attended transfer
20692    The transferor places the transferee
20693    on hold, calls the transfer target to alert them,
20694    places the target on hold, then proceeds with the transfer
20695    using a Replaces header field in the Refer-to header. This
20696    will force the transfee to send an Invite to the target,
20697    with a replaces header that instructs the target to
20698    hangup the call between the transferor and the target.
20699    In this case, the Refer/to: uses the AOR address. (The same
20700    URI that the transferee used to establish the session with
20701    the transfer target (To: ). The Require: replaces header should
20702    be in the INVITE to avoid the wrong UA in a forked SIP proxy
20703    scenario to answer and have no call to replace with.
20704 
20705    The referred-by header is *NOT* required, but if we get it,
20706    can be copied into the INVITE to the transfer target to 
20707    inform the target about the transferor
20708 
20709    "Any REFER request has to be appropriately authenticated.".
20710    
20711    We can't destroy dialogs, since we want the call to continue.
20712    
20713    */
20714 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock)
20715 {
20716    struct sip_dual current;   /* Chan1: Call between asterisk and transferer */
20717                /* Chan2: Call between asterisk and transferee */
20718 
20719    int res = 0;
20720    current.req.data = NULL;
20721 
20722    if (req->debug)
20723       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");
20724 
20725    if (!p->owner) {
20726       /* This is a REFER outside of an existing SIP dialog */
20727       /* We can't handle that, so decline it */
20728       ast_debug(3, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
20729       transmit_response(p, "603 Declined (No dialog)", req);
20730       if (!req->ignore) {
20731          append_history(p, "Xfer", "Refer failed. Outside of dialog.");
20732          sip_alreadygone(p);
20733          pvt_set_needdestroy(p, "outside of dialog");
20734       }
20735       return 0;
20736    }
20737 
20738 
20739    /* Check if transfer is allowed from this device */
20740    if (p->allowtransfer == TRANSFER_CLOSED ) {
20741       /* Transfer not allowed, decline */
20742       transmit_response(p, "603 Declined (policy)", req);
20743       append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
20744       /* Do not destroy SIP session */
20745       return 0;
20746    }
20747 
20748    if (!req->ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
20749       /* Already have a pending REFER */
20750       transmit_response(p, "491 Request pending", req);
20751       append_history(p, "Xfer", "Refer failed. Request pending.");
20752       return 0;
20753    }
20754 
20755    /* Allocate memory for call transfer data */
20756    if (!p->refer && !sip_refer_allocate(p)) {
20757       transmit_response(p, "500 Internal Server Error", req);
20758       append_history(p, "Xfer", "Refer failed. Memory allocation error.");
20759       return -3;
20760    }
20761 
20762    res = get_refer_info(p, req); /* Extract headers */
20763 
20764    p->refer->status = REFER_SENT;
20765 
20766    if (res != 0) {
20767       switch (res) {
20768       case -2: /* Syntax error */
20769          transmit_response(p, "400 Bad Request (Refer-to missing)", req);
20770          append_history(p, "Xfer", "Refer failed. Refer-to missing.");
20771          if (req->debug)
20772             ast_debug(1, "SIP transfer to black hole can't be handled (no refer-to: )\n");
20773          break;
20774       case -3:
20775          transmit_response(p, "603 Declined (Non sip: uri)", req);
20776          append_history(p, "Xfer", "Refer failed. Non SIP uri");
20777          if (req->debug)
20778             ast_debug(1, "SIP transfer to non-SIP uri denied\n");
20779          break;
20780       default:
20781          /* Refer-to extension not found, fake a failed transfer */
20782          transmit_response(p, "202 Accepted", req);
20783          append_history(p, "Xfer", "Refer failed. Bad extension.");
20784          transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
20785          ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
20786          if (req->debug)
20787             ast_debug(1, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
20788          break;
20789       } 
20790       return 0;
20791    }
20792    if (ast_strlen_zero(p->context))
20793       ast_string_field_set(p, context, sip_cfg.default_context);
20794 
20795    /* If we do not support SIP domains, all transfers are local */
20796    if (sip_cfg.allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
20797       p->refer->localtransfer = 1;
20798       if (sipdebug)
20799          ast_debug(3, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
20800    } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
20801       /* This PBX doesn't bother with SIP domains or domain is local, so this transfer is local */
20802       p->refer->localtransfer = 1;
20803    } else if (sipdebug)
20804          ast_debug(3, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
20805 
20806    /* Is this a repeat of a current request? Ignore it */
20807    /* Don't know what else to do right now. */
20808    if (req->ignore) 
20809       return res;
20810 
20811    /* If this is a blind transfer, we have the following
20812    channels to work with:
20813    - chan1, chan2: The current call between transferer and transferee (2 channels)
20814    - target_channel: A new call from the transferee to the target (1 channel)
20815    We need to stay tuned to what happens in order to be able
20816    to bring back the call to the transferer */
20817 
20818    /* If this is a attended transfer, we should have all call legs within reach:
20819    - chan1, chan2: The call between the transferer and transferee (2 channels)
20820    - target_channel, targetcall_pvt: The call between the transferer and the target (2 channels)
20821    We want to bridge chan2 with targetcall_pvt!
20822    
20823    The replaces call id in the refer message points
20824    to the call leg between Asterisk and the transferer.
20825    So we need to connect the target and the transferee channel
20826    and hangup the two other channels silently 
20827    
20828    If the target is non-local, the call ID could be on a remote
20829    machine and we need to send an INVITE with replaces to the
20830    target. We basically handle this as a blind transfer
20831    and let the sip_call function catch that we need replaces
20832    header in the INVITE.
20833    */
20834 
20835 
20836    /* Get the transferer's channel */
20837    current.chan1 = p->owner;
20838 
20839    /* Find the other part of the bridge (2) - transferee */
20840    current.chan2 = ast_bridged_channel(current.chan1);
20841    
20842    if (sipdebug)
20843       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>");
20844 
20845    if (!current.chan2 && !p->refer->attendedtransfer) {
20846       /* No bridged channel, propably IVR or echo or similar... */
20847       /* Guess we should masquerade or something here */
20848       /* Until we figure it out, refuse transfer of such calls */
20849       if (sipdebug)
20850          ast_debug(3, "Refused SIP transfer on non-bridged channel.\n");
20851       p->refer->status = REFER_FAILED;
20852       append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
20853       transmit_response(p, "603 Declined", req);
20854       return -1;
20855    }
20856 
20857    if (current.chan2) {
20858       if (sipdebug)
20859          ast_debug(4, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);
20860 
20861       ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
20862    }
20863 
20864    ast_set_flag(&p->flags[0], SIP_GOTREFER);
20865 
20866    /* Attended transfer: Find all call legs and bridge transferee with target*/
20867    if (p->refer->attendedtransfer) {
20868       if ((res = local_attended_transfer(p, &current, req, seqno)))
20869          return res; /* We're done with the transfer */
20870       /* Fall through for remote transfers that we did not find locally */
20871       if (sipdebug)
20872          ast_debug(4, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
20873       /* Fallthrough if we can't find the call leg internally */
20874    }
20875 
20876 
20877    /* Parking a call */
20878    if (p->refer->localtransfer && !strcmp(p->refer->refer_to, ast_parking_ext())) {
20879       /* Must release c's lock now, because it will not longer be accessible after the transfer! */
20880       *nounlock = 1;
20881       ast_channel_unlock(current.chan1);
20882       copy_request(&current.req, req);
20883       ast_clear_flag(&p->flags[0], SIP_GOTREFER);
20884       p->refer->status = REFER_200OK;
20885       append_history(p, "Xfer", "REFER to call parking.");
20886       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",
20887          current.chan1->name,
20888          current.chan1->uniqueid,
20889          p->callid,
20890          current.chan2->name,
20891          current.chan2->uniqueid,
20892          p->refer->refer_to);
20893       if (sipdebug)
20894          ast_debug(4, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
20895       sip_park(current.chan2, current.chan1, req, seqno);
20896       return res;
20897    } 
20898 
20899    /* Blind transfers and remote attended xfers */
20900    transmit_response(p, "202 Accepted", req);
20901 
20902    if (current.chan1 && current.chan2) {
20903       ast_debug(3, "chan1->name: %s\n", current.chan1->name);
20904       pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
20905    }
20906    if (current.chan2) {
20907       pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
20908       pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", p->refer->refer_to_domain);
20909       pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
20910       /* One for the new channel */
20911       pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
20912       /* Attended transfer to remote host, prepare headers for the INVITE */
20913       if (p->refer->referred_by) 
20914          pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", p->refer->referred_by);
20915    }
20916    /* Generate a Replaces string to be used in the INVITE during attended transfer */
20917    if (!ast_strlen_zero(p->refer->replaces_callid)) {
20918       char tempheader[SIPBUFSIZE];
20919       snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid, 
20920             p->refer->replaces_callid_totag ? ";to-tag=" : "", 
20921             p->refer->replaces_callid_totag, 
20922             p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
20923             p->refer->replaces_callid_fromtag);
20924       if (current.chan2)
20925          pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
20926    }
20927    /* Must release lock now, because it will not longer
20928       be accessible after the transfer! */
20929    *nounlock = 1;
20930    ast_channel_unlock(current.chan1);
20931 
20932    /* Connect the call */
20933 
20934    /* FAKE ringing if not attended transfer */
20935    if (!p->refer->attendedtransfer)
20936       transmit_notify_with_sipfrag(p, seqno, "183 Ringing", FALSE); 
20937 
20938    /* For blind transfer, this will lead to a new call */
20939    /* For attended transfer to remote host, this will lead to
20940       a new SIP call with a replaces header, if the dial plan allows it 
20941    */
20942    if (!current.chan2) {
20943       /* We have no bridge, so we're talking with Asterisk somehow */
20944       /* We need to masquerade this call */
20945       /* What to do to fix this situation:
20946          * Set up the new call in a new channel 
20947          * Let the new channel masq into this channel
20948          Please add that code here :-)
20949       */
20950       p->refer->status = REFER_FAILED;
20951       transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
20952       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
20953       append_history(p, "Xfer", "Refer failed (only bridged calls).");
20954       return -1;
20955    }
20956    ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);   /* Delay hangup */
20957 
20958 
20959    /* For blind transfers, move the call to the new extensions. For attended transfers on multiple
20960       servers - generate an INVITE with Replaces. Either way, let the dial plan decided  */
20961    res = ast_async_goto(current.chan2, p->refer->refer_to_context, p->refer->refer_to, 1);
20962 
20963    if (!res) {
20964       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",
20965          current.chan1->name,
20966          current.chan1->uniqueid,
20967          p->callid,
20968          current.chan2->name,
20969          current.chan2->uniqueid,
20970          p->refer->refer_to, p->refer->refer_to_context);
20971       /* Success  - we have a new channel */
20972       ast_debug(3, "%s transfer succeeded. Telling transferer.\n", p->refer->attendedtransfer? "Attended" : "Blind");
20973       transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
20974       if (p->refer->localtransfer)
20975          p->refer->status = REFER_200OK;
20976       if (p->owner)
20977          p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
20978       append_history(p, "Xfer", "Refer succeeded.");
20979       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
20980       /* Do not hangup call, the other side do that when we say 200 OK */
20981       /* We could possibly implement a timer here, auto congestion */
20982       res = 0;
20983    } else {
20984       ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Don't delay hangup */
20985       ast_debug(3, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
20986       append_history(p, "Xfer", "Refer failed.");
20987       /* Failure of some kind */
20988       p->refer->status = REFER_FAILED;
20989       transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
20990       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
20991       res = -1;
20992    }
20993    return res;
20994 }
20995 
20996 /*! \brief Handle incoming CANCEL request */
20997 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
20998 {
20999       
21000    check_via(p, req);
21001    sip_alreadygone(p);
21002 
21003    /* At this point, we could have cancelled the invite at the same time
21004       as the other side sends a CANCEL. Our final reply with error code
21005       might not have been received by the other side before the CANCEL
21006       was sent, so let's just give up retransmissions and waiting for
21007       ACK on our error code. The call is hanging up any way. */
21008    if (p->invitestate == INV_TERMINATED)
21009       __sip_pretend_ack(p);
21010    else
21011       p->invitestate = INV_CANCELLED;
21012    
21013    if (p->owner && p->owner->_state == AST_STATE_UP) {
21014       /* This call is up, cancel is ignored, we need a bye */
21015       transmit_response(p, "200 OK", req);
21016       ast_debug(1, "Got CANCEL on an answered call. Ignoring... \n");
21017       return 0;
21018    }
21019 
21020    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) 
21021       update_call_counter(p, DEC_CALL_LIMIT);
21022 
21023    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
21024    if (p->owner)
21025       ast_queue_hangup(p->owner);
21026    else
21027       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21028    if (p->initreq.len > 0) {
21029       struct sip_pkt *pkt, *prev_pkt;
21030       /* If the CANCEL we are receiving is a retransmission, and we already have scheduled
21031        * a reliable 487, then we don't want to schedule another one on top of the previous
21032        * one.
21033        *
21034        * As odd as this may sound, we can't rely on the previously-transmitted "reliable" 
21035        * response in this situation. What if we've sent all of our reliable responses 
21036        * already and now all of a sudden, we get this second CANCEL?
21037        *
21038        * The only way to do this correctly is to cancel our previously-scheduled reliably-
21039        * transmitted response and send a new one in its place.
21040        */
21041       for (pkt = p->packets, prev_pkt = NULL; pkt; prev_pkt = pkt, pkt = pkt->next) {
21042          if (pkt->seqno == p->lastinvite && pkt->response_code == 487) {
21043             AST_SCHED_DEL(sched, pkt->retransid);
21044             UNLINK(pkt, p->packets, prev_pkt);
21045             ast_free(pkt);
21046             break;
21047          }
21048       }
21049       transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
21050       transmit_response(p, "200 OK", req);
21051       return 1;
21052    } else {
21053       transmit_response(p, "481 Call Leg Does Not Exist", req);
21054       return 0;
21055    }
21056 }
21057 
21058 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen)
21059 {
21060    struct sip_pvt *p = chan->tech_pvt;
21061    char *all = "", *parse = ast_strdupa(preparse);
21062    int res = 0;
21063    AST_DECLARE_APP_ARGS(args,
21064       AST_APP_ARG(param);
21065       AST_APP_ARG(type);
21066       AST_APP_ARG(field);
21067    );
21068    AST_STANDARD_APP_ARGS(args, parse);
21069 
21070    /* Sanity check */
21071    if (!IS_SIP_TECH(chan->tech)) {
21072       ast_log(LOG_ERROR, "Cannot call %s on a non-SIP channel\n", funcname);
21073       return 0;
21074    }
21075 
21076    memset(buf, 0, buflen);
21077 
21078    if (p == NULL) {
21079       return -1;
21080    }
21081 
21082    if (!strcasecmp(args.param, "peerip")) {
21083       ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", buflen);
21084    } else if (!strcasecmp(args.param, "recvip")) {
21085       ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", buflen);
21086    } else if (!strcasecmp(args.param, "from")) {
21087       ast_copy_string(buf, p->from, buflen);
21088    } else if (!strcasecmp(args.param, "uri")) {
21089       ast_copy_string(buf, p->uri, buflen);
21090    } else if (!strcasecmp(args.param, "useragent")) {
21091       ast_copy_string(buf, p->useragent, buflen);
21092    } else if (!strcasecmp(args.param, "peername")) {
21093       ast_copy_string(buf, p->peername, buflen);
21094    } else if (!strcasecmp(args.param, "t38passthrough")) {
21095       ast_copy_string(buf, (p->t38.state == T38_DISABLED) ? "0" : "1", buflen);
21096    } else if (!strcasecmp(args.param, "rtpdest")) {
21097       struct sockaddr_in sin;
21098       struct ast_rtp *stream = NULL;
21099 
21100       if (ast_strlen_zero(args.type))
21101          args.type = "audio";
21102 
21103       if (!strcasecmp(args.type, "audio")) {
21104          stream = p->rtp;
21105       } else if (!strcasecmp(args.type, "video")) {
21106          stream = p->vrtp;
21107       } else if (!strcasecmp(args.type, "text")) {
21108          stream = p->trtp;
21109       } else {
21110          return -1;
21111       }
21112 
21113       if (!stream) {
21114          return -1;
21115       }
21116 
21117       ast_rtp_get_peer(stream, &sin);
21118       snprintf(buf, buflen, "%s:%d", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
21119    } else if (!strcasecmp(args.param, "rtpqos")) {
21120       struct ast_rtp_quality qos;
21121       struct ast_rtp *rtp = p->rtp;
21122       
21123       memset(&qos, 0, sizeof(qos));
21124 
21125       if (ast_strlen_zero(args.type))
21126          args.type = "audio";
21127       if (ast_strlen_zero(args.field))
21128          args.field = "all";
21129       
21130       if (!strcasecmp(args.type, "AUDIO")) {
21131          all = ast_rtp_get_quality(rtp = p->rtp, &qos, RTPQOS_SUMMARY);
21132       } else if (!strcasecmp(args.type, "VIDEO")) {
21133          all = ast_rtp_get_quality(rtp = p->vrtp, &qos, RTPQOS_SUMMARY);
21134       } else if (!strcasecmp(args.type, "TEXT")) {
21135          all = ast_rtp_get_quality(rtp = p->trtp, &qos, RTPQOS_SUMMARY);
21136       } else {
21137          return -1;
21138       }
21139       
21140       if (!strcasecmp(args.field, "local_ssrc"))
21141          snprintf(buf, buflen, "%u", qos.local_ssrc);
21142       else if (!strcasecmp(args.field, "local_lostpackets"))
21143          snprintf(buf, buflen, "%u", qos.local_lostpackets);
21144       else if (!strcasecmp(args.field, "local_jitter"))
21145          snprintf(buf, buflen, "%.0f", qos.local_jitter * 1000.0);
21146       else if (!strcasecmp(args.field, "local_count"))
21147          snprintf(buf, buflen, "%u", qos.local_count);
21148       else if (!strcasecmp(args.field, "remote_ssrc"))
21149          snprintf(buf, buflen, "%u", qos.remote_ssrc);
21150       else if (!strcasecmp(args.field, "remote_lostpackets"))
21151          snprintf(buf, buflen, "%u", qos.remote_lostpackets);
21152       else if (!strcasecmp(args.field, "remote_jitter"))
21153          snprintf(buf, buflen, "%.0f", qos.remote_jitter * 1000.0);
21154       else if (!strcasecmp(args.field, "remote_count"))
21155          snprintf(buf, buflen, "%u", qos.remote_count);
21156       else if (!strcasecmp(args.field, "rtt"))
21157          snprintf(buf, buflen, "%.0f", qos.rtt * 1000.0);
21158       else if (!strcasecmp(args.field, "all"))
21159          ast_copy_string(buf, all, buflen);
21160       else if (!ast_rtp_get_qos(rtp, args.field, buf, buflen))
21161           ;
21162       else {
21163          ast_log(LOG_WARNING, "Unrecognized argument '%s' to %s\n", preparse, funcname);
21164          return -1;
21165       }
21166    } else {
21167       res = -1;
21168    }
21169    return res;
21170 }
21171 
21172 /*! \brief Handle incoming BYE request */
21173 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
21174 {
21175    struct ast_channel *c=NULL;
21176    int res;
21177    struct ast_channel *bridged_to;
21178    
21179    /* If we have an INCOMING invite that we haven't answered, terminate that transaction */
21180    if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !req->ignore) {
21181       transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
21182    }
21183 
21184    __sip_pretend_ack(p);
21185 
21186    p->invitestate = INV_TERMINATED;
21187 
21188    copy_request(&p->initreq, req);
21189    if (sipdebug)
21190       ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
21191    check_via(p, req);
21192    sip_alreadygone(p);
21193 
21194    /* Get RTCP quality before end of call */
21195    if (p->do_history || p->owner) {
21196       struct ast_channel *bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
21197       char *videoqos, *textqos;
21198 
21199       /* We need to get the lock on bridge because ast_rtp_set_vars will attempt
21200        * to lock the bridge. This may get hairy...
21201        */
21202       while (bridge && ast_channel_trylock(bridge)) {
21203          ast_channel_unlock(p->owner);
21204          do {
21205             /* Can't use DEADLOCK_AVOIDANCE since p is an ao2 object */
21206             sip_pvt_unlock(p);
21207             usleep(1);
21208             sip_pvt_lock(p);
21209          } while (p->owner && ast_channel_trylock(p->owner));
21210          bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
21211       }
21212 
21213       if (p->rtp) {  
21214          if (p->do_history) {
21215             char *audioqos,
21216                  *audioqos_jitter,
21217                  *audioqos_loss,
21218                  *audioqos_rtt;
21219 
21220             audioqos        = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_SUMMARY);
21221             audioqos_jitter = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_JITTER);
21222             audioqos_loss   = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_LOSS);
21223             audioqos_rtt    = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_RTT);
21224 
21225             append_history(p, "RTCPaudio", "Quality:%s", audioqos);
21226             append_history(p, "RTCPaudioJitter", "Quality:%s", audioqos_jitter);
21227             append_history(p, "RTCPaudioLoss", "Quality:%s", audioqos_loss);
21228             append_history(p, "RTCPaudioRTT", "Quality:%s", audioqos_rtt);
21229          }
21230          
21231          if (p->owner) {
21232             ast_rtp_set_vars(p->owner, p->rtp);
21233          }
21234       }
21235 
21236       if (bridge) {
21237          struct sip_pvt *q = bridge->tech_pvt;
21238 
21239          if (IS_SIP_TECH(bridge->tech) && q && q->rtp)
21240             ast_rtp_set_vars(bridge, q->rtp);
21241          ast_channel_unlock(bridge);
21242       }
21243 
21244       if (p->vrtp) {
21245          videoqos = ast_rtp_get_quality(p->vrtp, NULL, RTPQOS_SUMMARY);
21246          if (p->do_history)
21247             append_history(p, "RTCPvideo", "Quality:%s", videoqos);
21248          if (p->owner)
21249             pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", videoqos);
21250       }
21251 
21252       if (p->trtp) {
21253          textqos = ast_rtp_get_quality(p->trtp, NULL, RTPQOS_SUMMARY);
21254          if (p->do_history)
21255             append_history(p, "RTCPtext", "Quality:%s", textqos);
21256          if (p->owner)
21257             pbx_builtin_setvar_helper(p->owner, "RTPTEXTQOS", textqos);
21258       }
21259    }
21260 
21261    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
21262    stop_session_timer(p); /* Stop Session-Timer */
21263 
21264    if (!ast_strlen_zero(get_header(req, "Also"))) {
21265       ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method.  Ask vendor to support REFER instead\n",
21266          ast_inet_ntoa(p->recv.sin_addr));
21267       if (ast_strlen_zero(p->context))
21268          ast_string_field_set(p, context, sip_cfg.default_context);
21269       res = get_also_info(p, req);
21270       if (!res) {
21271          c = p->owner;
21272          if (c) {
21273             bridged_to = ast_bridged_channel(c);
21274             if (bridged_to) {
21275                /* Don't actually hangup here... */
21276                ast_queue_control(c, AST_CONTROL_UNHOLD);
21277                ast_async_goto(bridged_to, p->context, p->refer->refer_to, 1);
21278             } else
21279                ast_queue_hangup(p->owner);
21280          }
21281       } else {
21282          ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_inet_ntoa(p->recv.sin_addr));
21283          if (p->owner)
21284             ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
21285       }
21286    } else if (p->owner) {
21287       ast_queue_hangup(p->owner);
21288       ast_debug(3, "Received bye, issuing owner hangup\n");
21289    } else {
21290       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21291       ast_debug(3, "Received bye, no owner, selfdestruct soon.\n");
21292    }
21293    ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21294    transmit_response(p, "200 OK", req);
21295 
21296    return 1;
21297 }
21298 
21299 /*! \brief Handle incoming MESSAGE request */
21300 static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
21301 {
21302    if (!req->ignore) {
21303       if (req->debug)
21304          ast_verbose("Receiving message!\n");
21305       receive_message(p, req);
21306    } else
21307       transmit_response(p, "202 Accepted", req);
21308    return 1;
21309 }
21310 
21311 static void add_peer_mwi_subs(struct sip_peer *peer)
21312 {
21313    struct sip_mailbox *mailbox;
21314 
21315    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
21316       mailbox->event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, peer,
21317          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
21318          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
21319          AST_EVENT_IE_END);
21320    }
21321 }
21322 
21323 /*! \brief  Handle incoming SUBSCRIBE request */
21324 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
21325 {
21326    int gotdest = 0;
21327    int res = 0;
21328    int firststate = AST_EXTENSION_REMOVED;
21329    struct sip_peer *authpeer = NULL;
21330    const char *eventheader = get_header(req, "Event");   /* Get Event package name */
21331    const char *acceptheader = get_header(req, "Accept");
21332    int resubscribe = (p->subscribed != NONE);
21333    char *temp, *event;
21334    struct ao2_iterator i;
21335 
21336    if (p->initreq.headers) {  
21337       /* We already have a dialog */
21338       if (p->initreq.method != SIP_SUBSCRIBE) {
21339          /* This is a SUBSCRIBE within another SIP dialog, which we do not support */
21340          /* For transfers, this could happen, but since we haven't seen it happening, let us just refuse this */
21341          transmit_response(p, "403 Forbidden (within dialog)", req);
21342          /* Do not destroy session, since we will break the call if we do */
21343          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);
21344          return 0;
21345       } else if (req->debug) {
21346          if (resubscribe)
21347             ast_debug(1, "Got a re-subscribe on existing subscription %s\n", p->callid);
21348          else
21349             ast_debug(1, "Got a new subscription %s (possibly with auth)\n", p->callid);
21350       }
21351    }
21352 
21353    /* Check if we have a global disallow setting on subscriptions. 
21354       if so, we don't have to check peer settings after auth, which saves a lot of processing
21355    */
21356    if (!sip_cfg.allowsubscribe) {
21357       transmit_response(p, "403 Forbidden (policy)", req);
21358       pvt_set_needdestroy(p, "forbidden");
21359       return 0;
21360    }
21361 
21362    if (!req->ignore && !resubscribe) { /* Set up dialog, new subscription */
21363       const char *to = get_header(req, "To");
21364       char totag[128];
21365 
21366       /* Check to see if a tag was provided, if so this is actually a resubscription of a dialog we no longer know about */
21367       if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
21368          if (req->debug)
21369             ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
21370          transmit_response(p, "481 Subscription does not exist", req);
21371          pvt_set_needdestroy(p, "subscription does not exist");
21372          return 0;
21373       }
21374 
21375       /* Use this as the basis */
21376       if (req->debug)
21377          ast_verbose("Creating new subscription\n");
21378 
21379       copy_request(&p->initreq, req);
21380       if (sipdebug)
21381          ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
21382       check_via(p, req);
21383       build_route(p, req, 0);
21384    } else if (req->debug && req->ignore)
21385       ast_verbose("Ignoring this SUBSCRIBE request\n");
21386 
21387    /* Find parameters to Event: header value and remove them for now */
21388    if (ast_strlen_zero(eventheader)) {
21389       transmit_response(p, "489 Bad Event", req);
21390       ast_debug(2, "Received SIP subscribe for unknown event package: <none>\n");
21391       pvt_set_needdestroy(p, "unknown event package in subscribe");
21392       return 0;
21393    }
21394 
21395    if ( (strchr(eventheader, ';'))) {
21396       event = ast_strdupa(eventheader);   /* Since eventheader is a const, we can't change it */
21397       temp = strchr(event, ';');       
21398       *temp = '\0';           /* Remove any options for now */
21399                      /* We might need to use them later :-) */
21400    } else
21401       event = (char *) eventheader;    /* XXX is this legal ? */
21402 
21403    /* Handle authentication */
21404    res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, sin, &authpeer);
21405    /* if an authentication response was sent, we are done here */
21406    if (res == AUTH_CHALLENGE_SENT)  /* authpeer = NULL here */
21407       return 0;
21408    if (res < 0) {
21409       if (res == AUTH_FAKE_AUTH) {
21410          ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
21411          transmit_fake_auth_response(p, SIP_SUBSCRIBE, req, XMIT_UNRELIABLE);
21412       } else {
21413          ast_log(LOG_NOTICE, "Failed to authenticate device %s for SUBSCRIBE\n", get_header(req, "From"));
21414          transmit_response_reliable(p, "403 Forbidden", req);
21415       }
21416       pvt_set_needdestroy(p, "authentication failed");
21417       return 0;
21418    }
21419 
21420    /* At this point, authpeer cannot be NULL. Remember we hold a reference,
21421     * so we must release it when done.
21422     * XXX must remove all the checks for authpeer == NULL.
21423     */
21424 
21425    /* Check if this device  is allowed to subscribe at all */
21426    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
21427       transmit_response(p, "403 Forbidden (policy)", req);
21428       pvt_set_needdestroy(p, "subscription not allowed");
21429       if (authpeer)
21430          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 1)");
21431       return 0;
21432    }
21433 
21434    if (strcmp(event, "message-summary")) {
21435       /* Get destination right away */
21436       gotdest = get_destination(p, NULL);
21437    }
21438 
21439    /* Get full contact header - this needs to be used as a request URI in NOTIFY's */
21440    parse_ok_contact(p, req);
21441 
21442    build_contact(p);
21443    if (gotdest) {
21444       transmit_response(p, "404 Not Found", req);
21445       pvt_set_needdestroy(p, "subscription target not found");
21446       if (authpeer)
21447          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
21448       return 0;
21449    }
21450 
21451    /* Initialize tag for new subscriptions */   
21452    if (ast_strlen_zero(p->tag))
21453       make_our_tag(p->tag, sizeof(p->tag));
21454 
21455    if (!strcmp(event, "presence") || !strcmp(event, "dialog")) { /* Presence, RFC 3842 */
21456       unsigned int pidf_xml;
21457 
21458       if (authpeer)  /* We do not need the authpeer any more */
21459          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
21460 
21461       /* Header from Xten Eye-beam Accept: multipart/related, application/rlmi+xml, application/pidf+xml, application/xpidf+xml */
21462 
21463       pidf_xml = strstr(acceptheader, "application/pidf+xml") ? 1 : 0;
21464 
21465       /* Older versions of Polycom firmware will claim pidf+xml, but really
21466        * they only support xpidf+xml. */
21467       if (pidf_xml && strstr(p->useragent, "Polycom")) {
21468          p->subscribed = XPIDF_XML;
21469       } else if (pidf_xml) {
21470          p->subscribed = PIDF_XML;         /* RFC 3863 format */
21471       } else if (strstr(acceptheader, "application/dialog-info+xml")) {
21472          p->subscribed = DIALOG_INFO_XML;
21473          /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
21474       } else if (strstr(acceptheader, "application/cpim-pidf+xml")) {
21475          p->subscribed = CPIM_PIDF_XML;    /* RFC 3863 format */
21476       } else if (strstr(acceptheader, "application/xpidf+xml")) {
21477          p->subscribed = XPIDF_XML;        /* Early pre-RFC 3863 format with MSN additions (Microsoft Messenger) */
21478       } else if (ast_strlen_zero(acceptheader)) {
21479          if (p->subscribed == NONE) { /* if the subscribed field is not already set, and there is no accept header... */
21480             transmit_response(p, "489 Bad Event", req);
21481   
21482             ast_log(LOG_WARNING, "SUBSCRIBE failure: no Accept header: pvt: stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
21483                p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
21484             pvt_set_needdestroy(p, "no Accept header");
21485             return 0;
21486          }
21487          /* if p->subscribed is non-zero, then accept is not obligatory; according to rfc 3265 section 3.1.3, at least.
21488             so, we'll just let it ride, keeping the value from a previous subscription, and not abort the subscription */
21489       } else {
21490          /* Can't find a format for events that we know about */
21491          char mybuf[200];
21492          snprintf(mybuf, sizeof(mybuf), "489 Bad Event (format %s)", acceptheader);
21493          transmit_response(p, mybuf, req);
21494  
21495          ast_log(LOG_WARNING, "SUBSCRIBE failure: unrecognized format: '%s' pvt: subscribed: %d, stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
21496             acceptheader, (int)p->subscribed, p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
21497          pvt_set_needdestroy(p, "unrecognized format");
21498          return 0;
21499       }
21500    } else if (!strcmp(event, "message-summary")) { 
21501       if (!ast_strlen_zero(acceptheader) && strcmp(acceptheader, "application/simple-message-summary")) {
21502          /* Format requested that we do not support */
21503          transmit_response(p, "406 Not Acceptable", req);
21504          ast_debug(2, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
21505          pvt_set_needdestroy(p, "unknown format");
21506          if (authpeer)
21507             unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 3)");
21508          return 0;
21509       }
21510       /* Looks like they actually want a mailbox status 
21511         This version of Asterisk supports mailbox subscriptions
21512         The subscribed URI needs to exist in the dial plan
21513         In most devices, this is configurable to the voicemailmain extension you use
21514       */
21515       if (!authpeer || AST_LIST_EMPTY(&authpeer->mailboxes)) {
21516          transmit_response(p, "404 Not found (no mailbox)", req);
21517          pvt_set_needdestroy(p, "received 404 response");
21518          ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", authpeer->name);
21519          if (authpeer)
21520             unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 4)");
21521          return 0;
21522       }
21523 
21524       p->subscribed = MWI_NOTIFICATION;
21525       if (ast_test_flag(&authpeer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY)) {
21526          add_peer_mwi_subs(authpeer);
21527       }
21528       if (authpeer->mwipvt && authpeer->mwipvt != p) {   /* Destroy old PVT if this is a new one */
21529          /* We only allow one subscription per peer */
21530          dialog_unlink_all(authpeer->mwipvt, TRUE, TRUE);
21531          authpeer->mwipvt = dialog_unref(authpeer->mwipvt, "unref dialog authpeer->mwipvt");
21532          /* sip_destroy(authpeer->mwipvt); */
21533       }
21534       if (authpeer->mwipvt)
21535          dialog_unref(authpeer->mwipvt, "Unref previously stored mwipvt dialog pointer");
21536       authpeer->mwipvt = dialog_ref(p, "setting peers' mwipvt to p");      /* Link from peer to pvt UH- should this be dialog_ref()? */
21537       if (p->relatedpeer)
21538          unref_peer(p->relatedpeer, "Unref previously stored relatedpeer ptr");
21539       p->relatedpeer = ref_peer(authpeer, "setting dialog's relatedpeer pointer");  /* already refcounted...Link from pvt to peer UH- should this be dialog_ref()? */
21540       /* Do not release authpeer here */
21541    } else { /* At this point, Asterisk does not understand the specified event */
21542       transmit_response(p, "489 Bad Event", req);
21543       ast_debug(2, "Received SIP subscribe for unknown event package: %s\n", event);
21544       pvt_set_needdestroy(p, "unknown event package");
21545       if (authpeer)
21546          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 5)");
21547       return 0;
21548    }
21549 
21550    /* Add subscription for extension state from the PBX core */
21551    if (p->subscribed != MWI_NOTIFICATION && !resubscribe) {
21552       if (p->stateid > -1) {
21553          ast_extension_state_del(p->stateid, cb_extensionstate);
21554          /* we need to dec the refcount, now that the extensionstate is removed */
21555          dialog_unref(p, "the extensionstate containing this dialog ptr was deleted");
21556       }
21557       p->stateid = ast_extension_state_add(p->context, p->exten, cb_extensionstate, dialog_ref(p,"copying dialog ptr into extension state struct"));
21558    }
21559 
21560    if (!req->ignore && p)
21561       p->lastinvite = seqno;
21562    if (p && !p->needdestroy) {
21563       p->expiry = atoi(get_header(req, "Expires"));
21564 
21565       /* check if the requested expiry-time is within the approved limits from sip.conf */
21566       if (p->expiry > max_expiry)
21567          p->expiry = max_expiry;
21568       if (p->expiry < min_expiry && p->expiry > 0)
21569          p->expiry = min_expiry;
21570 
21571       if (sipdebug) {
21572          if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
21573             ast_debug(2, "Adding subscription for mailbox notification - peer %s\n", p->relatedpeer->name);
21574          else
21575             ast_debug(2, "Adding subscription for extension %s context %s for peer %s\n", p->exten, p->context, p->username);
21576       }
21577       if (p->autokillid > -1 && sip_cancel_destroy(p))   /* Remove subscription expiry for renewals */
21578          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
21579       if (p->expiry > 0)
21580          sip_scheddestroy(p, (p->expiry + 10) * 1000);   /* Set timer for destruction of call at expiration */
21581 
21582       if (p->subscribed == MWI_NOTIFICATION) {
21583          ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21584          transmit_response(p, "200 OK", req);
21585          if (p->relatedpeer) {   /* Send first notification */
21586             ao2_lock(p->relatedpeer); /* was WRLOCK */
21587             sip_send_mwi_to_peer(p->relatedpeer, NULL, 0);
21588             ao2_unlock(p->relatedpeer);
21589          }
21590       } else {
21591          struct sip_pvt *p_old;
21592 
21593          if ((firststate = ast_extension_state(NULL, p->context, p->exten)) < 0) {
21594 
21595             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));
21596             transmit_response(p, "404 Not found", req);
21597             pvt_set_needdestroy(p, "no extension for SUBSCRIBE");
21598             return 0;
21599          }
21600          ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21601          transmit_response(p, "200 OK", req);
21602          transmit_state_notify(p, firststate, 1, FALSE); /* Send first notification */
21603          append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
21604          /* hide the 'complete' exten/context in the refer_to field for later display */
21605          ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
21606 
21607          /* remove any old subscription from this peer for the same exten/context,
21608          as the peer has obviously forgotten about it and it's wasteful to wait
21609          for it to expire and send NOTIFY messages to the peer only to have them
21610          ignored (or generate errors)
21611          */
21612          i = ao2_iterator_init(dialogs, 0);
21613          while ((p_old = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
21614             if (p_old == p) {
21615                ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before continue");
21616                continue;
21617             }
21618             if (p_old->initreq.method != SIP_SUBSCRIBE) {
21619                ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before continue");
21620                continue;
21621             }
21622             if (p_old->subscribed == NONE) {
21623                ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before continue");
21624                continue;
21625             }
21626             sip_pvt_lock(p_old);
21627             if (!strcmp(p_old->username, p->username)) {
21628                if (!strcmp(p_old->exten, p->exten) &&
21629                    !strcmp(p_old->context, p->context)) {
21630                   pvt_set_needdestroy(p_old, "replacing subscription");
21631                   sip_pvt_unlock(p_old);
21632                   ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before break");
21633                   break;
21634                }
21635             }
21636             sip_pvt_unlock(p_old);
21637             ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next");
21638          }
21639          ao2_iterator_destroy(&i);
21640       }
21641       if (!p->expiry) {
21642          pvt_set_needdestroy(p, "forcing expiration");
21643       }
21644    }
21645    return 1;
21646 }
21647 
21648 /*! \brief Handle incoming REGISTER request */
21649 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e)
21650 {
21651    enum check_auth_result res;
21652 
21653    /* Use this as the basis */
21654    copy_request(&p->initreq, req);
21655    if (sipdebug)
21656       ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
21657    check_via(p, req);
21658    if ((res = register_verify(p, sin, req, e)) < 0) {
21659       const char *reason;
21660 
21661       switch (res) {
21662       case AUTH_SECRET_FAILED:
21663          reason = "Wrong password";
21664          break;
21665       case AUTH_USERNAME_MISMATCH:
21666          reason = "Username/auth name mismatch";
21667          break;
21668       case AUTH_NOT_FOUND:
21669          reason = "No matching peer found";
21670          break;
21671       case AUTH_UNKNOWN_DOMAIN:
21672          reason = "Not a local domain";
21673          break;
21674       case AUTH_PEER_NOT_DYNAMIC:
21675          reason = "Peer is not supposed to register";
21676          break;
21677       case AUTH_ACL_FAILED:
21678          reason = "Device does not match ACL";
21679          break;
21680       case AUTH_BAD_TRANSPORT:
21681          reason = "Device not configured to use this transport type";
21682          break;
21683       default:
21684          reason = "Unknown failure";
21685          break;
21686       }
21687       ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
21688          get_header(req, "To"), ast_inet_ntoa(sin->sin_addr),
21689          reason);
21690       append_history(p, "RegRequest", "Failed : Account %s : %s", get_header(req, "To"), reason);
21691    } else
21692       append_history(p, "RegRequest", "Succeeded : Account %s", get_header(req, "To"));
21693 
21694    if (res < 1) {
21695       /* Destroy the session, but keep us around for just a bit in case they don't
21696          get our 200 OK */
21697       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21698    }
21699    return res;
21700 }
21701 
21702 /*! \brief Handle incoming SIP requests (methods) 
21703 \note This is where all incoming requests go first   */
21704 /* called with p and p->owner locked */
21705 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock)
21706 {
21707    /* Called with p->lock held, as well as p->owner->lock if appropriate, keeping things
21708       relatively static */
21709    const char *cmd;
21710    const char *cseq;
21711    const char *useragent;
21712    int seqno;
21713    int len;
21714    int respid;
21715    int res = 0;
21716    int debug = sip_debug_test_pvt(p);
21717    char *e;
21718    int error = 0;
21719    int oldmethod = p->method;
21720    int acked = 0;
21721 
21722    /* Get Method and Cseq */
21723    cseq = get_header(req, "Cseq");
21724    cmd = REQ_OFFSET_TO_STR(req, header[0]);
21725 
21726    /* Must have Cseq */
21727    if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq)) {
21728       ast_log(LOG_ERROR, "Missing Cseq. Dropping this SIP message, it's incomplete.\n");
21729       error = 1;
21730    }
21731    if (!error && sscanf(cseq, "%30d%n", &seqno, &len) != 1) {
21732       ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
21733       error = 1;
21734    }
21735    if (error) {
21736       if (!p->initreq.headers) { /* New call */
21737          pvt_set_needdestroy(p, "no headers");
21738       }
21739       return -1;
21740    }
21741    /* Get the command XXX */
21742 
21743    cmd = REQ_OFFSET_TO_STR(req, rlPart1);
21744    e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlPart2));
21745 
21746    /* Save useragent of the client */
21747    useragent = get_header(req, "User-Agent");
21748    if (!ast_strlen_zero(useragent))
21749       ast_string_field_set(p, useragent, useragent);
21750 
21751    /* Find out SIP method for incoming request */
21752    if (req->method == SIP_RESPONSE) {  /* Response to our request */
21753       /* ignore means "don't do anything with it" but still have to 
21754        * respond appropriately.
21755        * But in this case this is a response already, so we really
21756        * have nothing to do with this message, and even setting the
21757        * ignore flag is pointless.
21758        */
21759       if (ast_strlen_zero(e)) {
21760          return 0;
21761       }
21762       if (sscanf(e, "%30d %n", &respid, &len) != 1) {
21763          ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
21764          return 0;
21765       }
21766       if (respid <= 0) {
21767          ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
21768          return 0;
21769       }
21770       if (p->ocseq && (p->ocseq < seqno)) {
21771          if (option_debug)
21772             ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
21773          return -1;
21774       } else {
21775          if ((respid == 200) || ((respid >= 300) && (respid <= 399))) {
21776             extract_uri(p, req);
21777          }
21778          handle_response(p, respid, e + len, req, seqno);
21779       }
21780       return 0;
21781    }
21782 
21783    /* New SIP request coming in 
21784       (could be new request in existing SIP dialog as well...) 
21785     */         
21786    
21787    p->method = req->method;   /* Find out which SIP method they are using */
21788    ast_debug(4, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd); 
21789 
21790    if (p->icseq && (p->icseq > seqno) ) {
21791       if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
21792          ast_debug(2, "Got CANCEL or ACK on INVITE with transactions in between.\n");
21793       }  else {
21794          ast_debug(1, "Ignoring too old SIP packet packet %d (expecting >= %d)\n", seqno, p->icseq);
21795          if (req->method != SIP_ACK)
21796             transmit_response(p, "503 Server error", req);  /* We must respond according to RFC 3261 sec 12.2 */
21797          return -1;
21798       }
21799    } else if (p->icseq &&
21800          p->icseq == seqno &&
21801          req->method != SIP_ACK &&
21802          (p->method != SIP_CANCEL || p->alreadygone)) {
21803       /* ignore means "don't do anything with it" but still have to 
21804          respond appropriately.  We do this if we receive a repeat of
21805          the last sequence number  */
21806       req->ignore = 1;
21807       ast_debug(3, "Ignoring SIP message because of retransmit (%s Seqno %d, ours %d)\n", sip_methods[p->method].text, p->icseq, seqno);
21808    }
21809       
21810    if (seqno >= p->icseq)
21811       /* Next should follow monotonically (but not necessarily 
21812          incrementally -- thanks again to the genius authors of SIP --
21813          increasing */
21814       p->icseq = seqno;
21815 
21816    /* Find their tag if we haven't got it */
21817    if (ast_strlen_zero(p->theirtag)) {
21818       char tag[128];
21819 
21820       gettag(req, "From", tag, sizeof(tag));
21821       ast_string_field_set(p, theirtag, tag);
21822    }
21823    snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
21824 
21825    if (sip_cfg.pedanticsipchecking) {
21826       /* If this is a request packet without a from tag, it's not
21827          correct according to RFC 3261  */
21828       /* Check if this a new request in a new dialog with a totag already attached to it,
21829          RFC 3261 - section 12.2 - and we don't want to mess with recovery  */
21830       if (!p->initreq.headers && req->has_to_tag) {
21831          /* If this is a first request and it got a to-tag, it is not for us */
21832          if (!req->ignore && req->method == SIP_INVITE) {
21833             transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
21834             /* Will cease to exist after ACK */
21835          } else if (req->method != SIP_ACK) {
21836             transmit_response(p, "481 Call/Transaction Does Not Exist", req);
21837             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21838          } else {
21839             ast_debug(1, "Got ACK for unknown dialog... strange.\n");
21840          }
21841          return res;
21842       }
21843    }
21844 
21845    if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY)) {
21846       transmit_response(p, "400 Bad request", req);
21847       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21848       return -1;
21849    }
21850 
21851    /* Handle various incoming SIP methods in requests */
21852    switch (p->method) {
21853    case SIP_OPTIONS:
21854       res = handle_request_options(p, req);
21855       break;
21856    case SIP_INVITE:
21857       res = handle_request_invite(p, req, debug, seqno, sin, recount, e, nounlock);
21858       break;
21859    case SIP_REFER:
21860       res = handle_request_refer(p, req, debug, seqno, nounlock);
21861       break;
21862    case SIP_CANCEL:
21863       res = handle_request_cancel(p, req);
21864       break;
21865    case SIP_BYE:
21866       res = handle_request_bye(p, req);
21867       break;
21868    case SIP_MESSAGE:
21869       res = handle_request_message(p, req);
21870       break;
21871    case SIP_SUBSCRIBE:
21872       res = handle_request_subscribe(p, req, sin, seqno, e);
21873       break;
21874    case SIP_REGISTER:
21875       res = handle_request_register(p, req, sin, e);
21876       break;
21877    case SIP_INFO:
21878       if (req->debug)
21879          ast_verbose("Receiving INFO!\n");
21880       if (!req->ignore) 
21881          handle_request_info(p, req);
21882       else  /* if ignoring, transmit response */
21883          transmit_response(p, "200 OK", req);
21884       break;
21885    case SIP_NOTIFY:
21886       res = handle_request_notify(p, req, sin, seqno, e);
21887       break;
21888    case SIP_ACK:
21889       /* Make sure we don't ignore this */
21890       if (seqno == p->pendinginvite) {
21891          p->invitestate = INV_TERMINATED;
21892          p->pendinginvite = 0;
21893          acked = __sip_ack(p, seqno, 1 /* response */, 0);
21894          if (find_sdp(req)) {
21895             if (process_sdp(p, req, SDP_T38_NONE))
21896                return -1;
21897          }
21898          check_pendings(p);
21899       } else if (p->glareinvite == seqno) {
21900          /* handle ack for the 491 pending sent for glareinvite */
21901          p->glareinvite = 0;
21902          acked = __sip_ack(p, seqno, 1, 0);
21903       }
21904       if (!acked) {
21905          /* Got an ACK that did not match anything. Ignore
21906           * silently and restore previous method */
21907          p->method = oldmethod;
21908       }
21909       if (!p->lastinvite && ast_strlen_zero(p->randdata)) {
21910          pvt_set_needdestroy(p, "unmatched ACK");
21911       }
21912       break;
21913    default:
21914       transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
21915       ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n", 
21916          cmd, ast_inet_ntoa(p->sa.sin_addr));
21917       /* If this is some new method, and we don't have a call, destroy it now */
21918       if (!p->initreq.headers) {
21919          pvt_set_needdestroy(p, "unimplemented method");
21920       }
21921       break;
21922    }
21923    return res;
21924 }
21925 
21926 static void process_request_queue(struct sip_pvt *p, int *recount, int *nounlock)
21927 {
21928    struct sip_request *req;
21929 
21930    while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
21931       if (handle_incoming(p, req, &p->recv, recount, nounlock) == -1) {
21932          /* Request failed */
21933          if (option_debug) {
21934             ast_log(LOG_DEBUG, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
21935          }
21936       }
21937       ast_free(req);
21938    }
21939 }
21940 
21941 static int scheduler_process_request_queue(const void *data)
21942 {
21943    struct sip_pvt *p = (struct sip_pvt *) data;
21944    int recount = 0;
21945    int nounlock = 0;
21946    int lockretry;
21947 
21948    for (lockretry = 10; lockretry > 0; lockretry--) {
21949       sip_pvt_lock(p);
21950 
21951       /* lock the owner if it has one -- we may need it */
21952       /* because this is deadlock-prone, we need to try and unlock if failed */
21953       if (!p->owner || !ast_channel_trylock(p->owner)) {
21954          break;   /* locking succeeded */
21955       }
21956 
21957       if (lockretry != 1) {
21958          sip_pvt_unlock(p);
21959          /* Sleep for a very short amount of time */
21960          usleep(1);
21961       }
21962    }
21963 
21964    if (!lockretry) {
21965       int retry = !AST_LIST_EMPTY(&p->request_queue);
21966 
21967       /* we couldn't get the owner lock, which is needed to process
21968          the queued requests, so return a non-zero value, which will
21969          cause the scheduler to run this request again later if there
21970          still requests to be processed
21971       */
21972       sip_pvt_unlock(p);
21973       if (!retry) {
21974          dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
21975       }
21976       return retry;
21977    };
21978 
21979    process_request_queue(p, &recount, &nounlock);
21980    p->request_queue_sched_id = -1;
21981 
21982    if (p->owner && !nounlock) {
21983       ast_channel_unlock(p->owner);
21984    }
21985    sip_pvt_unlock(p);
21986 
21987    if (recount) {
21988       ast_update_use_count();
21989    }
21990 
21991    dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
21992 
21993    return 0;
21994 }
21995 
21996 static int queue_request(struct sip_pvt *p, const struct sip_request *req)
21997 {
21998    struct sip_request *newreq;
21999 
22000    if (!(newreq = ast_calloc(1, sizeof(*newreq)))) {
22001       return -1;
22002    }
22003 
22004    copy_request(newreq, req);
22005    AST_LIST_INSERT_TAIL(&p->request_queue, newreq, next);
22006    if (p->request_queue_sched_id == -1) {
22007       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) {
22008          dialog_unref(p, "Decrement refcount due to sched_add failure");
22009       }
22010    }
22011 
22012    return 0;
22013 }
22014 
22015 /*! \brief Read data from SIP UDP socket
22016 \note sipsock_read locks the owner channel while we are processing the SIP message
22017 \return 1 on error, 0 on success
22018 \note Successful messages is connected to SIP call and forwarded to handle_incoming() 
22019 */
22020 static int sipsock_read(int *id, int fd, short events, void *ignore)
22021 {
22022    struct sip_request req;
22023    struct sockaddr_in sin = { 0, };
22024    int res;
22025    socklen_t len = sizeof(sin);
22026    static char readbuf[65535];
22027 
22028    memset(&req, 0, sizeof(req));
22029    res = recvfrom(fd, readbuf, sizeof(readbuf) - 1, 0, (struct sockaddr *)&sin, &len);
22030    if (res < 0) {
22031 #if !defined(__FreeBSD__)
22032       if (errno == EAGAIN)
22033          ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
22034       else 
22035 #endif
22036       if (errno != ECONNREFUSED)
22037          ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
22038       return 1;
22039    }
22040 
22041    readbuf[res] = '\0';
22042 
22043    if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
22044       return 1;
22045    }
22046 
22047    if (ast_str_set(&req.data, 0, "%s", readbuf) == AST_DYNSTR_BUILD_FAILED) {
22048       return -1;
22049    }
22050 
22051    req.len = res;
22052    req.socket.fd = sipsock;
22053    set_socket_transport(&req.socket, SIP_TRANSPORT_UDP);
22054    req.socket.tcptls_session  = NULL;
22055    req.socket.port = bindaddr.sin_port;
22056 
22057    handle_request_do(&req, &sin);
22058    deinit_req(&req);
22059 
22060    return 1;
22061 }
22062 
22063 /*! \brief Handle incoming SIP message - request or response 
22064 
22065    This is used for all transports (udp, tcp and tcp/tls)
22066 */
22067 static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin) 
22068 {
22069    struct sip_pvt *p;
22070    int recount = 0;
22071    int nounlock = 0;
22072    int lockretry;
22073 
22074    if (sip_debug_test_addr(sin)) /* Set the debug flag early on packet level */
22075       req->debug = 1;
22076    if (sip_cfg.pedanticsipchecking)
22077       req->len = lws2sws(req->data->str, req->len);   /* Fix multiline headers */
22078    if (req->debug) {
22079       ast_verbose("\n<--- SIP read from %s:%s:%d --->\n%s\n<------------->\n", 
22080          get_transport(req->socket.type), ast_inet_ntoa(sin->sin_addr), 
22081          ntohs(sin->sin_port), req->data->str);
22082    }
22083 
22084    if (parse_request(req) == -1) { /* Bad packet, can't parse */
22085       ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
22086       return 1;
22087    }
22088    req->method = find_sip_method(REQ_OFFSET_TO_STR(req, rlPart1));
22089 
22090    if (req->debug)
22091       ast_verbose("--- (%d headers %d lines)%s ---\n", req->headers, req->lines, (req->headers + req->lines == 0) ? " Nat keepalive" : "");
22092 
22093    if (req->headers < 2) { /* Must have at least two headers */
22094       ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
22095       return 1;
22096    }
22097 
22098    /* Process request, with netlock held, and with usual deadlock avoidance */
22099    for (lockretry = 10; lockretry > 0; lockretry--) {
22100       ast_mutex_lock(&netlock);
22101 
22102       /* Find the active SIP dialog or create a new one */
22103       p = find_call(req, sin, req->method);  /* returns p locked */
22104       if (p == NULL) {
22105          ast_debug(1, "Invalid SIP message - rejected , no callid, len %d\n", req->len);
22106          ast_mutex_unlock(&netlock);
22107          return 1;
22108       }
22109 
22110       copy_socket_data(&p->socket, &req->socket);
22111 
22112       /* Go ahead and lock the owner if it has one -- we may need it */
22113       /* becaues this is deadlock-prone, we need to try and unlock if failed */
22114       if (!p->owner || !ast_channel_trylock(p->owner))
22115          break;   /* locking succeeded */
22116 
22117       if (lockretry != 1) {
22118          sip_pvt_unlock(p);
22119          ao2_t_ref(p, -1, "release p (from find_call) inside lockretry loop"); /* we'll look for it again, but p is dead now */
22120          ast_mutex_unlock(&netlock);
22121          /* Sleep for a very short amount of time */
22122          usleep(1);
22123       }
22124    }
22125    p->recv = *sin;
22126 
22127    if (p->do_history) /* This is a request or response, note what it was for */
22128       append_history(p, "Rx", "%s / %s / %s", req->data->str, get_header(req, "CSeq"), REQ_OFFSET_TO_STR(req, rlPart2));
22129 
22130    if (!lockretry) {
22131       if (!queue_request(p, req)) {
22132          /* the request has been queued for later handling */
22133          sip_pvt_unlock(p);
22134          ao2_t_ref(p, -1, "release p (from find_call) after queueing request");
22135          ast_mutex_unlock(&netlock);
22136          return 1;
22137       }
22138 
22139       if (p->owner)
22140          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 ??? - "));
22141       ast_log(LOG_ERROR, "SIP transaction failed: %s \n", p->callid);
22142       if (req->method != SIP_ACK)
22143          transmit_response(p, "503 Server error", req);  /* We must respond according to RFC 3261 sec 12.2 */
22144       /* XXX We could add retry-after to make sure they come back */
22145       append_history(p, "LockFail", "Owner lock failed, transaction failed.");
22146       sip_pvt_unlock(p);
22147       ao2_t_ref(p, -1, "release p (from find_call) at end of lockretry"); /* p is gone after the return */
22148       ast_mutex_unlock(&netlock);
22149       return 1;
22150    }
22151 
22152    /* if there are queued requests on this sip_pvt, process them first, so that everything is
22153       handled in order
22154    */
22155    if (!AST_LIST_EMPTY(&p->request_queue)) {
22156       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"));
22157       process_request_queue(p, &recount, &nounlock);
22158    }
22159 
22160    if (handle_incoming(p, req, sin, &recount, &nounlock) == -1) {
22161       /* Request failed */
22162       ast_debug(1, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
22163    }
22164       
22165    if (recount)
22166       ast_update_use_count();
22167 
22168    if (p->owner && !nounlock)
22169       ast_channel_unlock(p->owner);
22170    sip_pvt_unlock(p);
22171    ast_mutex_unlock(&netlock);
22172    ao2_t_ref(p, -1, "throw away dialog ptr from find_call at end of routine"); /* p is gone after the return */
22173    return 1;
22174 }
22175 
22176 /*! \brief Returns the port to use for this socket
22177  *
22178  * \param type The type of transport used
22179  * \param port Port we are checking to see if it's the standard port.
22180  * \note port is expected in host byte order
22181  */
22182 static int sip_standard_port(enum sip_transport type, int port)
22183 {
22184    if (type & SIP_TRANSPORT_TLS)
22185       return port == STANDARD_TLS_PORT;
22186    else
22187       return port == STANDARD_SIP_PORT;
22188 }
22189 
22190 static int threadinfo_locate_cb(void *obj, void *arg, int flags)
22191 {
22192    struct sip_threadinfo *th = obj;
22193    struct sockaddr_in *s = arg;
22194 
22195    if (!inaddrcmp(&th->tcptls_session->remote_address, s)) {
22196       return CMP_MATCH | CMP_STOP;
22197    }
22198 
22199    return 0;
22200 }
22201 
22202 /*! 
22203  * \brief Find thread for TCP/TLS session (based on IP/Port 
22204  *
22205  * \note This function returns an astobj2 reference
22206  */
22207 static struct ast_tcptls_session_instance *sip_tcp_locate(struct sockaddr_in *s)
22208 {
22209    struct sip_threadinfo *th;
22210    struct ast_tcptls_session_instance *tcptls_instance = NULL;
22211 
22212    if ((th = ao2_callback(threadt, 0, threadinfo_locate_cb, s))) {
22213       tcptls_instance = (ao2_ref(th->tcptls_session, +1), th->tcptls_session);
22214       ao2_t_ref(th, -1, "decrement ref from callback");
22215    }
22216    return tcptls_instance;
22217 }
22218 
22219 /*! \todo Get socket for dialog, prepare if needed, and return file handle  */
22220 static int sip_prepare_socket(struct sip_pvt *p) 
22221 {
22222    struct sip_socket *s = &p->socket;
22223    static const char name[] = "SIP socket";
22224    struct sip_threadinfo *th = NULL;
22225    struct ast_tcptls_session_instance *tcptls_session;
22226    struct ast_tcptls_session_args tmp_ca = {
22227       .name = name,
22228       .accept_fd = -1,
22229    };
22230    struct ast_tcptls_session_args *ca;
22231 
22232    /* check to see if a socket is already active */
22233    if ((s->fd != -1) && (s->type == SIP_TRANSPORT_UDP)) {
22234       return s->fd;
22235    }
22236    if ((s->type & (SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS)) &&
22237          (s->tcptls_session) &&
22238          (s->tcptls_session->fd != -1)) {
22239       return s->tcptls_session->fd;
22240    }
22241 
22242    /*! \todo Check this... This might be wrong, depending on the proxy configuration
22243       If proxy is in "force" mode its correct.
22244     */
22245    if (p->outboundproxy && p->outboundproxy->transport) {
22246       s->type = p->outboundproxy->transport;
22247    }
22248 
22249    if (s->type == SIP_TRANSPORT_UDP) {
22250       s->fd = sipsock;
22251       return s->fd;
22252    }
22253 
22254    /* At this point we are dealing with a TCP/TLS connection
22255     * 1. We need to check to see if a connectin thread exists
22256     *    for this address, if so use that.
22257     * 2. If a thread does not exist for this address, but the tcptls_session
22258     *    exists on the socket, the connection was closed.
22259     * 3. If no tcptls_session thread exists for the address, and no tcptls_session
22260     *    already exists on the socket, create a new one and launch a new thread.
22261     */
22262 
22263    /* 1.  check for existing threads */
22264    tmp_ca.remote_address = *(sip_real_dst(p));
22265    if ((tcptls_session = sip_tcp_locate(&tmp_ca.remote_address))) {
22266       s->fd = tcptls_session->fd;
22267       if (s->tcptls_session) {
22268          ao2_ref(s->tcptls_session, -1);
22269          s->tcptls_session = NULL;
22270       }
22271       s->tcptls_session = tcptls_session;
22272       return s->fd;
22273    /* 2.  Thread not found, if tcptls_session already exists, it once had a thread and is now terminated */
22274    } else if (s->tcptls_session) {
22275       return s->fd; /* XXX whether reconnection is ever necessary here needs to be investigated further */
22276    }
22277 
22278    /* 3.  Create a new TCP/TLS client connection */
22279    /* create new session arguments for the client connection */
22280    if (!(ca = ao2_alloc(sizeof(*ca), sip_tcptls_client_args_destructor)) ||
22281       !(ca->name = ast_strdup(name))) {
22282       goto create_tcptls_session_fail;
22283    }
22284    ca->accept_fd = -1;
22285    ca->remote_address = *(sip_real_dst(p));
22286    /* if type is TLS, we need to create a tls cfg for this session arg */
22287    if (s->type == SIP_TRANSPORT_TLS) {
22288       if (!(ca->tls_cfg = ast_calloc(1, sizeof(*ca->tls_cfg)))) {
22289          goto create_tcptls_session_fail;
22290       }
22291       memcpy(ca->tls_cfg, &default_tls_cfg, sizeof(*ca->tls_cfg));
22292 
22293       if (!(ca->tls_cfg->certfile = ast_strdup(default_tls_cfg.certfile)) ||
22294          !(ca->tls_cfg->cipher = ast_strdup(default_tls_cfg.cipher)) ||
22295          !(ca->tls_cfg->cafile = ast_strdup(default_tls_cfg.cafile)) ||
22296          !(ca->tls_cfg->capath = ast_strdup(default_tls_cfg.capath))) {
22297 
22298          goto create_tcptls_session_fail;
22299       }
22300 
22301       /* this host is used as the common name in ssl/tls */
22302       if (!ast_strlen_zero(p->tohost)) {
22303          ast_copy_string(ca->hostname, p->tohost, sizeof(ca->hostname));
22304       }
22305    }
22306    /* Create a client connection for address, this does not start the connection, just sets it up. */
22307    if (!(s->tcptls_session = ast_tcptls_client_create(ca))) {
22308       goto create_tcptls_session_fail;
22309    }
22310 
22311    s->fd = s->tcptls_session->fd;
22312 
22313    /* client connections need to have the sip_threadinfo object created before
22314     * the thread is detached.  This ensures the alert_pipe is up before it will
22315     * be used.  Note that this function links the new threadinfo object into the
22316     * threadt container. */
22317    if (!(th = sip_threadinfo_create(s->tcptls_session, s->type))) {
22318       goto create_tcptls_session_fail;
22319 
22320    }
22321 
22322    /* Give the new thread a reference to the tcptls_session */
22323    ao2_ref(s->tcptls_session, +1);
22324 
22325    if (ast_pthread_create_background(&ca->master, NULL, sip_tcp_worker_fn, s->tcptls_session)) {
22326       ast_debug(1, "Unable to launch '%s'.", ca->name);
22327       ao2_ref(s->tcptls_session, -1); /* take away the thread ref we just gave it */
22328       goto create_tcptls_session_fail;
22329    }
22330 
22331    return s->fd;
22332 
22333 create_tcptls_session_fail:
22334    if (ca) {
22335       ao2_t_ref(ca, -1, "failed to create client, getting rid of client tcptls_session arguments");
22336    }
22337    if (s->tcptls_session) {
22338       close(tcptls_session->fd);
22339       s->fd = tcptls_session->fd = -1;
22340       ao2_ref(s->tcptls_session, -1);
22341       s->tcptls_session = NULL;
22342    }
22343    if (th) {
22344       ao2_t_unlink(threadt, th, "Removing tcptls thread info object, thread failed to open");
22345    }
22346 
22347    return -1;
22348 }
22349 
22350 /*!
22351  * \brief Small function to parse a config line for a host with a transport
22352  *        i.e. tls://www.google.com:8056
22353  */
22354 static int sip_parse_host(char *line, int lineno, char **hostname, int *portnum, enum sip_transport *transport)
22355 {
22356    char *port;
22357 
22358    if ((*hostname = strstr(line, "://"))) {
22359       *hostname += 3;
22360 
22361       if (!strncasecmp(line, "tcp", 3))
22362          *transport = SIP_TRANSPORT_TCP;
22363       else if (!strncasecmp(line, "tls", 3))
22364          *transport = SIP_TRANSPORT_TLS;
22365       else if (!strncasecmp(line, "udp", 3))
22366          *transport = SIP_TRANSPORT_UDP;
22367       else
22368          ast_log(LOG_NOTICE, "'%.3s' is not a valid transport type on line %d of sip.conf. defaulting to udp.\n", line, lineno);
22369    } else {
22370       *hostname = line;
22371       *transport = SIP_TRANSPORT_UDP;
22372    }
22373 
22374    if ((line = strrchr(*hostname, '@')))
22375       line++;
22376    else
22377       line = *hostname;
22378 
22379    if ((port = strrchr(line, ':'))) {
22380       *port++ = '\0';
22381 
22382       if (!sscanf(port, "%5u", portnum)) {
22383          ast_log(LOG_NOTICE, "'%s' is not a valid port number on line %d of sip.conf. using default.\n", port, lineno);
22384          port = NULL;
22385       }
22386    }
22387 
22388    if (!port) {
22389       if (*transport & SIP_TRANSPORT_TLS) {
22390          *portnum = STANDARD_TLS_PORT;
22391       } else {
22392          *portnum = STANDARD_SIP_PORT;
22393       }
22394    }
22395 
22396    return 0;
22397 }
22398 
22399 /*!
22400  * \brief Get cached MWI info
22401  * \retval 0 At least one message is waiting
22402  * \retval 1 no messages waiting
22403  */
22404 static int get_cached_mwi(struct sip_peer *peer, int *new, int *old)
22405 {
22406    struct sip_mailbox *mailbox;
22407 
22408    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
22409       struct ast_event *event;
22410       event = ast_event_get_cached(AST_EVENT_MWI,
22411          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
22412          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
22413          AST_EVENT_IE_END);
22414       if (!event)
22415          continue;
22416       *new += ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
22417       *old += ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
22418       ast_event_destroy(event);
22419    }
22420 
22421    return (*new || *old) ? 0 : 1;
22422 }
22423 
22424 /*! \brief Send message waiting indication to alert peer that they've got voicemail */
22425 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only)
22426 {
22427    /* Called with peerl lock, but releases it */
22428    struct sip_pvt *p;
22429    int newmsgs = 0, oldmsgs = 0;
22430 
22431    if (ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY) && !peer->mwipvt)
22432       return 0;
22433 
22434    /* Do we have an IP address? If not, skip this peer */
22435    if (!peer->addr.sin_addr.s_addr && !peer->defaddr.sin_addr.s_addr) 
22436       return 0;
22437 
22438    if (event) {
22439       newmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
22440       oldmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
22441    } else if (!cache_only) { /* Fall back to manually checking the mailbox */
22442       struct ast_str *mailbox_str = ast_str_alloca(512);
22443       peer_mailboxes_to_str(&mailbox_str, peer);
22444       ast_app_inboxcount(mailbox_str->str, &newmsgs, &oldmsgs);
22445    } else {
22446       get_cached_mwi(peer, &newmsgs, &oldmsgs);
22447    }
22448    
22449    if (peer->mwipvt) {
22450       /* Base message on subscription */
22451       p = dialog_ref(peer->mwipvt, "sip_send_mwi_to_peer: Setting dialog ptr p from peer->mwipvt-- should this be done?");
22452    } else {
22453       /* Build temporary dialog for this message */
22454       if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) 
22455          return -1;
22456       /* If we don't set the socket type to 0, then create_addr_from_peer will fail immediately if the peer
22457        * uses any transport other than UDP. We set the type to 0 here and then let create_addr_from_peer copy 
22458        * the peer's socket information to the sip_pvt we just allocated
22459        */
22460       set_socket_transport(&p->socket, 0);
22461       if (create_addr_from_peer(p, peer)) {
22462          /* Maybe they're not registered, etc. */
22463          dialog_unlink_all(p, TRUE, TRUE);
22464          dialog_unref(p, "unref dialog p just created via sip_alloc");
22465          /* sip_destroy(p); */
22466          return 0;
22467       }
22468       /* Recalculate our side, and recalculate Call ID */
22469       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
22470       build_via(p);
22471       ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
22472       build_callid_pvt(p);
22473       ao2_t_link(dialogs, p, "Linking in under new name");
22474       /* Destroy this session after 32 secs */
22475       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22476    }
22477 
22478    /* Send MWI */
22479    ast_set_flag(&p->flags[0], SIP_OUTGOING);
22480    /* the following will decrement the refcount on p as it finishes */
22481    transmit_notify_with_mwi(p, newmsgs, oldmsgs, peer->vmexten);
22482    dialog_unref(p, "unref dialog ptr p just before it goes out of scope at the end of sip_send_mwi_to_peer.");
22483    return 0;
22484 }
22485 
22486 /*! \brief helper function for the monitoring thread -- seems to be called with the assumption that the dialog is locked */
22487 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t)
22488 {
22489    /* If we have no RTP or no active owner, no need to check timers */
22490    if (!dialog->rtp || !dialog->owner)
22491       return;
22492    /* If the call is not in UP state or redirected outside Asterisk, no need to check timers */
22493 
22494    if (dialog->owner->_state != AST_STATE_UP || dialog->redirip.sin_addr.s_addr)
22495       return;
22496 
22497    /* If the call is involved in a T38 fax session do not check RTP timeout */
22498    if (dialog->t38.state == T38_ENABLED)
22499       return;
22500 
22501    /* If we have no timers set, return now */
22502    if ((ast_rtp_get_rtpkeepalive(dialog->rtp) == 0) && (ast_rtp_get_rtptimeout(dialog->rtp) == 0) && (ast_rtp_get_rtpholdtimeout(dialog->rtp) == 0))
22503       return;
22504 
22505    /* Check AUDIO RTP keepalives */
22506    if (dialog->lastrtptx && ast_rtp_get_rtpkeepalive(dialog->rtp) &&
22507           (t > dialog->lastrtptx + ast_rtp_get_rtpkeepalive(dialog->rtp))) {
22508       /* Need to send an empty RTP packet */
22509       dialog->lastrtptx = time(NULL);
22510       ast_rtp_sendcng(dialog->rtp, 0);
22511    }
22512 
22513    /*! \todo Check video RTP keepalives
22514 
22515       Do we need to move the lastrtptx to the RTP structure to have one for audio and one
22516       for video? It really does belong to the RTP structure.
22517    */
22518 
22519    /* Check AUDIO RTP timers */
22520    if (dialog->lastrtprx && (ast_rtp_get_rtptimeout(dialog->rtp) || ast_rtp_get_rtpholdtimeout(dialog->rtp)) &&
22521           (t > dialog->lastrtprx + ast_rtp_get_rtptimeout(dialog->rtp))) {
22522 
22523       /* Might be a timeout now -- see if we're on hold */
22524       struct sockaddr_in sin;
22525       ast_rtp_get_peer(dialog->rtp, &sin);
22526       if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD) || (ast_rtp_get_rtpholdtimeout(dialog->rtp) &&
22527            (t > dialog->lastrtprx + ast_rtp_get_rtpholdtimeout(dialog->rtp)))) {
22528          /* Needs a hangup */
22529          if (ast_rtp_get_rtptimeout(dialog->rtp)) {
22530             while (dialog->owner && ast_channel_trylock(dialog->owner)) {
22531                sip_pvt_unlock(dialog);
22532                usleep(1);
22533                sip_pvt_lock(dialog);
22534             }
22535             if (!dialog->owner) {
22536                return; /* channel hangup can occur during deadlock avoidance. */
22537             }
22538             ast_log(LOG_NOTICE, "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
22539                dialog->owner->name, (long) (t - dialog->lastrtprx));
22540             /* Issue a softhangup */
22541             ast_softhangup_nolock(dialog->owner, AST_SOFTHANGUP_DEV);
22542             ast_channel_unlock(dialog->owner);
22543             /* forget the timeouts for this call, since a hangup
22544                has already been requested and we don't want to
22545                repeatedly request hangups
22546             */
22547             ast_rtp_set_rtptimeout(dialog->rtp, 0);
22548             ast_rtp_set_rtpholdtimeout(dialog->rtp, 0);
22549             if (dialog->vrtp) {
22550                ast_rtp_set_rtptimeout(dialog->vrtp, 0);
22551                ast_rtp_set_rtpholdtimeout(dialog->vrtp, 0);
22552             }
22553          }
22554       }
22555    }
22556 }
22557 
22558 /*! \brief The SIP monitoring thread 
22559 \note This thread monitors all the SIP sessions and peers that needs notification of mwi
22560    (and thus do not have a separate thread) indefinitely 
22561 */
22562 static void *do_monitor(void *data)
22563 {
22564    int res;
22565    time_t t;
22566    int reloading;
22567 
22568    /* Add an I/O event to our SIP UDP socket */
22569    if (sipsock > -1) 
22570       sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
22571 
22572    /* From here on out, we die whenever asked */
22573    for(;;) {
22574       /* Check for a reload request */
22575       ast_mutex_lock(&sip_reload_lock);
22576       reloading = sip_reloading;
22577       sip_reloading = FALSE;
22578       ast_mutex_unlock(&sip_reload_lock);
22579       if (reloading) {
22580          ast_verb(1, "Reloading SIP\n");
22581          sip_do_reload(sip_reloadreason);
22582 
22583          /* Change the I/O fd of our UDP socket */
22584          if (sipsock > -1) {
22585             if (sipsock_read_id)
22586                sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
22587             else
22588                sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
22589          } else if (sipsock_read_id) {
22590             ast_io_remove(io, sipsock_read_id);
22591             sipsock_read_id = NULL;
22592          }
22593       }
22594 
22595       /* Check for dialogs needing to be killed */
22596       t = time(NULL);
22597       /* don't scan the dialogs list if it hasn't been a reasonable period
22598          of time since the last time we did it (when MWI is being sent, we can
22599          get back to this point every millisecond or less)
22600       */
22601       ao2_t_callback(dialogs, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, dialog_needdestroy, &t,
22602             "callback to remove dialogs w/needdestroy");
22603 
22604       /* the old methodology would be to restart the search for dialogs to delete with every 
22605          dialog that was found and destroyed, probably because the list contents would change,
22606          so we'd need to restart. This isn't the best thing to do with callbacks. */
22607 
22608       /* XXX TODO The scheduler usage in this module does not have sufficient 
22609        * synchronization being done between running the scheduler and places 
22610        * scheduling tasks.  As it is written, any scheduled item may not run 
22611        * any sooner than about  1 second, regardless of whether a sooner time 
22612        * was asked for. */
22613 
22614       pthread_testcancel();
22615       /* Wait for sched or io */
22616       res = ast_sched_wait(sched);
22617       if ((res < 0) || (res > 1000))
22618          res = 1000;
22619       res = ast_io_wait(io, res);
22620       if (res > 20)
22621          ast_debug(1, "chan_sip: ast_io_wait ran %d all at once\n", res);
22622       ast_mutex_lock(&monlock);
22623       res = ast_sched_runq(sched);
22624       if (res >= 20)
22625          ast_debug(1, "chan_sip: ast_sched_runq ran %d all at once\n", res);
22626       ast_mutex_unlock(&monlock);
22627    }
22628 
22629    /* Never reached */
22630    return NULL;
22631 }
22632 
22633 /*! \brief Start the channel monitor thread */
22634 static int restart_monitor(void)
22635 {
22636    /* If we're supposed to be stopped -- stay stopped */
22637    if (monitor_thread == AST_PTHREADT_STOP)
22638       return 0;
22639    ast_mutex_lock(&monlock);
22640    if (monitor_thread == pthread_self()) {
22641       ast_mutex_unlock(&monlock);
22642       ast_log(LOG_WARNING, "Cannot kill myself\n");
22643       return -1;
22644    }
22645    if (monitor_thread != AST_PTHREADT_NULL) {
22646       /* Wake up the thread */
22647       pthread_kill(monitor_thread, SIGURG);
22648    } else {
22649       /* Start a new monitor */
22650       if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
22651          ast_mutex_unlock(&monlock);
22652          ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
22653          return -1;
22654       }
22655    }
22656    ast_mutex_unlock(&monlock);
22657    return 0;
22658 }
22659 
22660 
22661 /*! \brief Session-Timers: Restart session timer */
22662 static void restart_session_timer(struct sip_pvt *p)
22663 {
22664    if (!p->stimer) {
22665       ast_log(LOG_WARNING, "Null stimer in restart_session_timer - %s\n", p->callid);
22666       return;
22667    }
22668 
22669    if (p->stimer->st_active == TRUE) {
22670       AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
22671             dialog_unref(p, "Removing session timer ref"));
22672       ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
22673       start_session_timer(p);
22674    }
22675 }
22676 
22677 
22678 /*! \brief Session-Timers: Stop session timer */
22679 static void stop_session_timer(struct sip_pvt *p)
22680 {
22681    if (!p->stimer) {
22682       ast_log(LOG_WARNING, "Null stimer in stop_session_timer - %s\n", p->callid);
22683       return;
22684    }
22685 
22686    if (p->stimer->st_active == TRUE) {
22687       p->stimer->st_active = FALSE;
22688       AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
22689             dialog_unref(p, "removing session timer ref"));
22690       ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
22691    }
22692 }
22693 
22694 
22695 /*! \brief Session-Timers: Start session timer */
22696 static void start_session_timer(struct sip_pvt *p)
22697 {
22698    if (!p->stimer) {
22699       ast_log(LOG_WARNING, "Null stimer in start_session_timer - %s\n", p->callid);
22700       return;
22701    }
22702 
22703    p->stimer->st_schedid  = ast_sched_add(sched, p->stimer->st_interval * 1000 / 2, proc_session_timer, 
22704          dialog_ref(p, "adding session timer ref"));
22705    if (p->stimer->st_schedid < 0) {
22706       dialog_unref(p, "removing session timer ref");
22707       ast_log(LOG_ERROR, "ast_sched_add failed.\n");
22708    }
22709    ast_debug(2, "Session timer started: %d - %s\n", p->stimer->st_schedid, p->callid);
22710 }
22711 
22712 
22713 /*! \brief Session-Timers: Process session refresh timeout event */
22714 static int proc_session_timer(const void *vp)
22715 {
22716    struct sip_pvt *p = (struct sip_pvt *) vp;
22717    int sendreinv = FALSE;
22718    int res = 0;
22719 
22720    if (!p->stimer) {
22721       ast_log(LOG_WARNING, "Null stimer in proc_session_timer - %s\n", p->callid);
22722       goto return_unref;
22723    }
22724 
22725    ast_debug(2, "Session timer expired: %d - %s\n", p->stimer->st_schedid, p->callid);
22726 
22727    if (!p->owner) {
22728       goto return_unref;
22729    }
22730 
22731    if ((p->stimer->st_active != TRUE) || (p->owner->_state != AST_STATE_UP)) {
22732       goto return_unref;
22733    }
22734 
22735    switch (p->stimer->st_ref) {
22736    case SESSION_TIMER_REFRESHER_UAC:
22737       if (p->outgoing_call == TRUE) {
22738          sendreinv = TRUE;
22739       }
22740       break;
22741    case SESSION_TIMER_REFRESHER_UAS:
22742       if (p->outgoing_call != TRUE) {
22743          sendreinv = TRUE;
22744       }
22745       break;
22746    default:
22747       ast_log(LOG_ERROR, "Unknown session refresher %d\n", p->stimer->st_ref);
22748       goto return_unref;
22749    }
22750 
22751    if (sendreinv == TRUE) {
22752       res = 1;
22753       transmit_reinvite_with_sdp(p, FALSE, TRUE);
22754    } else {
22755       p->stimer->st_expirys++;
22756       if (p->stimer->st_expirys >= 2) {
22757          if (p->stimer->quit_flag) {
22758             goto return_unref;
22759          }
22760          ast_log(LOG_WARNING, "Session-Timer expired - %s\n", p->callid);
22761          sip_pvt_lock(p);
22762          while (p->owner && ast_channel_trylock(p->owner)) {
22763             sip_pvt_unlock(p);
22764             usleep(1);
22765             if (p->stimer && p->stimer->quit_flag) {
22766                goto return_unref;
22767             }
22768             sip_pvt_lock(p);
22769          }
22770 
22771          ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
22772          ast_channel_unlock(p->owner);
22773          sip_pvt_unlock(p);
22774       }
22775    }
22776 
22777 return_unref:
22778    if (!res) {
22779       /* An error occurred.  Stop session timer processing */
22780       if (p->stimer) {
22781          p->stimer->st_schedid = -1;
22782          stop_session_timer(p);
22783       }
22784 
22785       /* If we are not asking to be rescheduled, then we need to release our
22786        * reference to the dialog. */
22787       dialog_unref(p, "removing session timer ref");
22788    }
22789 
22790    return res;
22791 }
22792 
22793 
22794 /*! \brief Session-Timers: Function for parsing Min-SE header */
22795 int parse_minse (const char *p_hdrval, int *const p_interval)
22796 {
22797    if (ast_strlen_zero(p_hdrval)) {
22798       ast_log(LOG_WARNING, "Null Min-SE header\n");
22799       return -1;
22800    }
22801 
22802    *p_interval = 0;
22803    p_hdrval = ast_skip_blanks(p_hdrval);
22804    if (!sscanf(p_hdrval, "%30d", p_interval)) {
22805       ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
22806       return -1;
22807    }
22808 
22809    ast_debug(2, "Received Min-SE: %d\n", *p_interval);
22810    return 0;
22811 }
22812 
22813 
22814 /*! \brief Session-Timers: Function for parsing Session-Expires header */
22815 int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref)
22816 {
22817    char *p_token;
22818    int  ref_idx;
22819    char *p_se_hdr;
22820 
22821    if (ast_strlen_zero(p_hdrval)) {
22822       ast_log(LOG_WARNING, "Null Session-Expires header\n");
22823       return -1;
22824    }
22825 
22826    *p_ref = SESSION_TIMER_REFRESHER_AUTO;
22827    *p_interval = 0;
22828 
22829    p_se_hdr = ast_strdupa(p_hdrval);
22830    p_se_hdr = ast_skip_blanks(p_se_hdr);
22831 
22832    while ((p_token = strsep(&p_se_hdr, ";"))) {
22833       p_token = ast_skip_blanks(p_token);
22834       if (!sscanf(p_token, "%30d", p_interval)) {
22835          ast_log(LOG_WARNING, "Parsing of Session-Expires failed\n");
22836          return -1;
22837       }
22838 
22839       ast_debug(2, "Session-Expires: %d\n", *p_interval);
22840 
22841       if (!p_se_hdr)
22842          continue;
22843 
22844       p_se_hdr = ast_skip_blanks(p_se_hdr);
22845       ref_idx = strlen("refresher=");
22846       if (!strncasecmp(p_se_hdr, "refresher=", ref_idx)) {
22847          p_se_hdr += ref_idx;
22848          p_se_hdr = ast_skip_blanks(p_se_hdr);
22849 
22850          if (!strncasecmp(p_se_hdr, "uac", strlen("uac"))) {
22851             *p_ref = SESSION_TIMER_REFRESHER_UAC;
22852             ast_debug(2, "Refresher: UAC\n");
22853          } else if (!strncasecmp(p_se_hdr, "uas", strlen("uas"))) {
22854             *p_ref = SESSION_TIMER_REFRESHER_UAS;
22855             ast_debug(2, "Refresher: UAS\n");
22856          } else {
22857             ast_log(LOG_WARNING, "Invalid refresher value %s\n", p_se_hdr);
22858             return -1;
22859          }
22860          break;
22861       }
22862    }
22863    return 0;
22864 }
22865 
22866 
22867 /*! \brief Handle 422 response to INVITE with session-timer requested
22868 
22869    Session-Timers:   An INVITE originated by Asterisk that asks for session-timers support
22870    from the UAS can result into a 422 response. This is how a UAS or an intermediary proxy 
22871    server tells Asterisk that the session refresh interval offered by Asterisk is too low 
22872    for them.  The proc_422_rsp() function handles a 422 response.  It extracts the Min-SE 
22873    header that comes back in 422 and sends a new INVITE accordingly. */
22874 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp)
22875 {
22876    int rtn;
22877    const char *p_hdrval;
22878    int minse;
22879 
22880    p_hdrval = get_header(rsp, "Min-SE");
22881    if (ast_strlen_zero(p_hdrval)) {
22882       ast_log(LOG_WARNING, "422 response without a Min-SE header %s\n", p_hdrval);
22883       return;
22884    }
22885    rtn = parse_minse(p_hdrval, &minse);
22886    if (rtn != 0) {
22887       ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
22888       return;
22889    }
22890    p->stimer->st_interval = minse;
22891    transmit_invite(p, SIP_INVITE, 1, 2); 
22892 }
22893 
22894 
22895 /*! \brief Get Max or Min SE (session timer expiry)
22896  * \param p pointer to the SIP dialog 
22897  * \param max if true, get max se, otherwise min se
22898 */
22899 int st_get_se(struct sip_pvt *p, int max)
22900 {
22901    if (max == TRUE) {
22902       if (p->stimer->st_cached_max_se) {
22903          return p->stimer->st_cached_max_se;
22904       } else if (p->peername) {
22905          struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
22906          if (pp) {
22907             p->stimer->st_cached_max_se = pp->stimer.st_max_se;
22908             unref_peer(pp, "unref peer pointer from find_peer call in st_get_se");
22909             return (p->stimer->st_cached_max_se);
22910          }
22911       }
22912       p->stimer->st_cached_max_se = global_max_se;
22913       return (p->stimer->st_cached_max_se);
22914    } else {
22915       if (p->stimer->st_cached_min_se) {
22916          return p->stimer->st_cached_min_se;
22917       } else if (p->peername) {
22918          struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
22919          if (pp) {
22920             p->stimer->st_cached_min_se = pp->stimer.st_min_se;
22921             unref_peer(pp, "unref peer pointer from find_peer call in st_get_se (2)");
22922             return (p->stimer->st_cached_min_se);
22923          }
22924       }
22925       p->stimer->st_cached_min_se = global_min_se;
22926       return (p->stimer->st_cached_min_se);
22927    }
22928 }
22929 
22930 
22931 /*! \brief Get the entity (UAC or UAS) that's acting as the session-timer refresher 
22932  * \param p pointer to the SIP dialog 
22933 */
22934 enum st_refresher st_get_refresher(struct sip_pvt *p)
22935 {
22936    if (p->stimer->st_cached_ref != SESSION_TIMER_REFRESHER_AUTO) 
22937       return p->stimer->st_cached_ref;
22938 
22939    if (p->peername) {
22940       struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
22941       if (pp) {
22942          p->stimer->st_cached_ref = pp->stimer.st_ref;
22943          unref_peer(pp, "unref peer pointer from find_peer call in st_get_refresher");
22944          return pp->stimer.st_ref;
22945       }
22946    }
22947    
22948    p->stimer->st_cached_ref = global_st_refresher;
22949    return global_st_refresher;
22950 }
22951 
22952 
22953 /*! \brief Get the session-timer mode 
22954  * \param p pointer to the SIP dialog 
22955 */
22956 enum st_mode st_get_mode(struct sip_pvt *p)
22957 {
22958    if (!p->stimer) 
22959       sip_st_alloc(p);
22960 
22961    if (p->stimer->st_cached_mode != SESSION_TIMER_MODE_INVALID) 
22962       return p->stimer->st_cached_mode;
22963 
22964    if (p->peername) {
22965       struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
22966       if (pp) {
22967          p->stimer->st_cached_mode = pp->stimer.st_mode_oper;
22968          unref_peer(pp, "unref peer pointer from find_peer call in st_get_mode");
22969          return pp->stimer.st_mode_oper;
22970       }
22971    }
22972 
22973    p->stimer->st_cached_mode = global_st_mode;
22974    return global_st_mode;
22975 }
22976 
22977 
22978 /*! \brief React to lack of answer to Qualify poke */
22979 static int sip_poke_noanswer(const void *data)
22980 {
22981    struct sip_peer *peer = (struct sip_peer *)data;
22982    
22983    peer->pokeexpire = -1;
22984 
22985    if (peer->lastms > -1) {
22986       ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE!  Last qualify: %d\n", peer->name, peer->lastms);
22987       if (sip_cfg.peer_rtupdate) {
22988          ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", "-1", SENTINEL);
22989       }
22990       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
22991       if (sip_cfg.regextenonqualify) {
22992          register_peer_exten(peer, FALSE);
22993       }
22994    }
22995 
22996    if (peer->call) {
22997       dialog_unlink_all(peer->call, TRUE, TRUE);
22998       peer->call = dialog_unref(peer->call, "unref dialog peer->call");
22999       /* peer->call = sip_destroy(peer->call);*/
23000    }
23001    
23002    peer->lastms = -1;
23003    ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
23004 
23005    /* Try again quickly */
23006    AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, 
23007          DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer,
23008          unref_peer(_data, "removing poke peer ref"),
23009          unref_peer(peer, "removing poke peer ref"),
23010          ref_peer(peer, "adding poke peer ref"));
23011 
23012    /* Release the ref held by the running scheduler entry */
23013    unref_peer(peer, "release peer poke noanswer ref");
23014 
23015    return 0;
23016 }
23017 
23018 /*! \brief Check availability of peer, also keep NAT open
23019 \note This is done with 60 seconds between each ping,
23020    unless forced by cli or manager. If peer is unreachable,
23021    we check every 10th second by default. 
23022 */
23023 static int sip_poke_peer(struct sip_peer *peer, int force)
23024 {
23025    struct sip_pvt *p;
23026    int xmitres = 0;
23027    
23028    if ((!peer->maxms && !force) || !peer->addr.sin_addr.s_addr) {
23029       /* IF we have no IP, or this isn't to be monitored, return
23030         immediately after clearing things out */
23031       AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
23032             unref_peer(peer, "removing poke peer ref"));
23033       
23034       peer->lastms = 0;
23035       if (peer->call) {
23036          peer->call = dialog_unref(peer->call, "unref dialog peer->call");
23037       }
23038       return 0;
23039    }
23040    if (peer->call) {
23041       if (sipdebug) {
23042          ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
23043       }
23044       dialog_unlink_all(peer->call, TRUE, TRUE);
23045       peer->call = dialog_unref(peer->call, "unref dialog peer->call");
23046       /* peer->call = sip_destroy(peer->call); */
23047    }
23048    if (!(p = sip_alloc(NULL, NULL, 0, SIP_OPTIONS, NULL))) {
23049       return -1;
23050    }
23051    peer->call = dialog_ref(p, "copy sip alloc from p to peer->call");
23052    
23053    p->sa = peer->addr;
23054    p->recv = peer->addr;
23055    copy_socket_data(&p->socket, &peer->socket);
23056    ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
23057    ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
23058 
23059    /* Send OPTIONs to peer's fullcontact */
23060    if (!ast_strlen_zero(peer->fullcontact))
23061       ast_string_field_set(p, fullcontact, peer->fullcontact);
23062 
23063    if (!ast_strlen_zero(peer->tohost))
23064       ast_string_field_set(p, tohost, peer->tohost);
23065    else
23066       ast_string_field_set(p, tohost, ast_inet_ntoa(peer->addr.sin_addr));
23067 
23068    /* Recalculate our side, and recalculate Call ID */
23069    ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
23070    build_via(p);
23071    ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
23072    build_callid_pvt(p);
23073    ao2_t_link(dialogs, p, "Linking in under new name");
23074 
23075    AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
23076          unref_peer(peer, "removing poke peer ref"));
23077    
23078    if (p->relatedpeer)
23079       p->relatedpeer = unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
23080    p->relatedpeer = ref_peer(peer, "setting the relatedpeer field in the dialog");
23081    ast_set_flag(&p->flags[0], SIP_OUTGOING);
23082 #ifdef VOCAL_DATA_HACK
23083    ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
23084    xmitres = transmit_invite(p, SIP_INVITE, 0, 2); /* sinks the p refcount */
23085 #else
23086    xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2); /* sinks the p refcount */
23087 #endif
23088    peer->ps = ast_tvnow();
23089    if (xmitres == XMIT_ERROR) {
23090       sip_poke_noanswer(peer);   /* Immediately unreachable, network problems */
23091    } else if (!force) {
23092       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, peer->maxms * 2, sip_poke_noanswer, peer,
23093             unref_peer(_data, "removing poke peer ref"),
23094             unref_peer(peer, "removing poke peer ref"),
23095             ref_peer(peer, "adding poke peer ref"));
23096    }
23097    dialog_unref(p, "unref dialog at end of sip_poke_peer, obtained from sip_alloc, just before it goes out of scope");
23098    return 0;
23099 }
23100 
23101 /*! \brief Part of PBX channel interface
23102 \note
23103 \par  Return values:---
23104 
23105    If we have qualify on and the device is not reachable, regardless of registration
23106    state we return AST_DEVICE_UNAVAILABLE
23107 
23108    For peers with call limit:
23109       - not registered        AST_DEVICE_UNAVAILABLE
23110       - registered, no call         AST_DEVICE_NOT_INUSE
23111       - registered, active calls    AST_DEVICE_INUSE
23112       - registered, call limit reached AST_DEVICE_BUSY
23113       - registered, onhold       AST_DEVICE_ONHOLD
23114       - registered, ringing         AST_DEVICE_RINGING
23115 
23116    For peers without call limit:
23117       - not registered        AST_DEVICE_UNAVAILABLE
23118       - registered            AST_DEVICE_NOT_INUSE
23119       - fixed IP (!dynamic)         AST_DEVICE_NOT_INUSE
23120    
23121    Peers that does not have a known call and can't be reached by OPTIONS
23122       - unreachable           AST_DEVICE_UNAVAILABLE
23123 
23124    If we return AST_DEVICE_UNKNOWN, the device state engine will try to find
23125    out a state by walking the channel list.
23126 
23127    The queue system (\ref app_queue.c) treats a member as "active"
23128    if devicestate is != AST_DEVICE_UNAVAILBALE && != AST_DEVICE_INVALID
23129 
23130    When placing a call to the queue member, queue system sets a member to busy if
23131    != AST_DEVICE_NOT_INUSE and != AST_DEVICE_UNKNOWN
23132 
23133 */
23134 static int sip_devicestate(void *data)
23135 {
23136    char *host;
23137    char *tmp;
23138    struct sip_peer *p;
23139 
23140    int res = AST_DEVICE_INVALID;
23141 
23142    /* make sure data is not null. Maybe unnecessary, but better be safe */
23143    host = ast_strdupa(data ? data : "");
23144    if ((tmp = strchr(host, '@')))
23145       host = tmp + 1;
23146 
23147    ast_debug(3, "Checking device state for peer %s\n", host);
23148 
23149    /* If find_peer asks for a realtime peer, then this breaks rtautoclear.  This
23150     * is because when a peer tries to autoexpire, the last thing it does is to
23151     * queue up an event telling the system that the devicestate has changed
23152     * (presumably to unavailable).  If we ask for a realtime peer here, this would
23153     * load it BACK into memory, thus defeating the point of trying to clear dead
23154     * hosts out of memory.
23155     */
23156    if ((p = find_peer(host, NULL, FALSE, FINDALLDEVICES, TRUE, 0))) {
23157       if (p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) {
23158          /* we have an address for the peer */
23159       
23160          /* Check status in this order
23161             - Hold
23162             - Ringing
23163             - Busy (enforced only by call limit)
23164             - Inuse (we have a call)
23165             - Unreachable (qualify)
23166             If we don't find any of these state, report AST_DEVICE_NOT_INUSE
23167             for registered devices */
23168 
23169          if (p->onHold)
23170             /* First check for hold or ring states */
23171             res = AST_DEVICE_ONHOLD;
23172          else if (p->inRinging) {
23173             if (p->inRinging == p->inUse)
23174                res = AST_DEVICE_RINGING;
23175             else
23176                res = AST_DEVICE_RINGINUSE;
23177          } else if (p->call_limit && (p->inUse == p->call_limit))
23178             /* check call limit */
23179             res = AST_DEVICE_BUSY;
23180          else if (p->call_limit && p->busy_level && p->inUse >= p->busy_level)
23181             /* We're forcing busy before we've reached the call limit */
23182             res = AST_DEVICE_BUSY;
23183          else if (p->call_limit && p->inUse)
23184             /* Not busy, but we do have a call */
23185             res = AST_DEVICE_INUSE;
23186          else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0))) 
23187             /* We don't have a call. Are we reachable at all? Requires qualify= */
23188             res = AST_DEVICE_UNAVAILABLE;
23189          else  /* Default reply if we're registered and have no other data */
23190             res = AST_DEVICE_NOT_INUSE;
23191       } else {
23192          /* there is no address, it's unavailable */
23193          res = AST_DEVICE_UNAVAILABLE;
23194       }
23195       unref_peer(p, "unref_peer, from sip_devicestate, release ref from find_peer");
23196    } else {
23197       res = AST_DEVICE_UNKNOWN;
23198    }
23199 
23200    return res;
23201 }
23202 
23203 /*! \brief PBX interface function -build SIP pvt structure 
23204  * SIP calls initiated by the PBX arrive here. 
23205  *
23206  * \verbatim   
23207  *    SIP Dial string syntax
23208  *    SIP/exten@host!dnid
23209  * or SIP/host/exten!dnid
23210  * or SIP/host!dnid
23211  * \endverbatim
23212 */
23213 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause)
23214 {
23215    struct sip_pvt *p;
23216    struct ast_channel *tmpc = NULL;
23217    char *ext = NULL, *host;
23218    char tmp[256];
23219    char *dest = data;
23220    char *dnid;
23221    char *secret = NULL;
23222    char *md5secret = NULL;
23223    char *authname = NULL;
23224    char *trans = NULL;
23225    enum sip_transport transport = 0;
23226    int oldformat = format;
23227 
23228    /* mask request with some set of allowed formats.
23229     * XXX this needs to be fixed.
23230     * The original code uses AST_FORMAT_AUDIO_MASK, but it is
23231     * unclear what to use here. We have global_capabilities, which is
23232     * configured from sip.conf, and sip_tech.capabilities, which is
23233     * hardwired to all audio formats.
23234     */
23235    format &= AST_FORMAT_AUDIO_MASK;
23236    if (!format) {
23237       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));
23238       *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;   /* Can't find codec to connect to host */
23239       return NULL;
23240    }
23241    ast_debug(1, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));
23242 
23243    if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE, NULL))) {
23244       ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", dest);
23245       *cause = AST_CAUSE_SWITCH_CONGESTION;
23246       return NULL;
23247    }
23248 
23249    p->outgoing_call = TRUE;
23250 
23251    if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
23252       dialog_unlink_all(p, TRUE, TRUE);
23253       dialog_unref(p, "unref dialog p from mem fail");
23254       /* sip_destroy(p); */
23255       ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
23256       *cause = AST_CAUSE_SWITCH_CONGESTION;
23257       return NULL;
23258    }
23259 
23260    /* Save the destination, the SIP dial string */
23261    ast_copy_string(tmp, dest, sizeof(tmp));
23262 
23263 
23264    /* Find DNID and take it away */
23265    dnid = strchr(tmp, '!');
23266    if (dnid != NULL) {
23267       *dnid++ = '\0';
23268       ast_string_field_set(p, todnid, dnid);
23269    }
23270 
23271    /* Find at sign - @ */
23272    host = strchr(tmp, '@');
23273    if (host) {
23274       *host++ = '\0';
23275       ext = tmp;
23276       secret = strchr(ext, ':');
23277    }
23278    if (secret) {
23279       *secret++ = '\0';
23280       md5secret = strchr(secret, ':');
23281    }
23282    if (md5secret) {
23283       *md5secret++ = '\0';
23284       authname = strchr(md5secret, ':');
23285    }
23286    if (authname) {
23287       *authname++ = '\0';
23288       trans = strchr(authname, ':');
23289    }
23290    if (trans) {
23291       *trans++ = '\0';
23292       if (!strcasecmp(trans, "tcp"))
23293          transport = SIP_TRANSPORT_TCP;
23294       else if (!strcasecmp(trans, "tls"))
23295          transport = SIP_TRANSPORT_TLS;
23296       else {
23297          if (strcasecmp(trans, "udp"))
23298             ast_log(LOG_WARNING, "'%s' is not a valid transport option to Dial() for SIP calls, using udp by default.\n", trans);
23299          transport = SIP_TRANSPORT_UDP;
23300       }
23301    } else { /* use default */
23302       transport = SIP_TRANSPORT_UDP;
23303    }
23304 
23305    if (!host) {
23306       ext = strchr(tmp, '/');
23307       if (ext) 
23308          *ext++ = '\0';
23309       host = tmp;
23310    }
23311 
23312    set_socket_transport(&p->socket, transport);
23313 
23314    /* We now have 
23315       host = peer name, DNS host name or DNS domain (for SRV) 
23316       ext = extension (user part of URI)
23317       dnid = destination of the call (applies to the To: header)
23318    */
23319    if (create_addr(p, host, NULL, 1)) {
23320       *cause = AST_CAUSE_UNREGISTERED;
23321       ast_debug(3, "Cant create SIP call - target device not registered\n");
23322       dialog_unlink_all(p, TRUE, TRUE);
23323       dialog_unref(p, "unref dialog p UNREGISTERED");
23324       /* sip_destroy(p); */
23325       return NULL;
23326    }
23327    if (ast_strlen_zero(p->peername) && ext)
23328       ast_string_field_set(p, peername, ext);
23329    /* Recalculate our side, and recalculate Call ID */
23330    ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
23331    build_via(p);
23332    ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
23333    build_callid_pvt(p);
23334    ao2_t_link(dialogs, p, "Linking in under new name");
23335    
23336    /* We have an extension to call, don't use the full contact here */
23337    /* This to enable dialing registered peers with extension dialling,
23338       like SIP/peername/extension   
23339       SIP/peername will still use the full contact 
23340     */
23341    if (ext) {
23342       ast_string_field_set(p, username, ext);
23343       ast_string_field_set(p, fullcontact, NULL);
23344    }
23345    if (secret && !ast_strlen_zero(secret))
23346       ast_string_field_set(p, peersecret, secret);
23347 
23348    if (md5secret && !ast_strlen_zero(md5secret))
23349       ast_string_field_set(p, peermd5secret, md5secret);
23350 
23351    if (authname && !ast_strlen_zero(authname))
23352       ast_string_field_set(p, authname, authname);
23353 #if 0
23354    printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
23355 #endif
23356    p->prefcodec = oldformat;           /* Format for this call */
23357    p->jointcapability = oldformat & p->capability;
23358    sip_pvt_lock(p);
23359    tmpc = sip_new(p, AST_STATE_DOWN, host);  /* Place the call */
23360    if (sip_cfg.callevents)
23361       manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
23362          "Channel: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
23363          p->owner? p->owner->name : "", "SIP", p->callid, p->fullcontact, p->peername);
23364    sip_pvt_unlock(p);
23365    if (!tmpc) {
23366       dialog_unlink_all(p, TRUE, TRUE);
23367       /* sip_destroy(p); */
23368    }
23369    dialog_unref(p, "toss pvt ptr at end of sip_request_call");
23370    ast_update_use_count();
23371    restart_monitor();
23372    return tmpc;
23373 }
23374 
23375 /*! \brief Parse insecure= setting in sip.conf and set flags according to setting */
23376 static void set_insecure_flags (struct ast_flags *flags, const char *value, int lineno)
23377 {
23378    if (ast_strlen_zero(value))
23379       return;
23380 
23381    if (!ast_false(value)) {
23382       char buf[64];
23383       char *word, *next;
23384 
23385       ast_copy_string(buf, value, sizeof(buf));
23386       next = buf;
23387       while ((word = strsep(&next, ","))) {
23388          if (!strcasecmp(word, "port"))
23389             ast_set_flag(&flags[0], SIP_INSECURE_PORT);
23390          else if (!strcasecmp(word, "invite"))
23391             ast_set_flag(&flags[0], SIP_INSECURE_INVITE);
23392          else
23393             ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
23394       }
23395    }
23396 }
23397 
23398 /*!
23399   \brief Handle T.38 configuration options common to users and peers
23400   \returns non-zero if any config options were handled, zero otherwise
23401 */
23402 static int handle_t38_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v,
23403                int *maxdatagram)
23404 {
23405    int res = 1;
23406 
23407    if (!strcasecmp(v->name, "t38pt_udptl")) {
23408       char *buf = ast_strdupa(v->value);
23409       char *word, *next = buf;
23410 
23411       ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT);
23412 
23413       while ((word = strsep(&next, ","))) {
23414          if (ast_true(word) || !strcasecmp(word, "fec")) {
23415             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
23416             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_FEC);
23417          } else if (!strcasecmp(word, "redundancy")) {
23418             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
23419             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY);
23420          } else if (!strcasecmp(word, "none")) {
23421             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
23422             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
23423          } else if (!strncasecmp(word, "maxdatagram=", 12)) {
23424             if (sscanf(&word[12], "%30u", maxdatagram) != 1) {
23425                ast_log(LOG_WARNING, "Invalid maxdatagram '%s' at line %d of %s\n", v->value, v->lineno, config);
23426                *maxdatagram = global_t38_maxdatagram;
23427             }
23428          }
23429       }
23430    } else if (!strcasecmp(v->name, "t38pt_usertpsource")) {
23431       ast_set_flag(&mask[1], SIP_PAGE2_UDPTL_DESTINATION);
23432       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_UDPTL_DESTINATION);
23433    } else if (!strcasecmp(v->name, "forwardloopdetected")) {
23434       ast_set_flag(&mask[1], SIP_PAGE2_FORWARD_LOOP_DETECTED);
23435       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_FORWARD_LOOP_DETECTED);
23436    } else {
23437       res = 0;
23438    }
23439 
23440    return res;
23441 }
23442 
23443 /*!
23444   \brief Handle flag-type options common to configuration of devices - peers
23445   \param flags array of two struct ast_flags
23446   \param mask array of two struct ast_flags
23447   \param v linked list of config variables to process
23448   \returns non-zero if any config options were handled, zero otherwise
23449 */
23450 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
23451 {
23452    int res = 1;
23453 
23454    if (!strcasecmp(v->name, "trustrpid")) {
23455       ast_set_flag(&mask[0], SIP_TRUSTRPID);
23456       ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
23457    } else if (!strcasecmp(v->name, "sendrpid")) {
23458       ast_set_flag(&mask[0], SIP_SENDRPID);
23459       ast_set2_flag(&flags[0], ast_true(v->value), SIP_SENDRPID);
23460    } else if (!strcasecmp(v->name, "g726nonstandard")) {
23461       ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
23462       ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
23463    } else if (!strcasecmp(v->name, "useclientcode")) {
23464       ast_set_flag(&mask[0], SIP_USECLIENTCODE);
23465       ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
23466    } else if (!strcasecmp(v->name, "dtmfmode")) {
23467       ast_set_flag(&mask[0], SIP_DTMF);
23468       ast_clear_flag(&flags[0], SIP_DTMF);
23469       if (!strcasecmp(v->value, "inband"))
23470          ast_set_flag(&flags[0], SIP_DTMF_INBAND);
23471       else if (!strcasecmp(v->value, "rfc2833"))
23472          ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
23473       else if (!strcasecmp(v->value, "info"))
23474          ast_set_flag(&flags[0], SIP_DTMF_INFO);
23475       else if (!strcasecmp(v->value, "shortinfo"))
23476          ast_set_flag(&flags[0], SIP_DTMF_SHORTINFO);
23477       else if (!strcasecmp(v->value, "auto"))
23478          ast_set_flag(&flags[0], SIP_DTMF_AUTO);
23479       else {
23480          ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
23481          ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
23482       }
23483    } else if (!strcasecmp(v->name, "nat")) {
23484       ast_set_flag(&mask[0], SIP_NAT);
23485       ast_clear_flag(&flags[0], SIP_NAT);
23486       if (!strcasecmp(v->value, "never"))
23487          ast_set_flag(&flags[0], SIP_NAT_NEVER);
23488       else if (!strcasecmp(v->value, "route"))
23489          ast_set_flag(&flags[0], SIP_NAT_ROUTE);
23490       else if (ast_true(v->value))
23491          ast_set_flag(&flags[0], SIP_NAT_ALWAYS);
23492       else
23493          ast_set_flag(&flags[0], SIP_NAT_RFC3581);
23494    } else if (!strcasecmp(v->name, "directmedia") || !strcasecmp(v->name, "canreinvite")) {
23495       ast_set_flag(&mask[0], SIP_REINVITE);
23496       ast_clear_flag(&flags[0], SIP_REINVITE);
23497       if (ast_true(v->value)) {
23498          ast_set_flag(&flags[0], SIP_DIRECT_MEDIA | SIP_DIRECT_MEDIA_NAT);
23499       } else if (!ast_false(v->value)) {
23500          char buf[64];
23501          char *word, *next = buf;
23502 
23503          ast_copy_string(buf, v->value, sizeof(buf));
23504          while ((word = strsep(&next, ","))) {
23505             if (!strcasecmp(word, "update")) {
23506                ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_DIRECT_MEDIA);
23507             } else if (!strcasecmp(word, "nonat")) {
23508                ast_set_flag(&flags[0], SIP_DIRECT_MEDIA);
23509                ast_clear_flag(&flags[0], SIP_DIRECT_MEDIA_NAT);
23510             } else {
23511                ast_log(LOG_WARNING, "Unknown directmedia mode '%s' on line %d\n", v->value, v->lineno);
23512             }
23513          }
23514       }
23515    } else if (!strcasecmp(v->name, "insecure")) {
23516       ast_set_flag(&mask[0], SIP_INSECURE);
23517       ast_clear_flag(&flags[0], SIP_INSECURE);
23518       set_insecure_flags(&flags[0], v->value, v->lineno);   
23519    } else if (!strcasecmp(v->name, "progressinband")) {
23520       ast_set_flag(&mask[0], SIP_PROG_INBAND);
23521       ast_clear_flag(&flags[0], SIP_PROG_INBAND);
23522       if (ast_true(v->value))
23523          ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
23524       else if (strcasecmp(v->value, "never"))
23525          ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
23526    } else if (!strcasecmp(v->name, "promiscredir")) {
23527       ast_set_flag(&mask[0], SIP_PROMISCREDIR);
23528       ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
23529    } else if (!strcasecmp(v->name, "videosupport")) {
23530       if (!strcasecmp(v->value, "always")) {
23531          ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
23532          ast_set_flag(&flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
23533       } else {
23534          ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
23535          ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
23536       }
23537    } else if (!strcasecmp(v->name, "textsupport")) {
23538       ast_set_flag(&mask[1], SIP_PAGE2_TEXTSUPPORT);
23539       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_TEXTSUPPORT);
23540       res = 1;
23541    } else if (!strcasecmp(v->name, "allowoverlap")) {
23542       ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
23543       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWOVERLAP);
23544    } else if (!strcasecmp(v->name, "allowsubscribe")) {
23545       ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
23546       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
23547    } else if (!strcasecmp(v->name, "ignoresdpversion")) {
23548       ast_set_flag(&mask[1], SIP_PAGE2_IGNORESDPVERSION);
23549       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_IGNORESDPVERSION);
23550    } else if (!strcasecmp(v->name, "faxdetect")) {
23551       ast_set_flag(&mask[1], SIP_PAGE2_FAX_DETECT);
23552       if (ast_true(v->value)) {
23553          ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
23554       } else if (ast_false(v->value)) {
23555          ast_clear_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
23556       } else {
23557          char *buf = ast_strdupa(v->value);
23558          char *word, *next = buf;
23559 
23560          while ((word = strsep(&next, ","))) {
23561             if (!strcasecmp(word, "cng")) {
23562                ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_CNG);
23563             } else if (!strcasecmp(word, "t38")) {
23564                ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_T38);
23565             } else {
23566                ast_log(LOG_WARNING, "Unknown faxdetect mode '%s' on line %d.\n", word, v->lineno);
23567             }
23568          }
23569       }
23570    } else if (!strcasecmp(v->name, "rfc2833compensate")) {
23571       ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
23572       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
23573    } else if (!strcasecmp(v->name, "buggymwi")) {
23574       ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
23575       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
23576    } else
23577       res = 0;
23578 
23579    return res;
23580 }
23581 
23582 /*! \brief Add SIP domain to list of domains we are responsible for */
23583 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
23584 {
23585    struct domain *d;
23586 
23587    if (ast_strlen_zero(domain)) {
23588       ast_log(LOG_WARNING, "Zero length domain.\n");
23589       return 1;
23590    }
23591 
23592    if (!(d = ast_calloc(1, sizeof(*d))))
23593       return 0;
23594 
23595    ast_copy_string(d->domain, domain, sizeof(d->domain));
23596 
23597    if (!ast_strlen_zero(context))
23598       ast_copy_string(d->context, context, sizeof(d->context));
23599 
23600    d->mode = mode;
23601 
23602    AST_LIST_LOCK(&domain_list);
23603    AST_LIST_INSERT_TAIL(&domain_list, d, list);
23604    AST_LIST_UNLOCK(&domain_list);
23605 
23606    if (sipdebug)  
23607       ast_debug(1, "Added local SIP domain '%s'\n", domain);
23608 
23609    return 1;
23610 }
23611 
23612 /*! \brief  check_sip_domain: Check if domain part of uri is local to our server */
23613 static int check_sip_domain(const char *domain, char *context, size_t len)
23614 {
23615    struct domain *d;
23616    int result = 0;
23617 
23618    AST_LIST_LOCK(&domain_list);
23619    AST_LIST_TRAVERSE(&domain_list, d, list) {
23620       if (strcasecmp(d->domain, domain))
23621          continue;
23622 
23623       if (len && !ast_strlen_zero(d->context))
23624          ast_copy_string(context, d->context, len);
23625       
23626       result = 1;
23627       break;
23628    }
23629    AST_LIST_UNLOCK(&domain_list);
23630 
23631    return result;
23632 }
23633 
23634 /*! \brief Clear our domain list (at reload) */
23635 static void clear_sip_domains(void)
23636 {
23637    struct domain *d;
23638 
23639    AST_LIST_LOCK(&domain_list);
23640    while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
23641       ast_free(d);
23642    AST_LIST_UNLOCK(&domain_list);
23643 }
23644 
23645 
23646 /*! \brief Add realm authentication in list */
23647 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno)
23648 {
23649    char authcopy[256];
23650    char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
23651    struct sip_auth *a, *b, *auth;
23652 
23653    if (ast_strlen_zero(configuration))
23654       return authlist;
23655 
23656    ast_debug(1, "Auth config ::  %s\n", configuration);
23657 
23658    ast_copy_string(authcopy, configuration, sizeof(authcopy));
23659    username = authcopy;
23660 
23661    /* split user[:secret] and relm */
23662    realm = strrchr(username, '@');
23663    if (realm)
23664       *realm++ = '\0';
23665    if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
23666       ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
23667       return authlist;
23668    }
23669 
23670    /* parse username at ':' for secret, or '#" for md5secret */
23671    if ((secret = strchr(username, ':'))) {
23672       *secret++ = '\0';
23673    } else if ((md5secret = strchr(username, '#'))) {
23674       *md5secret++ = '\0';
23675    }
23676 
23677    if (!(auth = ast_calloc(1, sizeof(*auth))))
23678       return authlist;
23679 
23680    ast_copy_string(auth->realm, realm, sizeof(auth->realm));
23681    ast_copy_string(auth->username, username, sizeof(auth->username));
23682    if (secret)
23683       ast_copy_string(auth->secret, secret, sizeof(auth->secret));
23684    if (md5secret)
23685       ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
23686 
23687    /* find the end of the list */
23688    for (b = NULL, a = authlist; a ; b = a, a = a->next)
23689       ;
23690    if (b)
23691       b->next = auth;   /* Add structure add end of list */
23692    else
23693       authlist = auth;
23694 
23695    ast_verb(3, "Added authentication for realm %s\n", realm);
23696 
23697    return authlist;
23698 
23699 }
23700 
23701 /*! \brief Clear realm authentication list (at reload) */
23702 static int clear_realm_authentication(struct sip_auth *authlist)
23703 {
23704    struct sip_auth *a = authlist;
23705    struct sip_auth *b;
23706 
23707    while (a) {
23708       b = a;
23709       a = a->next;
23710       ast_free(b);
23711    }
23712 
23713    return 1;
23714 }
23715 
23716 /*! \brief Find authentication for a specific realm */
23717 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm)
23718 {
23719    struct sip_auth *a;
23720 
23721    for (a = authlist; a; a = a->next) {
23722       if (!strcasecmp(a->realm, realm))
23723          break;
23724    }
23725 
23726    return a;
23727 }
23728 
23729 /*! \brief
23730  * implement the setvar config line
23731  */
23732 static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
23733 {
23734    struct ast_variable *tmpvar = NULL;
23735    char *varname = ast_strdupa(buf), *varval = NULL;
23736    
23737    if ((varval = strchr(varname, '='))) {
23738       *varval++ = '\0';
23739       if ((tmpvar = ast_variable_new(varname, varval, ""))) {
23740          tmpvar->next = list;
23741          list = tmpvar;
23742       }
23743    }
23744    return list;
23745 }
23746 
23747 /*! \brief Set peer defaults before configuring specific configurations */
23748 static void set_peer_defaults(struct sip_peer *peer)
23749 {
23750    if (peer->expire == 0) {
23751       /* Don't reset expire or port time during reload 
23752          if we have an active registration 
23753       */
23754       peer->expire = -1;
23755       peer->pokeexpire = -1;
23756       peer->addr.sin_port = htons(STANDARD_SIP_PORT);
23757       set_socket_transport(&peer->socket, SIP_TRANSPORT_UDP);
23758    }
23759    peer->type = SIP_TYPE_PEER;
23760    ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
23761    ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
23762    ast_string_field_set(peer, context, sip_cfg.default_context);
23763    ast_string_field_set(peer, subscribecontext, sip_cfg.default_subscribecontext);
23764    ast_string_field_set(peer, language, default_language);
23765    ast_string_field_set(peer, mohinterpret, default_mohinterpret);
23766    ast_string_field_set(peer, mohsuggest, default_mohsuggest);
23767    peer->addr.sin_family = AF_INET;
23768    peer->defaddr.sin_family = AF_INET;
23769    peer->capability = global_capability;
23770    peer->maxcallbitrate = default_maxcallbitrate;
23771    peer->rtptimeout = global_rtptimeout;
23772    peer->rtpholdtimeout = global_rtpholdtimeout;
23773    peer->rtpkeepalive = global_rtpkeepalive;
23774    peer->allowtransfer = sip_cfg.allowtransfer;
23775    peer->autoframing = global_autoframing;
23776    peer->t38_maxdatagram = global_t38_maxdatagram;
23777    peer->qualifyfreq = global_qualifyfreq;
23778    if (global_callcounter)
23779       peer->call_limit=INT_MAX;
23780    ast_string_field_set(peer, vmexten, default_vmexten);
23781    ast_string_field_set(peer, secret, "");
23782    ast_string_field_set(peer, remotesecret, "");
23783    ast_string_field_set(peer, md5secret, "");
23784    ast_string_field_set(peer, cid_num, "");
23785    ast_string_field_set(peer, cid_name, "");
23786    ast_string_field_set(peer, fromdomain, "");
23787    ast_string_field_set(peer, fromuser, "");
23788    ast_string_field_set(peer, regexten, "");
23789    peer->callgroup = 0;
23790    peer->pickupgroup = 0;
23791    peer->maxms = default_qualify;
23792    peer->prefs = default_prefs;
23793    peer->stimer.st_mode_oper = global_st_mode;  /* Session-Timers */
23794    peer->stimer.st_ref = global_st_refresher;
23795    peer->stimer.st_min_se = global_min_se;
23796    peer->stimer.st_max_se = global_max_se;
23797    peer->timer_t1 = global_t1;
23798    peer->timer_b = global_timer_b;
23799    clear_peer_mailboxes(peer);
23800    peer->transports = default_transports;
23801    peer->default_outbound_transport = default_primary_transport;
23802 }
23803 
23804 /*! \brief Create temporary peer (used in autocreatepeer mode) */
23805 static struct sip_peer *temp_peer(const char *name)
23806 {
23807    struct sip_peer *peer;
23808 
23809    if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
23810       return NULL;
23811 
23812    if (ast_string_field_init(peer, 512)) {
23813       ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
23814       return NULL;
23815    }
23816 
23817    ast_atomic_fetchadd_int(&apeerobjs, 1);
23818    set_peer_defaults(peer);
23819 
23820    ast_copy_string(peer->name, name, sizeof(peer->name));
23821 
23822    peer->selfdestruct = TRUE;
23823    peer->host_dynamic = TRUE;
23824    peer->prefs = default_prefs;
23825    reg_source_db(peer);
23826 
23827    return peer;
23828 }
23829 
23830 /*! \todo document this function */
23831 static void add_peer_mailboxes(struct sip_peer *peer, const char *value)
23832 {
23833    char *next, *mbox, *context;
23834 
23835    next = ast_strdupa(value);
23836 
23837    while ((mbox = context = strsep(&next, ","))) {
23838       struct sip_mailbox *mailbox;
23839       int duplicate = 0;
23840 
23841       strsep(&context, "@");
23842 
23843       if (ast_strlen_zero(mbox)) {
23844          continue;
23845       }
23846 
23847       /* Check whether the mailbox is already in the list */
23848       AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
23849          if (!strcmp(mailbox->mailbox, mbox) && !strcmp(S_OR(mailbox->context, ""), S_OR(context, ""))) {
23850             duplicate = 1;
23851             mailbox->delme = 1;
23852             break;
23853          }
23854       }
23855       if (duplicate) {
23856          continue;
23857       }
23858 
23859       if (!(mailbox = ast_calloc(1, sizeof(*mailbox)))) {
23860          continue;
23861       }
23862 
23863       mailbox->mailbox = ast_strdup(mbox);
23864       mailbox->context = ast_strdup(context);
23865 
23866       AST_LIST_INSERT_TAIL(&peer->mailboxes, mailbox, entry);
23867    }
23868 }
23869 
23870 /*! \brief Build peer from configuration (file or realtime static/dynamic) */
23871 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only)
23872 {
23873    struct sip_peer *peer = NULL;
23874    struct ast_ha *oldha = NULL;
23875    int found = 0;
23876    int firstpass = 1;
23877    uint16_t port = 0;
23878    int format = 0;      /* Ama flags */
23879    time_t regseconds = 0;
23880    struct ast_flags peerflags[2] = {{(0)}};
23881    struct ast_flags mask[2] = {{(0)}};
23882    char callback[256] = "";
23883    struct sip_peer tmp_peer;
23884    const char *srvlookup = NULL;
23885    static int deprecation_warning = 1;
23886    int alt_fullcontact = alt ? 1 : 0;
23887    struct ast_str *fullcontact = ast_str_alloca(512);
23888 
23889    if (!realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
23890       /* Note we do NOT use find_peer here, to avoid realtime recursion */
23891       /* We also use a case-sensitive comparison (unlike find_peer) so
23892          that case changes made to the peer name will be properly handled
23893          during reload
23894       */
23895       ast_copy_string(tmp_peer.name, name, sizeof(tmp_peer.name));
23896       peer = ao2_t_find(peers, &tmp_peer, OBJ_POINTER | OBJ_UNLINK, "find and unlink peer from peers table");
23897    }
23898 
23899    if (peer) {
23900       /* Already in the list, remove it and it will be added back (or FREE'd)  */
23901       found++;
23902       if (!(peer->the_mark))
23903          firstpass = 0;
23904    } else {
23905       if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
23906          return NULL;
23907 
23908       if (ast_string_field_init(peer, 512)) {
23909          ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
23910          return NULL;
23911       }
23912 
23913       if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
23914          ast_atomic_fetchadd_int(&rpeerobjs, 1);
23915          ast_debug(3, "-REALTIME- peer built. Name: %s. Peer objects: %d\n", name, rpeerobjs);
23916       } else
23917          ast_atomic_fetchadd_int(&speerobjs, 1);
23918    }
23919 
23920    /* Note that our peer HAS had its reference count increased */
23921    if (firstpass) {
23922       peer->lastmsgssent = -1;
23923       oldha = peer->ha;
23924       peer->ha = NULL;
23925       set_peer_defaults(peer);   /* Set peer defaults */
23926       peer->type = 0;
23927    }
23928    if (!found && name)
23929       ast_copy_string(peer->name, name, sizeof(peer->name));
23930 
23931    /* If we have channel variables, remove them (reload) */
23932    if (peer->chanvars) {
23933       ast_variables_destroy(peer->chanvars);
23934       peer->chanvars = NULL;
23935       /* XXX should unregister ? */
23936    }
23937 
23938    if (found)
23939       peer->portinuri = 0;
23940 
23941    /* If we have realm authentication information, remove them (reload) */
23942    clear_realm_authentication(peer->auth);
23943    peer->auth = NULL;
23944    /* clear the transport information.  We will detect if a default value is required after parsing the config */
23945    peer->default_outbound_transport = 0;
23946    peer->transports = 0;
23947 
23948    if (!devstate_only) {
23949       struct sip_mailbox *mailbox;
23950       AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
23951          mailbox->delme = 1;
23952       }
23953    }
23954 
23955    for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
23956       if (!devstate_only) {
23957          if (handle_common_options(&peerflags[0], &mask[0], v)) {
23958             continue;
23959          }
23960          if (handle_t38_options(&peerflags[0], &mask[0], v, &peer->t38_maxdatagram)) {
23961             continue;
23962          }
23963          if (!strcasecmp(v->name, "transport") && !ast_strlen_zero(v->value)) {
23964             char *val = ast_strdupa(v->value);
23965             char *trans;
23966 
23967             while ((trans = strsep(&val, ","))) {
23968                trans = ast_skip_blanks(trans);
23969 
23970                if (!strncasecmp(trans, "udp", 3)) {
23971                   peer->transports |= SIP_TRANSPORT_UDP;
23972                } else if (!strncasecmp(trans, "tcp", 3)) {
23973                   peer->transports |= SIP_TRANSPORT_TCP;
23974                } else if (!strncasecmp(trans, "tls", 3)) {
23975                   peer->transports |= SIP_TRANSPORT_TLS;
23976                } else {
23977                   ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
23978                }
23979 
23980                if (!peer->default_outbound_transport) { /*!< The first transport listed should be default outbound */
23981                   peer->default_outbound_transport = peer->transports;
23982                }
23983             }
23984          } else if (realtime && !strcasecmp(v->name, "regseconds")) {
23985             ast_get_time_t(v->value, &regseconds, 0, NULL);
23986          } else if (realtime && !strcasecmp(v->name, "name")) {
23987             ast_copy_string(peer->name, v->value, sizeof(peer->name));
23988          } else if (realtime && !strcasecmp(v->name, "useragent")) {
23989             ast_string_field_set(peer, useragent, v->value);
23990          } else if (!strcasecmp(v->name, "type")) {
23991             if (!strcasecmp(v->value, "peer")) {
23992                peer->type |= SIP_TYPE_PEER;
23993             } else if (!strcasecmp(v->value, "user")) {
23994                peer->type |= SIP_TYPE_USER;
23995             } else if (!strcasecmp(v->value, "friend")) {
23996                peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
23997             }
23998          } else if (!strcasecmp(v->name, "remotesecret")) {
23999             ast_string_field_set(peer, remotesecret, v->value);
24000          } else if (!strcasecmp(v->name, "secret")) {
24001             ast_string_field_set(peer, secret, v->value);
24002          } else if (!strcasecmp(v->name, "md5secret")) {
24003             ast_string_field_set(peer, md5secret, v->value);
24004          } else if (!strcasecmp(v->name, "auth")) {
24005             peer->auth = add_realm_authentication(peer->auth, v->value, v->lineno);
24006          } else if (!strcasecmp(v->name, "callerid")) {
24007             char cid_name[80] = { '\0' }, cid_num[80] = { '\0' };
24008 
24009             ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
24010             ast_string_field_set(peer, cid_name, cid_name);
24011             ast_string_field_set(peer, cid_num, cid_num);
24012          } else if (!strcasecmp(v->name, "fullname")) {
24013             ast_string_field_set(peer, cid_name, v->value);
24014          } else if (!strcasecmp(v->name, "trunkname")) {
24015             /* This is actually for a trunk, so we don't want to override callerid */
24016             ast_string_field_set(peer, cid_name, "");
24017          } else if (!strcasecmp(v->name, "cid_number")) {
24018             ast_string_field_set(peer, cid_num, v->value);
24019          } else if (!strcasecmp(v->name, "context")) {
24020             ast_string_field_set(peer, context, v->value);
24021             ast_set_flag(&peer->flags[1], SIP_PAGE2_HAVEPEERCONTEXT);
24022          } else if (!strcasecmp(v->name, "subscribecontext")) {
24023             ast_string_field_set(peer, subscribecontext, v->value);
24024          } else if (!strcasecmp(v->name, "fromdomain")) {
24025             ast_string_field_set(peer, fromdomain, v->value);
24026          } else if (!strcasecmp(v->name, "usereqphone")) {
24027             ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
24028          } else if (!strcasecmp(v->name, "fromuser")) {
24029             ast_string_field_set(peer, fromuser, v->value);
24030          } else if (!strcasecmp(v->name, "outboundproxy")) {
24031             char *port, *next, *force, *proxyname;
24032             int forceopt = FALSE;
24033             /* Set peer channel variable */
24034             next = proxyname = ast_strdupa(v->value);
24035             if ((port = strchr(proxyname, ':'))) {
24036                *port++ = '\0';
24037                next = port;
24038             }
24039             if ((force = strchr(next, ','))) {
24040                *force++ = '\0';
24041                forceopt = strcmp(force, "force");
24042             }
24043             /* Allocate proxy object */
24044             peer->outboundproxy = proxy_allocate(proxyname, port, forceopt);
24045          } else if (!strcasecmp(v->name, "host")) {
24046             if (!strcasecmp(v->value, "dynamic")) {
24047                /* They'll register with us */
24048                if (!found || !peer->host_dynamic) {
24049                   /* Initialize stuff if this is a new peer, or if it used to
24050                    * not be dynamic before the reload. */
24051                   memset(&peer->addr.sin_addr, 0, 4);
24052                   peer->addr.sin_port = 0;
24053                }
24054                peer->host_dynamic = TRUE;
24055             } else {
24056                /* Non-dynamic.  Make sure we become that way if we're not */
24057                AST_SCHED_DEL_UNREF(sched, peer->expire,
24058                      unref_peer(peer, "removing register expire ref"));
24059                /* the port will either be set to a default value or a config specified value once all option parsing is complete */
24060                peer->addr.sin_port = 0;
24061                peer->host_dynamic = FALSE;
24062                srvlookup = v->value;
24063             }
24064          } else if (!strcasecmp(v->name, "defaultip")) {
24065             if (!ast_strlen_zero(v->value) && ast_get_ip(&peer->defaddr, v->value)) {
24066                unref_peer(peer, "unref_peer: from build_peer defaultip");
24067                return NULL;
24068             }
24069          } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
24070             int ha_error = 0;
24071             if (!ast_strlen_zero(v->value)) {
24072                peer->ha = ast_append_ha(v->name, v->value, peer->ha, &ha_error);
24073             }
24074             if (ha_error) {
24075                ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
24076             }
24077          } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
24078             int ha_error = 0;
24079             if (!ast_strlen_zero(v->value)) {
24080                peer->contactha = ast_append_ha(v->name + 7, v->value, peer->contactha, &ha_error);
24081             }
24082             if (ha_error) {
24083                ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
24084             }
24085          } else if (!strcasecmp(v->name, "port")) {
24086             peer->portinuri = 1;
24087             if (!(port = port_str2int(v->value, 0))) {
24088                if (realtime) {
24089                   /* If stored as integer, could be 0 for some DBs (notably MySQL) */
24090                   peer->portinuri = 0;
24091                } else {
24092                   ast_log(LOG_WARNING, "Invalid peer port configuration at line %d : %s\n", v->lineno, v->value);
24093                }
24094             }
24095          } else if (!strcasecmp(v->name, "callingpres")) {
24096             peer->callingpres = ast_parse_caller_presentation(v->value);
24097             if (peer->callingpres == -1) {
24098                peer->callingpres = atoi(v->value);
24099             }
24100          } else if (!strcasecmp(v->name, "username") || !strcmp(v->name, "defaultuser")) {   /* "username" is deprecated */
24101             ast_string_field_set(peer, username, v->value);
24102             if (!strcasecmp(v->name, "username")) {
24103                if (deprecation_warning) {
24104                   ast_log(LOG_NOTICE, "The 'username' field for sip peers has been deprecated in favor of the term 'defaultuser'\n");
24105                   deprecation_warning = 0;
24106                }
24107                peer->deprecated_username = 1;
24108             }
24109          } else if (!strcasecmp(v->name, "language")) {
24110             ast_string_field_set(peer, language, v->value);
24111          } else if (!strcasecmp(v->name, "regexten")) {
24112             ast_string_field_set(peer, regexten, v->value);
24113          } else if (!strcasecmp(v->name, "callbackextension")) {
24114             ast_copy_string(callback, v->value, sizeof(callback));
24115          } else if (!strcasecmp(v->name, "amaflags")) {
24116             format = ast_cdr_amaflags2int(v->value);
24117             if (format < 0) {
24118                ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
24119             } else {
24120                peer->amaflags = format;
24121             }
24122          } else if (!strcasecmp(v->name, "accountcode")) {
24123             ast_string_field_set(peer, accountcode, v->value);
24124          } else if (!strcasecmp(v->name, "mohinterpret")) {
24125             ast_string_field_set(peer, mohinterpret, v->value);
24126          } else if (!strcasecmp(v->name, "mohsuggest")) {
24127             ast_string_field_set(peer, mohsuggest, v->value);
24128          } else if (!strcasecmp(v->name, "parkinglot")) {
24129             ast_string_field_set(peer, parkinglot, v->value);
24130          } else if (!strcasecmp(v->name, "mailbox")) {
24131             add_peer_mailboxes(peer, v->value);
24132          } else if (!strcasecmp(v->name, "hasvoicemail")) {
24133             /* People expect that if 'hasvoicemail' is set, that the mailbox will
24134              * be also set, even if not explicitly specified. */
24135             if (ast_true(v->value) && AST_LIST_EMPTY(&peer->mailboxes)) {
24136                add_peer_mailboxes(peer, name);
24137             }
24138          } else if (!strcasecmp(v->name, "subscribemwi")) {
24139             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
24140          } else if (!strcasecmp(v->name, "vmexten")) {
24141             ast_string_field_set(peer, vmexten, v->value);
24142          } else if (!strcasecmp(v->name, "callgroup")) {
24143             peer->callgroup = ast_get_group(v->value);
24144          } else if (!strcasecmp(v->name, "allowtransfer")) {
24145             peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
24146          } else if (!strcasecmp(v->name, "pickupgroup")) {
24147             peer->pickupgroup = ast_get_group(v->value);
24148          } else if (!strcasecmp(v->name, "allow")) {
24149             int error =  ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, TRUE);
24150             if (error) {
24151                ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
24152             }
24153          } else if (!strcasecmp(v->name, "disallow")) {
24154             int error =  ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, FALSE);
24155             if (error) {
24156                ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
24157             }
24158          } else if (!strcasecmp(v->name, "registertrying")) {
24159             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_REGISTERTRYING);
24160          } else if (!strcasecmp(v->name, "autoframing")) {
24161             peer->autoframing = ast_true(v->value);
24162          } else if (!strcasecmp(v->name, "rtptimeout")) {
24163             if ((sscanf(v->value, "%30d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
24164                ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
24165                peer->rtptimeout = global_rtptimeout;
24166             }
24167          } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
24168             if ((sscanf(v->value, "%30d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
24169                ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
24170                peer->rtpholdtimeout = global_rtpholdtimeout;
24171             }
24172          } else if (!strcasecmp(v->name, "rtpkeepalive")) {
24173             if ((sscanf(v->value, "%30d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
24174                ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d.  Using default.\n", v->value, v->lineno);
24175                peer->rtpkeepalive = global_rtpkeepalive;
24176             }
24177          } else if (!strcasecmp(v->name, "timert1")) {
24178             if ((sscanf(v->value, "%30d", &peer->timer_t1) != 1) || (peer->timer_t1 < 0)) {
24179                ast_log(LOG_WARNING, "'%s' is not a valid T1 time at line %d.  Using default.\n", v->value, v->lineno);
24180                peer->timer_t1 = global_t1;
24181             }
24182             /* Note that Timer B is dependent upon T1 and MUST NOT be lower
24183              * than T1 * 64, according to RFC 3261, Section 17.1.1.2 */
24184             if (peer->timer_b < peer->timer_t1 * 64) {
24185                peer->timer_b = peer->timer_t1 * 64;
24186             }
24187          } else if (!strcasecmp(v->name, "timerb")) {
24188             if ((sscanf(v->value, "%30d", &peer->timer_b) != 1) || (peer->timer_b < 0)) {
24189                ast_log(LOG_WARNING, "'%s' is not a valid Timer B time at line %d.  Using default.\n", v->value, v->lineno);
24190                peer->timer_b = global_timer_b;
24191             }
24192             if (peer->timer_b < peer->timer_t1 * 64) {
24193                static int warning = 0;
24194                if (warning++ % 20 == 0) {
24195                   ast_log(LOG_WARNING, "Timer B has been set lower than recommended. (RFC 3261, 17.1.1.2)\n");
24196                }
24197             }
24198          } else if (!strcasecmp(v->name, "setvar")) {
24199             peer->chanvars = add_var(v->value, peer->chanvars);
24200          } else if (!strcasecmp(v->name, "qualifyfreq")) {
24201             int i;
24202             if (sscanf(v->value, "%30d", &i) == 1) {
24203                peer->qualifyfreq = i * 1000;
24204             } else {
24205                ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
24206                peer->qualifyfreq = global_qualifyfreq;
24207             }
24208          } else if (!strcasecmp(v->name, "maxcallbitrate")) {
24209             peer->maxcallbitrate = atoi(v->value);
24210             if (peer->maxcallbitrate < 0) {
24211                peer->maxcallbitrate = default_maxcallbitrate;
24212             }
24213          } else if (!strcasecmp(v->name, "session-timers")) {
24214             int i = (int) str2stmode(v->value);
24215             if (i < 0) {
24216                ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
24217                peer->stimer.st_mode_oper = global_st_mode;
24218             } else {
24219                peer->stimer.st_mode_oper = i;
24220             }
24221          } else if (!strcasecmp(v->name, "session-expires")) {
24222             if (sscanf(v->value, "%30d", &peer->stimer.st_max_se) != 1) {
24223                ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
24224                peer->stimer.st_max_se = global_max_se;
24225             }
24226          } else if (!strcasecmp(v->name, "session-minse")) {
24227             if (sscanf(v->value, "%30d", &peer->stimer.st_min_se) != 1) {
24228                ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
24229                peer->stimer.st_min_se = global_min_se;
24230             }
24231             if (peer->stimer.st_min_se < 90) {
24232                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);
24233                peer->stimer.st_min_se = global_min_se;
24234             }
24235          } else if (!strcasecmp(v->name, "session-refresher")) {
24236             int i = (int) str2strefresher(v->value);
24237             if (i < 0) {
24238                ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
24239                peer->stimer.st_ref = global_st_refresher;
24240             } else {
24241                peer->stimer.st_ref = i;
24242             }
24243          }
24244       }
24245 
24246       /* These apply to devstate lookups */
24247       if (realtime && !strcasecmp(v->name, "lastms")) {
24248          sscanf(v->value, "%30d", &peer->lastms);
24249       } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
24250          inet_aton(v->value, &(peer->addr.sin_addr));
24251       } else if (realtime && !strcasecmp(v->name, "fullcontact")) {
24252          if (alt_fullcontact && !alt) {
24253             /* Reset, because the alternate also has a fullcontact and we
24254              * do NOT want the field value to be doubled. It might be
24255              * tempting to skip this, but the first table might not have
24256              * fullcontact and since we're here, we know that the alternate
24257              * absolutely does. */
24258             alt_fullcontact = 0;
24259             ast_str_reset(fullcontact);
24260          }
24261          /* Reconstruct field, because realtime separates our value at the ';' */
24262          if (fullcontact->used > 0) {
24263             ast_str_append(&fullcontact, 0, ";%s", v->value);
24264          } else {
24265             ast_str_set(&fullcontact, 0, "%s", v->value);
24266          }
24267       } else if (!strcasecmp(v->name, "qualify")) {
24268          if (!strcasecmp(v->value, "no")) {
24269             peer->maxms = 0;
24270          } else if (!strcasecmp(v->value, "yes")) {
24271             peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
24272          } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
24273             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);
24274             peer->maxms = 0;
24275          }
24276          if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->maxms > 0) {
24277             /* This would otherwise cause a network storm, where the
24278              * qualify response refreshes the peer from the database,
24279              * which in turn causes another qualify to be sent, ad
24280              * infinitum. */
24281             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);
24282             peer->maxms = 0;
24283          }
24284       } else if (!strcasecmp(v->name, "callcounter")) {
24285          peer->call_limit = ast_true(v->value) ? INT_MAX : 0;
24286       } else if (!strcasecmp(v->name, "call-limit")) {
24287          peer->call_limit = atoi(v->value);
24288          if (peer->call_limit < 0) {
24289             peer->call_limit = 0;
24290          }
24291       } else if (!strcasecmp(v->name, "busylevel")) {
24292          peer->busy_level = atoi(v->value);
24293          if (peer->busy_level < 0) {
24294             peer->busy_level = 0;
24295          }
24296       }
24297    }
24298 
24299    if (!devstate_only) {
24300       struct sip_mailbox *mailbox;
24301       AST_LIST_TRAVERSE_SAFE_BEGIN(&peer->mailboxes, mailbox, entry) {
24302          if (mailbox->delme) {
24303             AST_LIST_REMOVE_CURRENT(entry);
24304             destroy_mailbox(mailbox);
24305          }
24306       }
24307       AST_LIST_TRAVERSE_SAFE_END;
24308    }
24309 
24310    if (!peer->default_outbound_transport) {
24311       /* Set default set of transports */
24312       peer->transports = default_transports;
24313       /* Set default primary transport */
24314       peer->default_outbound_transport = default_primary_transport;
24315    }
24316 
24317    /* The default transport type set during build_peer should only replace the socket.type when...
24318     * 1. Registration is not present and the socket.type and default transport types are different.
24319     * 2. The socket.type is not an acceptable transport type after rebuilding peer.
24320     * 3. The socket.type is not set yet. */
24321    if (((peer->socket.type != peer->default_outbound_transport) && (peer->expire == -1)) ||
24322       !(peer->socket.type & peer->transports) || !(peer->socket.type)) {
24323 
24324       set_socket_transport(&peer->socket, peer->default_outbound_transport);
24325    }
24326 
24327    if (port && !realtime && peer->host_dynamic) {
24328       peer->defaddr.sin_port = htons(port);
24329    } else if (port) {
24330       peer->addr.sin_port = htons(port);
24331    }
24332 
24333    if (ast_str_strlen(fullcontact)) {
24334       ast_string_field_set(peer, fullcontact, ast_str_buffer(fullcontact));
24335       peer->rt_fromcontact = TRUE;
24336       /* We have a hostname in the fullcontact, but if we don't have an
24337        * address listed on the entry (or if it's 'dynamic'), then we need to
24338        * parse the entry to obtain the IP address, so a dynamic host can be
24339        * contacted immediately after reload (as opposed to waiting for it to
24340        * register once again). But if we have an address for this peer and NAT was
24341        * specified, use that address instead. */
24342       /* XXX May need to revisit the final argument; does the realtime DB store whether
24343        * the original contact was over TLS or not? XXX */
24344       if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) || !peer->addr.sin_addr.s_addr) {
24345          __set_address_from_contact(fullcontact->str, &peer->addr, 0);
24346       }
24347    }
24348 
24349    if (srvlookup && peer->dnsmgr == NULL) {
24350       char transport[MAXHOSTNAMELEN];
24351       char _srvlookup[MAXHOSTNAMELEN];
24352       char *params;
24353 
24354       ast_copy_string(_srvlookup, srvlookup, sizeof(_srvlookup));
24355       if ((params = strchr(_srvlookup, ';'))) {
24356          *params++ = '\0';
24357       }
24358 
24359       snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(peer->socket.type), get_srv_protocol(peer->socket.type));
24360 
24361       if (ast_dnsmgr_lookup(_srvlookup, &peer->addr, &peer->dnsmgr, sip_cfg.srvlookup && !peer->portinuri ? transport : NULL)) {
24362          ast_log(LOG_ERROR, "srvlookup failed for host: %s, on peer %s, removing peer\n", _srvlookup, peer->name);
24363          unref_peer(peer, "getting rid of a peer pointer");
24364          return NULL;
24365       }
24366 
24367       ast_string_field_set(peer, tohost, srvlookup);
24368       if (global_dynamic_exclude_static) {
24369          int err = 0;
24370          global_contact_ha = ast_append_ha("deny", (char *)ast_inet_ntoa(peer->addr.sin_addr), global_contact_ha, &err);
24371          if (err) {
24372             ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
24373          }
24374       }
24375    }
24376 
24377    if (!peer->addr.sin_port) {
24378       peer->addr.sin_port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
24379    }
24380    if (!peer->defaddr.sin_port) {
24381       peer->defaddr.sin_port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
24382    }
24383    if (!peer->socket.port) {
24384       peer->socket.port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
24385    }
24386 
24387    if (!sip_cfg.ignore_regexpire && peer->host_dynamic && realtime) {
24388       time_t nowtime = time(NULL);
24389 
24390       if ((nowtime - regseconds) > 0) {
24391          destroy_association(peer);
24392          memset(&peer->addr, 0, sizeof(peer->addr));
24393          peer->lastms = -1;
24394          ast_debug(1, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
24395       }
24396    }
24397 
24398    /* Startup regular pokes */
24399    if (!devstate_only && realtime && peer->lastms > 0) {
24400       ref_peer(peer, "schedule qualify");
24401       sip_poke_peer(peer, 0);
24402    }
24403 
24404    ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
24405    ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
24406    if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
24407       sip_cfg.allowsubscribe = TRUE;   /* No global ban any more */
24408    }
24409    if (peer->host_dynamic && !peer->is_realtime) {
24410       reg_source_db(peer);
24411    }
24412 
24413    /* If they didn't request that MWI is sent *only* on subscribe, go ahead and
24414     * subscribe to it now. */
24415    if (!devstate_only && !ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
24416       !AST_LIST_EMPTY(&peer->mailboxes)) {
24417       add_peer_mwi_subs(peer);
24418       /* Send MWI from the event cache only.  This is so we can send initial
24419        * MWI if app_voicemail got loaded before chan_sip.  If it is the other
24420        * way, then we will get events when app_voicemail gets loaded. */
24421       sip_send_mwi_to_peer(peer, NULL, 1);
24422    }
24423 
24424    peer->the_mark = 0;
24425 
24426    ast_free_ha(oldha);
24427    if (!ast_strlen_zero(callback)) { /* build string from peer info */
24428       char *reg_string;
24429       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) {
24430          ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
24431       } else if (reg_string) {
24432          sip_register(reg_string, 0); /* XXX TODO: count in registry_count */
24433          ast_free(reg_string);
24434       }
24435    }
24436    return peer;
24437 }
24438 
24439 static int peer_markall_func(void *device, void *arg, int flags)
24440 {
24441    struct sip_peer *peer = device;
24442    peer->the_mark = 1;
24443    return 0;
24444 }
24445 
24446 /*! \brief Re-read SIP.conf config file
24447 \note This function reloads all config data, except for
24448    active peers (with registrations). They will only
24449    change configuration data at restart, not at reload.
24450    SIP debug and recordhistory state will not change
24451  */
24452 static int reload_config(enum channelreloadreason reason)
24453 {
24454    struct ast_config *cfg, *ucfg;
24455    struct ast_variable *v;
24456    struct sip_peer *peer;
24457    char *cat, *stringp, *context, *oldregcontext;
24458    char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
24459    struct ast_flags dummy[2];
24460    struct ast_flags config_flags = { reason == CHANNEL_MODULE_LOAD ? 0 : ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? 0 : CONFIG_FLAG_FILEUNCHANGED };
24461    int auto_sip_domains = FALSE;
24462    struct sockaddr_in old_bindaddr = bindaddr;
24463    int registry_count = 0, peer_count = 0;
24464    time_t run_start, run_end;
24465    
24466    run_start = time(0);
24467    ast_unload_realtime("sipregs");     
24468    ast_unload_realtime("sippeers");
24469    cfg = ast_config_load(config, config_flags);
24470 
24471    /* We *must* have a config file otherwise stop immediately */
24472    if (!cfg) {
24473       ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
24474       return -1;
24475    } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
24476       ucfg = ast_config_load("users.conf", config_flags);
24477       if (ucfg == CONFIG_STATUS_FILEUNCHANGED) {
24478          return 1;
24479       } else if (ucfg == CONFIG_STATUS_FILEINVALID) {
24480          ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
24481          return 1;
24482       }
24483       /* Must reread both files, because one changed */
24484       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
24485       if ((cfg = ast_config_load(config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
24486          ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
24487          ast_config_destroy(ucfg);
24488          return 1;
24489       }
24490    } else if (cfg == CONFIG_STATUS_FILEINVALID) {
24491       ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
24492       return 1;
24493    } else {
24494       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
24495       if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
24496          ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
24497          ast_config_destroy(cfg);
24498          return 1;
24499       }
24500    }
24501 
24502    /* Initialize tcp sockets */
24503    memset(&sip_tcp_desc.local_address, 0, sizeof(sip_tcp_desc.local_address));
24504    memset(&sip_tls_desc.local_address, 0, sizeof(sip_tls_desc.local_address));
24505 
24506    ast_free_ha(global_contact_ha);
24507    global_contact_ha = NULL;
24508 
24509    default_tls_cfg.enabled = FALSE;    /* Default: Disable TLS */
24510 
24511    sip_tcp_desc.local_address.sin_port = htons(STANDARD_SIP_PORT);
24512    sip_tls_desc.local_address.sin_port = htons(STANDARD_TLS_PORT);
24513 
24514    if (reason != CHANNEL_MODULE_LOAD) {
24515       ast_debug(4, "--------------- SIP reload started\n");
24516 
24517       clear_realm_authentication(authl);
24518       clear_sip_domains();
24519       authl = NULL;
24520 
24521       /* First, destroy all outstanding registry calls */
24522       /* This is needed, since otherwise active registry entries will not be destroyed */
24523       ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {  /* regl is locked */
24524 
24525             ASTOBJ_RDLOCK(iterator); /* now regl is locked, and the object is also locked */
24526             if (iterator->call) {
24527                ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
24528                /* This will also remove references to the registry */
24529                dialog_unlink_all(iterator->call, TRUE, TRUE);
24530                iterator->call = dialog_unref(iterator->call, "remove iterator->call from registry traversal");
24531             }
24532             if (iterator->expire > -1) {
24533                AST_SCHED_DEL_UNREF(sched, iterator->expire, registry_unref(iterator, "reg ptr unref from reload config"));
24534             }
24535             if (iterator->timeout > -1) {
24536                AST_SCHED_DEL_UNREF(sched, iterator->timeout, registry_unref(iterator, "reg ptr unref from reload config"));
24537             }
24538             ASTOBJ_UNLOCK(iterator);
24539             
24540       } while(0));
24541 
24542       /* Then, actually destroy users and registry */
24543       ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
24544       ast_debug(4, "--------------- Done destroying registry list\n");
24545       ao2_t_callback(peers, OBJ_NODATA, peer_markall_func, NULL, "callback to mark all peers");
24546    }
24547    
24548    /* Reset certificate handling for TLS sessions */
24549    if (reason != CHANNEL_MODULE_LOAD) {
24550       ast_free(default_tls_cfg.certfile);
24551       ast_free(default_tls_cfg.cipher);
24552       ast_free(default_tls_cfg.cafile);
24553       ast_free(default_tls_cfg.capath);
24554    }
24555    default_tls_cfg.certfile = ast_strdup(AST_CERTFILE); /*XXX Not sure if this is useful */
24556    default_tls_cfg.cipher = ast_strdup("");
24557    default_tls_cfg.cafile = ast_strdup("");
24558    default_tls_cfg.capath = ast_strdup("");
24559 
24560    
24561    /* Initialize copy of current global_regcontext for later use in removing stale contexts */
24562    ast_copy_string(oldcontexts, global_regcontext, sizeof(oldcontexts));
24563    oldregcontext = oldcontexts;
24564 
24565    /* Clear all flags before setting default values */
24566    /* Preserve debugging settings for console */
24567    sipdebug &= sip_debug_console;
24568    ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
24569    ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
24570 
24571    /* Reset IP addresses  */
24572    memset(&bindaddr, 0, sizeof(bindaddr));
24573    memset(&stunaddr, 0, sizeof(stunaddr));
24574    memset(&internip, 0, sizeof(internip));
24575 
24576    /* Free memory for local network address mask */
24577    ast_free_ha(localaddr);
24578    memset(&localaddr, 0, sizeof(localaddr));
24579    memset(&externip, 0, sizeof(externip));
24580    memset(&default_prefs, 0 , sizeof(default_prefs));
24581    memset(&sip_cfg.outboundproxy, 0, sizeof(struct sip_proxy));
24582    sip_cfg.outboundproxy.ip.sin_port = htons(STANDARD_SIP_PORT);
24583    sip_cfg.outboundproxy.ip.sin_family = AF_INET;  /*!< Type of address: IPv4 */
24584    sip_cfg.outboundproxy.force = FALSE;      /*!< Don't force proxy usage, use route: headers */
24585    default_transports = 0;          /*!< Reset default transport to zero here, default value later on */
24586    default_primary_transport = 0;         /*!< Reset default primary transport to zero here, default value later on */
24587    ourport_tcp = STANDARD_SIP_PORT;
24588    ourport_tls = STANDARD_TLS_PORT;
24589    bindaddr.sin_port = htons(STANDARD_SIP_PORT);
24590    sip_cfg.srvlookup = DEFAULT_SRVLOOKUP;
24591    global_tos_sip = DEFAULT_TOS_SIP;
24592    global_tos_audio = DEFAULT_TOS_AUDIO;
24593    global_tos_video = DEFAULT_TOS_VIDEO;
24594    global_tos_text = DEFAULT_TOS_TEXT;
24595    global_cos_sip = DEFAULT_COS_SIP;
24596    global_cos_audio = DEFAULT_COS_AUDIO;
24597    global_cos_video = DEFAULT_COS_VIDEO;
24598    global_cos_text = DEFAULT_COS_TEXT;
24599 
24600    externhost[0] = '\0';         /* External host name (for behind NAT DynDNS support) */
24601    externexpire = 0;       /* Expiration for DNS re-issuing */
24602    externrefresh = 10;
24603 
24604    /* Reset channel settings to default before re-configuring */
24605    sip_cfg.allow_external_domains = DEFAULT_ALLOW_EXT_DOM;           /* Allow external invites */
24606    global_regcontext[0] = '\0';
24607    sip_cfg.regextenonqualify = DEFAULT_REGEXTENONQUALIFY;
24608    sip_cfg.notifyringing = DEFAULT_NOTIFYRINGING;
24609    sip_cfg.notifycid = DEFAULT_NOTIFYCID;
24610    sip_cfg.notifyhold = FALSE;      /*!< Keep track of hold status for a peer */
24611    sip_cfg.directrtpsetup = FALSE;     /* Experimental feature, disabled by default */
24612    sip_cfg.alwaysauthreject = DEFAULT_ALWAYSAUTHREJECT;
24613    sip_cfg.allowsubscribe = FALSE;
24614    snprintf(global_useragent, sizeof(global_useragent), "%s %s", DEFAULT_USERAGENT, ast_get_version());
24615    snprintf(global_sdpsession, sizeof(global_sdpsession), "%s %s", DEFAULT_SDPSESSION, ast_get_version());
24616    snprintf(global_sdpowner, sizeof(global_sdpowner), "%s", DEFAULT_SDPOWNER);
24617    global_prematuremediafilter = TRUE;
24618    ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
24619    ast_copy_string(sip_cfg.realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM), sizeof(sip_cfg.realm));
24620    ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
24621    sip_cfg.compactheaders = DEFAULT_COMPACTHEADERS;
24622    global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
24623    global_regattempts_max = 0;
24624    sip_cfg.pedanticsipchecking = DEFAULT_PEDANTIC;
24625    sip_cfg.autocreatepeer = DEFAULT_AUTOCREATEPEER;
24626    global_autoframing = 0;
24627    sip_cfg.allowguest = DEFAULT_ALLOWGUEST;
24628    global_callcounter = DEFAULT_CALLCOUNTER;
24629    global_match_auth_username = FALSE;    /*!< Match auth username if available instead of From: Default off. */
24630    global_rtptimeout = 0;
24631    global_rtpholdtimeout = 0;
24632    global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
24633    sip_cfg.allowtransfer = TRANSFER_OPENFORALL; /* Merrily accept all transfers by default */
24634    sip_cfg.rtautoclear = 120;
24635    ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE);   /* Default for all devices: TRUE */
24636    ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP);     /* Default for all devices: TRUE */
24637    sip_cfg.peer_rtupdate = TRUE;
24638    global_dynamic_exclude_static = 0;  /* Exclude static peers */
24639 
24640    /* Session-Timers */
24641    global_st_mode = SESSION_TIMER_MODE_ACCEPT;    
24642    global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
24643    global_min_se  = DEFAULT_MIN_SE;
24644    global_max_se  = DEFAULT_MAX_SE;
24645 
24646    /* Peer poking settings */
24647    global_qualify_gap = DEFAULT_QUALIFY_GAP;
24648    global_qualify_peers = DEFAULT_QUALIFY_PEERS;
24649 
24650    /* Initialize some reasonable defaults at SIP reload (used both for channel and as default for devices */
24651    ast_copy_string(sip_cfg.default_context, DEFAULT_CONTEXT, sizeof(sip_cfg.default_context));
24652    sip_cfg.default_subscribecontext[0] = '\0';
24653    default_language[0] = '\0';
24654    default_fromdomain[0] = '\0';
24655    default_qualify = DEFAULT_QUALIFY;
24656    default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
24657    ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
24658    ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
24659    ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
24660    ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833);        /*!< Default DTMF setting: RFC2833 */
24661    ast_set_flag(&global_flags[0], SIP_NAT_RFC3581);         /*!< NAT support if requested by device with rport */
24662    ast_set_flag(&global_flags[0], SIP_DIRECT_MEDIA);        /*!< Allow re-invites */
24663    ast_set_flag(&global_flags[1], SIP_PAGE2_FORWARD_LOOP_DETECTED); /*!< Set up call forward on 482 Loop Detected */
24664 
24665    /* Debugging settings, always default to off */
24666    dumphistory = FALSE;
24667    recordhistory = FALSE;
24668    sipdebug &= ~sip_debug_config;
24669 
24670    /* Misc settings for the channel */
24671    global_relaxdtmf = FALSE;
24672    sip_cfg.callevents = DEFAULT_CALLEVENTS;
24673    global_authfailureevents = FALSE;
24674    global_t1 = DEFAULT_TIMER_T1;
24675    global_timer_b = 64 * DEFAULT_TIMER_T1;
24676    global_t1min = DEFAULT_T1MIN;
24677    global_qualifyfreq = DEFAULT_QUALIFYFREQ;
24678    global_t38_maxdatagram = -1;
24679    global_shrinkcallerid = 1;
24680 
24681    sip_cfg.matchexterniplocally = DEFAULT_MATCHEXTERNIPLOCALLY;
24682 
24683    /* Copy the default jb config over global_jbconf */
24684    memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
24685 
24686    ast_clear_flag(&global_flags[1], SIP_PAGE2_FAX_DETECT);
24687    ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
24688    ast_clear_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT);
24689    ast_clear_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION);
24690 
24691 
24692    /* Read the [general] config section of sip.conf (or from realtime config) */
24693    for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
24694       if (handle_common_options(&global_flags[0], &dummy[0], v))
24695          continue;
24696       if (handle_t38_options(&global_flags[0], &dummy[0], v, &global_t38_maxdatagram)) {
24697          continue;
24698       }
24699       /* handle jb conf */
24700       if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
24701          continue;
24702 
24703       if (!strcasecmp(v->name, "context")) {
24704          ast_copy_string(sip_cfg.default_context, v->value, sizeof(sip_cfg.default_context));
24705       } else if (!strcasecmp(v->name, "subscribecontext")) {
24706          ast_copy_string(sip_cfg.default_subscribecontext, v->value, sizeof(sip_cfg.default_subscribecontext));
24707       } else if (!strcasecmp(v->name, "callcounter")) {
24708          global_callcounter = ast_true(v->value) ? 1 : 0;
24709       } else if (!strcasecmp(v->name, "allowguest")) {
24710          sip_cfg.allowguest = ast_true(v->value) ? 1 : 0;
24711       } else if (!strcasecmp(v->name, "realm")) {
24712          ast_copy_string(sip_cfg.realm, v->value, sizeof(sip_cfg.realm));
24713       } else if (!strcasecmp(v->name, "useragent")) {
24714          ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
24715          ast_debug(1, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
24716       } else if (!strcasecmp(v->name, "sdpsession")) {
24717          ast_copy_string(global_sdpsession, v->value, sizeof(global_sdpsession));
24718       } else if (!strcasecmp(v->name, "sdpowner")) {
24719          /* Field cannot contain spaces */
24720          if (!strstr(v->value, " "))
24721             ast_copy_string(global_sdpowner, v->value, sizeof(global_sdpowner));
24722          else
24723             ast_log(LOG_WARNING, "'%s' must not contain spaces at line %d.  Using default.\n", v->value, v->lineno);
24724       } else if (!strcasecmp(v->name, "allowtransfer")) {
24725          sip_cfg.allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
24726       } else if (!strcasecmp(v->name, "rtcachefriends")) {
24727          ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);   
24728       } else if (!strcasecmp(v->name, "rtsavesysname")) {
24729          sip_cfg.rtsave_sysname = ast_true(v->value);
24730       } else if (!strcasecmp(v->name, "rtupdate")) {
24731          sip_cfg.peer_rtupdate = ast_true(v->value);
24732       } else if (!strcasecmp(v->name, "ignoreregexpire")) {
24733          sip_cfg.ignore_regexpire = ast_true(v->value);
24734       } else if (!strcasecmp(v->name, "timert1")) {
24735          /* Defaults to 500ms, but RFC 3261 states that it is recommended
24736           * for the value to be set higher, though a lower value is only
24737           * allowed on private networks unconnected to the Internet. */
24738          global_t1 = atoi(v->value);
24739          /* Note that timer B is dependent on the value of T1 */
24740          global_timer_b = global_t1 * 64;
24741       } else if (!strcasecmp(v->name, "t1min")) {
24742          global_t1min = atoi(v->value);
24743       } else if (!strcasecmp(v->name, "transport") && !ast_strlen_zero(v->value)) {
24744          char *val = ast_strdupa(v->value);
24745          char *trans;
24746 
24747          while ((trans = strsep(&val, ","))) {
24748             trans = ast_skip_blanks(trans);
24749 
24750             if (!strncasecmp(trans, "udp", 3)) 
24751                default_transports |= SIP_TRANSPORT_UDP;
24752             else if (!strncasecmp(trans, "tcp", 3))
24753                default_transports |= SIP_TRANSPORT_TCP;
24754             else if (!strncasecmp(trans, "tls", 3))
24755                default_transports |= SIP_TRANSPORT_TLS;
24756             else
24757                ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
24758             if (default_primary_transport == 0) {
24759                default_primary_transport = default_transports;
24760             }
24761          }
24762       } else if (!strcasecmp(v->name, "tcpenable")) {
24763          sip_tcp_desc.local_address.sin_family = ast_false(v->value) ? 0 : AF_INET;
24764          ast_debug(2, "Enabling TCP socket for listening\n");
24765       } else if (!strcasecmp(v->name, "tcpbindaddr")) {
24766          int family = sip_tcp_desc.local_address.sin_family;
24767          if (ast_parse_arg(v->value, PARSE_INADDR, &sip_tcp_desc.local_address))
24768             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n", v->name, v->value, v->lineno, config);
24769          sip_tcp_desc.local_address.sin_family = family;
24770          ast_debug(2, "Setting TCP socket address to %s\n", v->value);
24771       } else if (!strcasecmp(v->name, "tlsenable")) {
24772          default_tls_cfg.enabled = ast_true(v->value) ? TRUE : FALSE;
24773          sip_tls_desc.local_address.sin_family = AF_INET;
24774       } else if (!strcasecmp(v->name, "tlscertfile")) {
24775          ast_free(default_tls_cfg.certfile);
24776          default_tls_cfg.certfile = ast_strdup(v->value);
24777       } else if (!strcasecmp(v->name, "tlscipher")) {
24778          ast_free(default_tls_cfg.cipher);
24779          default_tls_cfg.cipher = ast_strdup(v->value);
24780       } else if (!strcasecmp(v->name, "tlscafile")) {
24781          ast_free(default_tls_cfg.cafile);
24782          default_tls_cfg.cafile = ast_strdup(v->value);
24783       } else if (!strcasecmp(v->name, "tlscapath")) {
24784          ast_free(default_tls_cfg.capath);
24785          default_tls_cfg.capath = ast_strdup(v->value);
24786       } else if (!strcasecmp(v->name, "tlsverifyclient")) {
24787          ast_set2_flag(&default_tls_cfg.flags, ast_true(v->value), AST_SSL_VERIFY_CLIENT);   
24788       } else if (!strcasecmp(v->name, "tlsdontverifyserver")) {
24789          ast_set2_flag(&default_tls_cfg.flags, ast_true(v->value), AST_SSL_DONT_VERIFY_SERVER); 
24790       } else if (!strcasecmp(v->name, "tlsbindaddr")) {
24791          if (ast_parse_arg(v->value, PARSE_INADDR, &sip_tls_desc.local_address))
24792             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n", v->name, v->value, v->lineno, config);
24793       } else if (!strcasecmp(v->name, "dynamic_exclude_static") || !strcasecmp(v->name, "dynamic_excludes_static")) {
24794          global_dynamic_exclude_static = ast_true(v->value);
24795       } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
24796          int ha_error = 0;
24797          global_contact_ha = ast_append_ha(v->name + 7, v->value, global_contact_ha, &ha_error);
24798          if (ha_error) {
24799             ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
24800          }
24801       } else if (!strcasecmp(v->name, "rtautoclear")) {
24802          int i = atoi(v->value);
24803          if (i > 0)
24804             sip_cfg.rtautoclear = i;
24805          else
24806             i = 0;
24807          ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
24808       } else if (!strcasecmp(v->name, "usereqphone")) {
24809          ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);   
24810       } else if (!strcasecmp(v->name, "prematuremedia")) {
24811          global_prematuremediafilter = ast_true(v->value);
24812       } else if (!strcasecmp(v->name, "relaxdtmf")) {
24813          global_relaxdtmf = ast_true(v->value);
24814       } else if (!strcasecmp(v->name, "vmexten")) {
24815          ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
24816       } else if (!strcasecmp(v->name, "rtptimeout")) {
24817          if ((sscanf(v->value, "%30d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
24818             ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
24819             global_rtptimeout = 0;
24820          }
24821       } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
24822          if ((sscanf(v->value, "%30d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
24823             ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
24824             global_rtpholdtimeout = 0;
24825          }
24826       } else if (!strcasecmp(v->name, "rtpkeepalive")) {
24827          if ((sscanf(v->value, "%30d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
24828             ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d.  Using default.\n", v->value, v->lineno);
24829             global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
24830          }
24831       } else if (!strcasecmp(v->name, "compactheaders")) {
24832          sip_cfg.compactheaders = ast_true(v->value);
24833       } else if (!strcasecmp(v->name, "notifymimetype")) {
24834          ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
24835       } else if (!strcasecmp(v->name, "directrtpsetup")) {
24836          sip_cfg.directrtpsetup = ast_true(v->value);
24837       } else if (!strcasecmp(v->name, "notifyringing")) {
24838          sip_cfg.notifyringing = ast_true(v->value);
24839       } else if (!strcasecmp(v->name, "notifyhold")) {
24840          sip_cfg.notifyhold = ast_true(v->value);
24841       } else if (!strcasecmp(v->name, "notifycid")) {
24842          if (!strcasecmp(v->value, "ignore-context")) {
24843             sip_cfg.notifycid = IGNORE_CONTEXT;
24844          } else {
24845             sip_cfg.notifycid = ast_true(v->value);
24846          }
24847       } else if (!strcasecmp(v->name, "alwaysauthreject")) {
24848          sip_cfg.alwaysauthreject = ast_true(v->value);
24849       } else if (!strcasecmp(v->name, "mohinterpret")) {
24850          ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
24851       } else if (!strcasecmp(v->name, "mohsuggest")) {
24852          ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
24853       } else if (!strcasecmp(v->name, "language")) {
24854          ast_copy_string(default_language, v->value, sizeof(default_language));
24855       } else if (!strcasecmp(v->name, "regcontext")) {
24856          ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
24857          stringp = newcontexts;
24858          /* Let's remove any contexts that are no longer defined in regcontext */
24859          cleanup_stale_contexts(stringp, oldregcontext);
24860          /* Create contexts if they don't exist already */
24861          while ((context = strsep(&stringp, "&"))) {
24862             ast_copy_string(used_context, context, sizeof(used_context));
24863             ast_context_find_or_create(NULL, NULL, context, "SIP");
24864          }
24865          ast_copy_string(global_regcontext, v->value, sizeof(global_regcontext));
24866       } else if (!strcasecmp(v->name, "regextenonqualify")) {
24867          sip_cfg.regextenonqualify = ast_true(v->value);
24868       } else if (!strcasecmp(v->name, "callerid")) {
24869          ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
24870       } else if (!strcasecmp(v->name, "fromdomain")) {
24871          ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
24872       } else if (!strcasecmp(v->name, "outboundproxy")) {
24873          int portnum;
24874          char *tok, *proxyname;
24875 
24876          if (ast_strlen_zero(v->value)) {
24877             ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf.", v->lineno);
24878             continue;
24879          }
24880 
24881          tok = ast_skip_blanks(strtok(ast_strdupa(v->value), ","));
24882 
24883          sip_parse_host(tok, v->lineno, &proxyname, &portnum, &sip_cfg.outboundproxy.transport);
24884 
24885          sip_cfg.outboundproxy.ip.sin_port = htons(portnum);
24886    
24887          if ((tok = strtok(NULL, ","))) {
24888             sip_cfg.outboundproxy.force = !strncasecmp(ast_skip_blanks(tok), "force", 5);
24889          } else {
24890             sip_cfg.outboundproxy.force = FALSE;
24891          }
24892 
24893          if (ast_strlen_zero(proxyname)) {
24894             ast_log(LOG_WARNING, "you must specify a name for the outboundproxy on line %d of sip.conf.", v->lineno);
24895             sip_cfg.outboundproxy.name[0] = '\0';
24896             continue;
24897          }
24898 
24899          ast_copy_string(sip_cfg.outboundproxy.name, proxyname, sizeof(sip_cfg.outboundproxy.name));
24900 
24901          proxy_update(&sip_cfg.outboundproxy);
24902       } else if (!strcasecmp(v->name, "autocreatepeer")) {
24903          sip_cfg.autocreatepeer = ast_true(v->value);
24904       } else if (!strcasecmp(v->name, "match_auth_username")) {
24905          global_match_auth_username = ast_true(v->value);
24906       } else if (!strcasecmp(v->name, "srvlookup")) {
24907          sip_cfg.srvlookup = ast_true(v->value);
24908       } else if (!strcasecmp(v->name, "pedantic")) {
24909          sip_cfg.pedanticsipchecking = ast_true(v->value);
24910       } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
24911          max_expiry = atoi(v->value);
24912          if (max_expiry < 1)
24913             max_expiry = DEFAULT_MAX_EXPIRY;
24914       } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
24915          min_expiry = atoi(v->value);
24916          if (min_expiry < 1)
24917             min_expiry = DEFAULT_MIN_EXPIRY;
24918       } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
24919          default_expiry = atoi(v->value);
24920          if (default_expiry < 1)
24921             default_expiry = DEFAULT_DEFAULT_EXPIRY;
24922       } else if (!strcasecmp(v->name, "mwiexpiry") || !strcasecmp(v->name, "mwiexpirey")) {
24923          mwi_expiry = atoi(v->value);
24924          if (mwi_expiry < 1)
24925             mwi_expiry = DEFAULT_MWI_EXPIRY;
24926       } else if (!strcasecmp(v->name, "sipdebug")) {
24927          if (ast_true(v->value))
24928             sipdebug |= sip_debug_config;
24929       } else if (!strcasecmp(v->name, "dumphistory")) {
24930          dumphistory = ast_true(v->value);
24931       } else if (!strcasecmp(v->name, "recordhistory")) {
24932          recordhistory = ast_true(v->value);
24933       } else if (!strcasecmp(v->name, "registertimeout")) {
24934          global_reg_timeout = atoi(v->value);
24935          if (global_reg_timeout < 1)
24936             global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
24937       } else if (!strcasecmp(v->name, "registerattempts")) {
24938          global_regattempts_max = atoi(v->value);
24939       } else if (!strcasecmp(v->name, "stunaddr")) {
24940          stunaddr.sin_port = htons(3478);
24941          if (ast_parse_arg(v->value, PARSE_INADDR, &stunaddr))
24942             ast_log(LOG_WARNING, "Invalid STUN server address: %s\n", v->value);
24943          externexpire = time(NULL);
24944       } else if (!strcasecmp(v->name, "bindaddr") || !strcasecmp(v->name, "udpbindaddr")) {
24945          if (ast_parse_arg(v->value, PARSE_INADDR, &bindaddr))
24946             ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
24947       } else if (!strcasecmp(v->name, "localnet")) {
24948          struct ast_ha *na;
24949          int ha_error = 0;
24950 
24951          if (!(na = ast_append_ha("d", v->value, localaddr, &ha_error)))
24952             ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
24953          else
24954             localaddr = na;
24955          if (ha_error)
24956             ast_log(LOG_ERROR, "Bad localnet configuration value line %d : %s\n", v->lineno, v->value);
24957       } else if (!strcasecmp(v->name, "externip")) {
24958          if (ast_parse_arg(v->value, PARSE_INADDR, &externip))
24959             ast_log(LOG_WARNING, "Invalid address for externip keyword: %s\n", v->value);
24960          externexpire = 0;
24961          /* If no port was specified use the value of bindport */
24962          if (!externip.sin_port)
24963             externip.sin_port = bindaddr.sin_port;
24964       } else if (!strcasecmp(v->name, "externhost")) {
24965          ast_copy_string(externhost, v->value, sizeof(externhost));
24966          if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
24967             ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
24968          externexpire = time(NULL);
24969          /* If no port was specified use the value of bindport */
24970          if (!externip.sin_port)
24971             externip.sin_port = bindaddr.sin_port;
24972       } else if (!strcasecmp(v->name, "externrefresh")) {
24973          if (sscanf(v->value, "%30d", &externrefresh) != 1) {
24974             ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
24975             externrefresh = 10;
24976          }
24977       } else if (!strcasecmp(v->name, "allow")) {
24978          int error =  ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, TRUE);
24979          if (error)
24980             ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
24981       } else if (!strcasecmp(v->name, "disallow")) {
24982          int error =  ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, FALSE);
24983          if (error)
24984             ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
24985       } else if (!strcasecmp(v->name, "autoframing")) {
24986          global_autoframing = ast_true(v->value);
24987       } else if (!strcasecmp(v->name, "allowexternaldomains")) {
24988          sip_cfg.allow_external_domains = ast_true(v->value);
24989       } else if (!strcasecmp(v->name, "autodomain")) {
24990          auto_sip_domains = ast_true(v->value);
24991       } else if (!strcasecmp(v->name, "domain")) {
24992          char *domain = ast_strdupa(v->value);
24993          char *cntx = strchr(domain, ',');
24994 
24995          if (cntx)
24996             *cntx++ = '\0';
24997 
24998          if (ast_strlen_zero(cntx))
24999             ast_debug(1, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
25000          if (ast_strlen_zero(domain))
25001             ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
25002          else
25003             add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, cntx ? ast_strip(cntx) : "");
25004       } else if (!strcasecmp(v->name, "register")) {
25005          if (sip_register(v->value, v->lineno) == 0)
25006             registry_count++;
25007       } else if (!strcasecmp(v->name, "mwi")) {
25008          sip_subscribe_mwi(v->value, v->lineno);
25009       } else if (!strcasecmp(v->name, "tos_sip")) {
25010          if (ast_str2tos(v->value, &global_tos_sip))
25011             ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, refer to QoS documentation\n", v->lineno);
25012       } else if (!strcasecmp(v->name, "tos_audio")) {
25013          if (ast_str2tos(v->value, &global_tos_audio))
25014             ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, refer to QoS documentation\n", v->lineno);
25015       } else if (!strcasecmp(v->name, "tos_video")) {
25016          if (ast_str2tos(v->value, &global_tos_video))
25017             ast_log(LOG_WARNING, "Invalid tos_video value at line %d, refer to QoS documentation\n", v->lineno);
25018       } else if (!strcasecmp(v->name, "tos_text")) {
25019          if (ast_str2tos(v->value, &global_tos_text))
25020             ast_log(LOG_WARNING, "Invalid tos_text value at line %d, refer to QoS documentation\n", v->lineno);
25021       } else if (!strcasecmp(v->name, "cos_sip")) {
25022          if (ast_str2cos(v->value, &global_cos_sip))
25023             ast_log(LOG_WARNING, "Invalid cos_sip value at line %d, refer to QoS documentation\n", v->lineno);
25024       } else if (!strcasecmp(v->name, "cos_audio")) {
25025          if (ast_str2cos(v->value, &global_cos_audio))
25026             ast_log(LOG_WARNING, "Invalid cos_audio value at line %d, refer to QoS documentation\n", v->lineno);
25027       } else if (!strcasecmp(v->name, "cos_video")) {
25028          if (ast_str2cos(v->value, &global_cos_video))
25029             ast_log(LOG_WARNING, "Invalid cos_video value at line %d, refer to QoS documentation\n", v->lineno);
25030       } else if (!strcasecmp(v->name, "cos_text")) {
25031          if (ast_str2cos(v->value, &global_cos_text))
25032             ast_log(LOG_WARNING, "Invalid cos_text value at line %d, refer to QoS documentation\n", v->lineno);
25033       } else if (!strcasecmp(v->name, "bindport")) {
25034          int i;
25035          if (sscanf(v->value, "%5d", &i) == 1) {
25036             bindaddr.sin_port = htons(i);
25037          } else {
25038             ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
25039          }
25040       } else if (!strcasecmp(v->name, "qualify")) {
25041          if (!strcasecmp(v->value, "no")) {
25042             default_qualify = 0;
25043          } else if (!strcasecmp(v->value, "yes")) {
25044             default_qualify = DEFAULT_MAXMS;
25045          } else if (sscanf(v->value, "%30d", &default_qualify) != 1) {
25046             ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
25047             default_qualify = 0;
25048          }
25049       } else if (!strcasecmp(v->name, "qualifyfreq")) {
25050          int i;
25051          if (sscanf(v->value, "%30d", &i) == 1)
25052             global_qualifyfreq = i * 1000;
25053          else {
25054             ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
25055             global_qualifyfreq = DEFAULT_QUALIFYFREQ;
25056          }
25057       } else if (!strcasecmp(v->name, "callevents")) {
25058          sip_cfg.callevents = ast_true(v->value);
25059       } else if (!strcasecmp(v->name, "authfailureevents")) {
25060          global_authfailureevents = ast_true(v->value);
25061       } else if (!strcasecmp(v->name, "maxcallbitrate")) {
25062          default_maxcallbitrate = atoi(v->value);
25063          if (default_maxcallbitrate < 0)
25064             default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
25065       } else if (!strcasecmp(v->name, "matchexterniplocally")) {
25066          sip_cfg.matchexterniplocally = ast_true(v->value);
25067       } else if (!strcasecmp(v->name, "session-timers")) {
25068          int i = (int) str2stmode(v->value); 
25069          if (i < 0) {
25070             ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
25071             global_st_mode = SESSION_TIMER_MODE_ACCEPT;
25072          } else {
25073             global_st_mode = i;
25074          }
25075       } else if (!strcasecmp(v->name, "session-expires")) {
25076          if (sscanf(v->value, "%30d", &global_max_se) != 1) {
25077             ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
25078             global_max_se = DEFAULT_MAX_SE;
25079          } 
25080       } else if (!strcasecmp(v->name, "session-minse")) {
25081          if (sscanf(v->value, "%30d", &global_min_se) != 1) {
25082             ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
25083             global_min_se = DEFAULT_MIN_SE;
25084          } 
25085          if (global_min_se < 90) {
25086             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);
25087             global_min_se = DEFAULT_MIN_SE;
25088          } 
25089       } else if (!strcasecmp(v->name, "session-refresher")) {
25090          int i = (int) str2strefresher(v->value); 
25091          if (i < 0) {
25092             ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
25093             global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
25094          } else {
25095             global_st_refresher = i;
25096          }
25097       } else if (!strcasecmp(v->name, "qualifygap")) {
25098          if (sscanf(v->value, "%30d", &global_qualify_gap) != 1) {
25099             ast_log(LOG_WARNING, "Invalid qualifygap '%s' at line %d of %s\n", v->value, v->lineno, config);
25100             global_qualify_gap = DEFAULT_QUALIFY_GAP;
25101          }
25102       } else if (!strcasecmp(v->name, "qualifypeers")) {
25103          if (sscanf(v->value, "%30d", &global_qualify_peers) != 1) {
25104             ast_log(LOG_WARNING, "Invalid pokepeers '%s' at line %d of %s\n", v->value, v->lineno, config);
25105             global_qualify_peers = DEFAULT_QUALIFY_PEERS;
25106          }
25107       } else if (!strcasecmp(v->name, "shrinkcallerid")) {
25108          if (ast_true(v->value)) {
25109             global_shrinkcallerid = 1;
25110          } else if (ast_false(v->value)) {
25111             global_shrinkcallerid = 0;
25112          } else {
25113             ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
25114          }
25115       }
25116    }
25117 
25118    if (!sip_cfg.allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
25119       ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
25120       sip_cfg.allow_external_domains = 1;
25121    }
25122    /* If not configured, set default transports */
25123    if (default_transports == 0) {
25124       default_transports = default_primary_transport = SIP_TRANSPORT_UDP;
25125    }
25126    
25127    /* Build list of authentication to various SIP realms, i.e. service providers */
25128    for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
25129       /* Format for authentication is auth = username:password@realm */
25130       if (!strcasecmp(v->name, "auth"))
25131          authl = add_realm_authentication(authl, v->value, v->lineno);
25132    }
25133 
25134    /* Set UDP address and open socket */
25135    bindaddr.sin_family = AF_INET;
25136    internip = bindaddr;
25137    if (ast_find_ourip(&internip.sin_addr, bindaddr)) {
25138       ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
25139       ast_config_destroy(cfg);
25140       return 0;
25141    }
25142 
25143    ast_mutex_lock(&netlock);
25144    if ((sipsock > -1) && (memcmp(&old_bindaddr, &bindaddr, sizeof(struct sockaddr_in)))) {
25145       close(sipsock);
25146       sipsock = -1;
25147    }
25148    if (sipsock < 0) {
25149       sipsock = socket(AF_INET, SOCK_DGRAM, 0);
25150       if (sipsock < 0) {
25151          ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
25152          ast_config_destroy(cfg);
25153          return -1;
25154       } else {
25155          /* Allow SIP clients on the same host to access us: */
25156          const int reuseFlag = 1;
25157 
25158          setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
25159                (const char*)&reuseFlag,
25160                sizeof reuseFlag);
25161 
25162          ast_enable_packet_fragmentation(sipsock);
25163 
25164          if (bind(sipsock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
25165             ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
25166             ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
25167             strerror(errno));
25168             close(sipsock);
25169             sipsock = -1;
25170          } else {
25171             ast_verb(2, "SIP Listening on %s:%d\n",
25172                   ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
25173             ast_netsock_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
25174          }
25175       }
25176    } else {
25177       ast_netsock_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
25178    }
25179    if (stunaddr.sin_addr.s_addr != 0) {
25180       ast_debug(1, "stun to %s:%d\n",
25181          ast_inet_ntoa(stunaddr.sin_addr) , ntohs(stunaddr.sin_port));
25182       ast_stun_request(sipsock, &stunaddr,
25183          NULL, &externip);
25184       ast_debug(1, "STUN sees us at %s:%d\n", 
25185          ast_inet_ntoa(externip.sin_addr) , ntohs(externip.sin_port));
25186    }
25187    ast_mutex_unlock(&netlock);
25188 
25189    /* Start TCP server */
25190    ast_tcptls_server_start(&sip_tcp_desc);
25191    if (sip_tcp_desc.accept_fd == -1 &&  sip_tcp_desc.local_address.sin_family == AF_INET) {
25192       /* TCP server start failed. Tell the admin */
25193       ast_log(LOG_ERROR, "SIP TCP Server start failed. Not listening on TCP socket.\n");
25194       sip_tcp_desc.local_address.sin_family = 0;
25195    } else {
25196       ast_debug(2, "SIP TCP server started\n");
25197    }
25198 
25199    /* Start TLS server if needed */
25200    memcpy(sip_tls_desc.tls_cfg, &default_tls_cfg, sizeof(default_tls_cfg));
25201 
25202    if (ast_ssl_setup(sip_tls_desc.tls_cfg)) {
25203       ast_tcptls_server_start(&sip_tls_desc);
25204       if (default_tls_cfg.enabled && sip_tls_desc.accept_fd == -1) {
25205          ast_log(LOG_ERROR, "TLS Server start failed. Not listening on TLS socket.\n");
25206          sip_tls_desc.tls_cfg = NULL;
25207       }
25208    } else if (sip_tls_desc.tls_cfg->enabled) {
25209       sip_tls_desc.tls_cfg = NULL;
25210       ast_log(LOG_WARNING, "SIP TLS server did not load because of errors.\n");
25211    }
25212 
25213    if (ucfg) {
25214       struct ast_variable *gen;
25215       int genhassip, genregistersip;
25216       const char *hassip, *registersip;
25217       
25218       genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
25219       genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
25220       gen = ast_variable_browse(ucfg, "general");
25221       cat = ast_category_browse(ucfg, NULL);
25222       while (cat) {
25223          if (strcasecmp(cat, "general")) {
25224             hassip = ast_variable_retrieve(ucfg, cat, "hassip");
25225             registersip = ast_variable_retrieve(ucfg, cat, "registersip");
25226             if (ast_true(hassip) || (!hassip && genhassip)) {
25227                peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0, 0);
25228                if (peer) {
25229                   /* user.conf entries are always of type friend */
25230                   peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
25231                   ao2_t_link(peers, peer, "link peer into peer table");
25232                   if ((peer->type & SIP_TYPE_PEER) && peer->addr.sin_addr.s_addr) {
25233                      ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
25234                   }
25235                   
25236                   unref_peer(peer, "unref_peer: from reload_config");
25237                   peer_count++;
25238                }
25239             }
25240             if (ast_true(registersip) || (!registersip && genregistersip)) {
25241                char tmp[256];
25242                const char *host = ast_variable_retrieve(ucfg, cat, "host");
25243                const char *username = ast_variable_retrieve(ucfg, cat, "username");
25244                const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
25245                const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
25246                const char *authuser = ast_variable_retrieve(ucfg, cat, "authuser");
25247                if (!host)
25248                   host = ast_variable_retrieve(ucfg, "general", "host");
25249                if (!username)
25250                   username = ast_variable_retrieve(ucfg, "general", "username");
25251                if (!secret)
25252                   secret = ast_variable_retrieve(ucfg, "general", "secret");
25253                if (!contact)
25254                   contact = "s";
25255                if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
25256                   if (!ast_strlen_zero(secret)) {
25257                      if (!ast_strlen_zero(authuser)) {
25258                         snprintf(tmp, sizeof(tmp), "%s?%s:%s:%s@%s/%s", cat, username, secret, authuser, host, contact);
25259                      } else {
25260                         snprintf(tmp, sizeof(tmp), "%s?%s:%s@%s/%s", cat, username, secret, host, contact);
25261                      }
25262                   } else if (!ast_strlen_zero(authuser)) {
25263                      snprintf(tmp, sizeof(tmp), "%s?%s::%s@%s/%s", cat, username, authuser, host, contact);
25264                   } else {
25265                      snprintf(tmp, sizeof(tmp), "%s?%s@%s/%s", cat, username, host, contact);
25266                   }
25267                   if (sip_register(tmp, 0) == 0)
25268                      registry_count++;
25269                }
25270             }
25271          }
25272          cat = ast_category_browse(ucfg, cat);
25273       }
25274       ast_config_destroy(ucfg);
25275    }
25276 
25277    /* Load peers, users and friends */
25278    cat = NULL;
25279    while ( (cat = ast_category_browse(cfg, cat)) ) {
25280       const char *utype;
25281       if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
25282          continue;
25283       utype = ast_variable_retrieve(cfg, cat, "type");
25284       if (!utype) {
25285          ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
25286          continue;
25287       } else {
25288          if (!strcasecmp(utype, "user")) {
25289             ;
25290          } else if (!strcasecmp(utype, "friend")) {
25291             ;
25292          } else if (!strcasecmp(utype, "peer")) {
25293             ;
25294          } else {
25295             ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
25296             continue;
25297          }
25298          peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0, 0);
25299          if (peer) {
25300             ao2_t_link(peers, peer, "link peer into peers table");
25301             if ((peer->type & SIP_TYPE_PEER) && peer->addr.sin_addr.s_addr) {
25302                ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
25303             }
25304             unref_peer(peer, "unref the result of the build_peer call. Now, the links from the tables are the only ones left.");
25305             peer_count++;
25306          }
25307       }
25308    }
25309 
25310    /* Add default domains - host name, IP address and IP:port
25311     * Only do this if user added any sip domain with "localdomains" 
25312     * In order to *not* break backwards compatibility 
25313     *    Some phones address us at IP only, some with additional port number 
25314     */
25315    if (auto_sip_domains) {
25316       char temp[MAXHOSTNAMELEN];
25317 
25318       /* First our default IP address */
25319       if (bindaddr.sin_addr.s_addr) {
25320          add_sip_domain(ast_inet_ntoa(bindaddr.sin_addr), SIP_DOMAIN_AUTO, NULL);
25321       } else if (internip.sin_addr.s_addr) {
25322       /* Our internal IP address, if configured */
25323          add_sip_domain(ast_inet_ntoa(internip.sin_addr), SIP_DOMAIN_AUTO, NULL);
25324       } else {
25325          ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
25326       }
25327 
25328       /* If TCP is running on a different IP than UDP, then add it too */
25329       if (sip_tcp_desc.local_address.sin_addr.s_addr && !inaddrcmp(&bindaddr, &sip_tcp_desc.local_address))
25330          add_sip_domain(ast_inet_ntoa(sip_tcp_desc.local_address.sin_addr), SIP_DOMAIN_AUTO, NULL);
25331 
25332       /* If TLS is running on a differen IP than UDP and TCP, then add that too */
25333       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))
25334          add_sip_domain(ast_inet_ntoa(sip_tls_desc.local_address.sin_addr), SIP_DOMAIN_AUTO, NULL);
25335 
25336       /* Our extern IP address, if configured */
25337       if (externip.sin_addr.s_addr)
25338          add_sip_domain(ast_inet_ntoa(externip.sin_addr), SIP_DOMAIN_AUTO, NULL);
25339 
25340       /* Extern host name (NAT traversal support) */
25341       if (!ast_strlen_zero(externhost))
25342          add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
25343       
25344       /* Our host name */
25345       if (!gethostname(temp, sizeof(temp)))
25346          add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
25347    }
25348 
25349    /* Release configuration from memory */
25350    ast_config_destroy(cfg);
25351 
25352    /* Load the list of manual NOTIFY types to support */
25353    if (notify_types)
25354       ast_config_destroy(notify_types);
25355    if ((notify_types = ast_config_load(notify_config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
25356       ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed.\n", notify_config);
25357       notify_types = NULL;
25358    }
25359 
25360    /* Done, tell the manager */
25361    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);
25362    run_end = time(0);
25363    ast_debug(4, "SIP reload_config done...Runtime= %d sec\n", (int)(run_end-run_start));
25364 
25365    return 0;
25366 }
25367 
25368 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
25369 {
25370    struct sip_pvt *p;
25371    struct ast_udptl *udptl = NULL;
25372    
25373    p = chan->tech_pvt;
25374    if (!p)
25375       return NULL;
25376    
25377    sip_pvt_lock(p);
25378    if (p->udptl && ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
25379       udptl = p->udptl;
25380    sip_pvt_unlock(p);
25381    return udptl;
25382 }
25383 
25384 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
25385 {
25386    struct sip_pvt *p;
25387    
25388    p = chan->tech_pvt;
25389    if (!p)
25390       return -1;
25391    sip_pvt_lock(p);
25392    if (udptl)
25393       ast_udptl_get_peer(udptl, &p->udptlredirip);
25394    else
25395       memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
25396    if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
25397       if (!p->pendinginvite) {
25398          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);
25399          transmit_reinvite_with_sdp(p, TRUE, FALSE);
25400       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
25401          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);
25402          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
25403       }
25404    }
25405    /* Reset lastrtprx timer */
25406    p->lastrtprx = p->lastrtptx = time(NULL);
25407    sip_pvt_unlock(p);
25408    return 0;
25409 }
25410 
25411 /*! \brief Returns null if we can't reinvite audio (part of RTP interface) */
25412 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
25413 {
25414    struct sip_pvt *p = NULL;
25415    enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
25416 
25417    if (!(p = chan->tech_pvt))
25418       return AST_RTP_GET_FAILED;
25419 
25420    sip_pvt_lock(p);
25421    if (!(p->rtp)) {
25422       sip_pvt_unlock(p);
25423       return AST_RTP_GET_FAILED;
25424    }
25425 
25426    *rtp = p->rtp;
25427 
25428    if (ast_rtp_getnat(*rtp) && !ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT))
25429       res = AST_RTP_TRY_PARTIAL;
25430    else if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
25431       res = AST_RTP_TRY_NATIVE;
25432    else if (ast_test_flag(&global_jbconf, AST_JB_FORCED))
25433       res = AST_RTP_GET_FAILED;
25434 
25435    sip_pvt_unlock(p);
25436 
25437    return res;
25438 }
25439 
25440 /*! \brief Returns null if we can't reinvite video (part of RTP interface) */
25441 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
25442 {
25443    struct sip_pvt *p = NULL;
25444    enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
25445    
25446    if (!(p = chan->tech_pvt))
25447       return AST_RTP_GET_FAILED;
25448 
25449    sip_pvt_lock(p);
25450    if (!(p->vrtp)) {
25451       sip_pvt_unlock(p);
25452       return AST_RTP_GET_FAILED;
25453    }
25454 
25455    *rtp = p->vrtp;
25456 
25457    if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
25458       res = AST_RTP_TRY_NATIVE;
25459 
25460    sip_pvt_unlock(p);
25461 
25462    return res;
25463 }
25464 
25465 /*! \brief Returns null if we can't reinvite text (part of RTP interface) */
25466 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
25467 {
25468    struct sip_pvt *p = NULL;
25469    enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
25470    
25471    if (!(p = chan->tech_pvt))
25472       return AST_RTP_GET_FAILED;
25473 
25474    sip_pvt_lock(p);
25475    if (!(p->trtp)) {
25476       sip_pvt_unlock(p);
25477       return AST_RTP_GET_FAILED;
25478    }
25479 
25480    *rtp = p->trtp;
25481 
25482    if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
25483       res = AST_RTP_TRY_NATIVE;
25484 
25485    sip_pvt_unlock(p);
25486 
25487    return res;
25488 }
25489 
25490 /*! \brief Set the RTP peer for this call */
25491 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)
25492 {
25493    struct sip_pvt *p;
25494    int changed = 0;
25495 
25496    p = chan->tech_pvt;
25497    if (!p) 
25498       return -1;
25499 
25500    /* Disable early RTP bridge  */
25501    if (!ast_bridged_channel(chan) && !sip_cfg.directrtpsetup)  /* We are in early state */
25502       return 0;
25503 
25504    sip_pvt_lock(p);
25505    if (p->alreadygone) {
25506       /* If we're destroyed, don't bother */
25507       sip_pvt_unlock(p);
25508       return 0;
25509    }
25510 
25511    /* if this peer cannot handle reinvites of the media stream to devices
25512       that are known to be behind a NAT, then stop the process now
25513    */
25514         if (nat_active && !ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
25515                 sip_pvt_unlock(p);
25516                 return 0;
25517         }
25518 
25519    if (rtp) {
25520       changed |= ast_rtp_get_peer(rtp, &p->redirip);
25521    } else if (p->redirip.sin_addr.s_addr || ntohs(p->redirip.sin_port) != 0) {
25522       memset(&p->redirip, 0, sizeof(p->redirip));
25523       changed = 1;
25524    }
25525    if (vrtp) {
25526       changed |= ast_rtp_get_peer(vrtp, &p->vredirip);
25527    } else if (p->vredirip.sin_addr.s_addr || ntohs(p->vredirip.sin_port) != 0) {
25528       memset(&p->vredirip, 0, sizeof(p->vredirip));
25529       changed = 1;
25530    }
25531    if (trtp) {
25532       changed |= ast_rtp_get_peer(trtp, &p->tredirip);
25533    } else if (p->tredirip.sin_addr.s_addr || ntohs(p->tredirip.sin_port) != 0) {
25534       memset(&p->tredirip, 0, sizeof(p->tredirip));
25535       changed = 1;
25536    }
25537    if (codecs && (p->redircodecs != codecs)) {
25538       p->redircodecs = codecs;
25539       changed = 1;
25540    }
25541    if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
25542       if (chan->_state != AST_STATE_UP) { /* We are in early state */
25543          if (p->do_history)
25544             append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
25545          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));
25546       } else if (!p->pendinginvite) {     /* We are up, and have no outstanding invite */
25547          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));
25548          transmit_reinvite_with_sdp(p, FALSE, FALSE);
25549       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
25550          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));
25551          /* We have a pending Invite. Send re-invite when we're done with the invite */
25552          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);   
25553       }
25554    }
25555    /* Reset lastrtprx timer */
25556    p->lastrtprx = p->lastrtptx = time(NULL);
25557    sip_pvt_unlock(p);
25558    return 0;
25559 }
25560 
25561 static char *app_dtmfmode = "SIPDtmfMode";
25562 static char *app_sipaddheader = "SIPAddHeader";
25563 static char *app_sipremoveheader = "SIPRemoveHeader";
25564 
25565 /*! \brief Set the DTMFmode for an outbound SIP call (application) */
25566 static int sip_dtmfmode(struct ast_channel *chan, void *data)
25567 {
25568    struct sip_pvt *p;
25569    char *mode = data;
25570 
25571    if (!data) {
25572       ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
25573       return 0;
25574    }
25575    ast_channel_lock(chan);
25576    if (!IS_SIP_TECH(chan->tech)) {
25577       ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
25578       ast_channel_unlock(chan);
25579       return 0;
25580    }
25581    p = chan->tech_pvt;
25582    if (!p) {
25583       ast_channel_unlock(chan);
25584       return 0;
25585    }
25586    sip_pvt_lock(p);
25587    if (!strcasecmp(mode, "info")) {
25588       ast_clear_flag(&p->flags[0], SIP_DTMF);
25589       ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
25590       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
25591    } else if (!strcasecmp(mode, "shortinfo")) {
25592       ast_clear_flag(&p->flags[0], SIP_DTMF);
25593       ast_set_flag(&p->flags[0], SIP_DTMF_SHORTINFO);
25594       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
25595    } else if (!strcasecmp(mode, "rfc2833")) {
25596       ast_clear_flag(&p->flags[0], SIP_DTMF);
25597       ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
25598       p->jointnoncodeccapability |= AST_RTP_DTMF;
25599    } else if (!strcasecmp(mode, "inband")) { 
25600       ast_clear_flag(&p->flags[0], SIP_DTMF);
25601       ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
25602       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
25603    } else
25604       ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n", mode);
25605    if (p->rtp)
25606       ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
25607    if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
25608       if (!p->dsp) {
25609          p->dsp = ast_dsp_new();
25610          ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
25611       }
25612    } else {
25613       if (p->dsp) {
25614          ast_dsp_free(p->dsp);
25615          p->dsp = NULL;
25616       }
25617    }
25618    sip_pvt_unlock(p);
25619    ast_channel_unlock(chan);
25620    return 0;
25621 }
25622 
25623 /*! \brief Add a SIP header to an outbound INVITE */
25624 static int sip_addheader(struct ast_channel *chan, void *data)
25625 {
25626    int no = 0;
25627    int ok = FALSE;
25628    char varbuf[30];
25629    char *inbuf = data, *subbuf;
25630    
25631    if (ast_strlen_zero(inbuf)) {
25632       ast_log(LOG_WARNING, "This application requires the argument: Header\n");
25633       return 0;
25634    }
25635    ast_channel_lock(chan);
25636 
25637    /* Check for headers */
25638    while (!ok && no <= 50) {
25639       no++;
25640       snprintf(varbuf, sizeof(varbuf), "__SIPADDHEADER%.2d", no);
25641 
25642       /* Compare without the leading underscores */
25643       if ((pbx_builtin_getvar_helper(chan, (const char *) varbuf + 2) == (const char *) NULL)) {
25644          ok = TRUE;
25645       }
25646    }
25647    if (ok) {
25648       size_t len = strlen(inbuf);
25649       subbuf = alloca(len + 1);
25650       ast_get_encoded_str(inbuf, subbuf, len + 1);
25651       pbx_builtin_setvar_helper(chan, varbuf, subbuf);
25652       if (sipdebug) {
25653          ast_debug(1, "SIP Header added \"%s\" as %s\n", inbuf, varbuf);
25654       }
25655    } else {
25656       ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
25657    }
25658    ast_channel_unlock(chan);
25659    return 0;
25660 }
25661 
25662 /*! \brief Remove SIP headers added previously with SipAddHeader application */
25663 static int sip_removeheader(struct ast_channel *chan, void *data)
25664 {
25665    struct ast_var_t *newvariable;
25666    struct varshead *headp;
25667    int removeall = 0;
25668    char *inbuf = (char *) data;
25669 
25670    if (ast_strlen_zero(inbuf)) {
25671       removeall = 1;
25672    }
25673    ast_channel_lock(chan);
25674  
25675    headp=&chan->varshead;
25676    AST_LIST_TRAVERSE_SAFE_BEGIN (headp, newvariable, entries) {
25677       if (strncasecmp(ast_var_name(newvariable), "SIPADDHEADER", strlen("SIPADDHEADER")) == 0) {
25678          if (removeall || (!strncasecmp(ast_var_value(newvariable),inbuf,strlen(inbuf)))) {
25679             if (sipdebug)
25680                ast_log(LOG_DEBUG,"removing SIP Header \"%s\" as %s\n",
25681                   ast_var_value(newvariable),
25682                   ast_var_name(newvariable));
25683             AST_LIST_REMOVE_CURRENT(entries);
25684             ast_var_delete(newvariable);
25685          }
25686       }
25687    }
25688    AST_LIST_TRAVERSE_SAFE_END;
25689  
25690    ast_channel_unlock(chan);
25691    return 0;
25692 }
25693 
25694 /*! \brief Transfer call before connect with a 302 redirect
25695 \note Called by the transfer() dialplan application through the sip_transfer()
25696    pbx interface function if the call is in ringing state 
25697 \todo Fix this function so that we wait for reply to the REFER and
25698    react to errors, denials or other issues the other end might have.
25699  */
25700 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
25701 {
25702    char *cdest;
25703    char *extension, *host, *port;
25704    char tmp[80];
25705 
25706    cdest = ast_strdupa(dest);
25707    
25708    extension = strsep(&cdest, "@");
25709    host = strsep(&cdest, ":");
25710    port = strsep(&cdest, ":");
25711    if (ast_strlen_zero(extension)) {
25712       ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
25713       return 0;
25714    }
25715 
25716    /* we'll issue the redirect message here */
25717    if (!host) {
25718       char *localtmp;
25719 
25720       ast_copy_string(tmp, get_header(&p->initreq, "To"), sizeof(tmp));
25721       if (ast_strlen_zero(tmp)) {
25722          ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
25723          return 0;
25724       }
25725       if ( ( (localtmp = strcasestr(tmp, "sip:")) || (localtmp = strcasestr(tmp, "sips:")) ) 
25726          && (localtmp = strchr(localtmp, '@'))) {
25727          char lhost[80], lport[80];
25728 
25729          memset(lhost, 0, sizeof(lhost));
25730          memset(lport, 0, sizeof(lport));
25731          localtmp++;
25732          /* This is okey because lhost and lport are as big as tmp */
25733          sscanf(localtmp, "%80[^<>:; ]:%80[^<>:; ]", lhost, lport);
25734          if (ast_strlen_zero(lhost)) {
25735             ast_log(LOG_ERROR, "Can't find the host address\n");
25736             return 0;
25737          }
25738          host = ast_strdupa(lhost);
25739          if (!ast_strlen_zero(lport)) {
25740             port = ast_strdupa(lport);
25741          }
25742       }
25743    }
25744 
25745    ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s%s%s>", extension, host, port ? ":" : "", port ? port : "");
25746    transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
25747 
25748    sip_scheddestroy(p, SIP_TRANS_TIMEOUT);   /* Make sure we stop send this reply. */
25749    sip_alreadygone(p);
25750    /* hangup here */
25751    return 0;
25752 }
25753 
25754 /*! \brief Return SIP UA's codec (part of the RTP interface) */
25755 static int sip_get_codec(struct ast_channel *chan)
25756 {
25757    struct sip_pvt *p = chan->tech_pvt;
25758    return p->jointcapability ? p->jointcapability : p->capability;   
25759 }
25760 
25761 /*! \brief Send a poke to all known peers */
25762 static void sip_poke_all_peers(void)
25763 {
25764    int ms = 0, num = 0;
25765    struct ao2_iterator i;
25766    struct sip_peer *peer;
25767 
25768    if (!speerobjs)   /* No peers, just give up */
25769       return;
25770 
25771    i = ao2_iterator_init(peers, 0);
25772    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
25773       ao2_lock(peer);
25774       if (num == global_qualify_peers) {
25775          ms += global_qualify_gap;
25776          num = 0;
25777       } else {
25778          num++;
25779       }
25780       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ms, sip_poke_peer_s, peer,
25781             unref_peer(_data, "removing poke peer ref"),
25782             unref_peer(peer, "removing poke peer ref"),
25783             ref_peer(peer, "adding poke peer ref"));
25784       ao2_unlock(peer);
25785       unref_peer(peer, "toss iterator peer ptr");
25786    }
25787    ao2_iterator_destroy(&i);
25788 }
25789 
25790 /*! \brief Send all known registrations */
25791 static void sip_send_all_registers(void)
25792 {
25793    int ms;
25794    int regspacing;
25795    if (!regobjs)
25796       return;
25797    regspacing = default_expiry * 1000/regobjs;
25798    if (regspacing > 100)
25799       regspacing = 100;
25800    ms = regspacing;
25801    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
25802       ASTOBJ_WRLOCK(iterator);
25803       ms += regspacing;
25804       AST_SCHED_REPLACE_UNREF(iterator->expire, sched, ms, sip_reregister, iterator, 
25805                         registry_unref(_data, "REPLACE sched del decs the refcount"),
25806                         registry_unref(iterator, "REPLACE sched add failure decs the refcount"),
25807                         registry_addref(iterator, "REPLACE sched add incs the refcount"));
25808       ASTOBJ_UNLOCK(iterator);
25809    } while (0)
25810    );
25811 }
25812 
25813 /*! \brief Send all MWI subscriptions */
25814 static void sip_send_all_mwi_subscriptions(void)
25815 {
25816    ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
25817       ASTOBJ_WRLOCK(iterator);
25818       AST_SCHED_DEL(sched, iterator->resub);
25819       if ((iterator->resub = ast_sched_add(sched, 1, sip_subscribe_mwi_do, ASTOBJ_REF(iterator))) < 0) {
25820          ASTOBJ_UNREF(iterator, sip_subscribe_mwi_destroy);
25821       }
25822       ASTOBJ_UNLOCK(iterator);
25823    } while (0));
25824 }
25825 
25826 /*! \brief Reload module */
25827 static int sip_do_reload(enum channelreloadreason reason)
25828 {
25829    time_t start_poke, end_poke;
25830    
25831    reload_config(reason);
25832    ast_sched_dump(sched);
25833 
25834    start_poke = time(0);
25835    /* Prune peers who still are supposed to be deleted */
25836    unlink_marked_peers_from_tables();
25837 
25838    ast_debug(4, "--------------- Done destroying pruned peers\n");
25839 
25840    /* Send qualify (OPTIONS) to all peers */
25841    sip_poke_all_peers();
25842 
25843    /* Register with all services */
25844    sip_send_all_registers();
25845 
25846    sip_send_all_mwi_subscriptions();
25847 
25848    end_poke = time(0);
25849    
25850    ast_debug(4, "do_reload finished. peer poke/prune reg contact time = %d sec.\n", (int)(end_poke-start_poke));
25851 
25852    ast_debug(4, "--------------- SIP reload done\n");
25853 
25854    return 0;
25855 }
25856 
25857 /*! \brief Force reload of module from cli */
25858 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
25859 {
25860    
25861    switch (cmd) {
25862    case CLI_INIT:
25863       e->command = "sip reload";
25864       e->usage =
25865          "Usage: sip reload\n"
25866          "       Reloads SIP configuration from sip.conf\n";
25867       return NULL;
25868    case CLI_GENERATE:
25869       return NULL;
25870    }
25871 
25872    ast_mutex_lock(&sip_reload_lock);
25873    if (sip_reloading) 
25874       ast_verbose("Previous SIP reload not yet done\n");
25875    else {
25876       sip_reloading = TRUE;
25877       sip_reloadreason = (a && a->fd) ? CHANNEL_CLI_RELOAD : CHANNEL_MODULE_RELOAD;
25878    }
25879    ast_mutex_unlock(&sip_reload_lock);
25880    restart_monitor();
25881 
25882    return CLI_SUCCESS;
25883 }
25884 
25885 /*! \brief  Part of Asterisk module interface */
25886 static int reload(void)
25887 {
25888    if (sip_reload(0, 0, NULL))
25889       return 0;
25890    return 1;
25891 }
25892 
25893 /*! \brief SIP Cli commands definition */
25894 static struct ast_cli_entry cli_sip[] = {
25895    AST_CLI_DEFINE(sip_show_channels, "List active SIP channels or subscriptions"),
25896    AST_CLI_DEFINE(sip_show_channelstats, "List statistics for active SIP channels"),
25897    AST_CLI_DEFINE(sip_show_domains, "List our local SIP domains"),
25898    AST_CLI_DEFINE(sip_show_inuse, "List all inuse/limits"),
25899    AST_CLI_DEFINE(sip_show_objects, "List all SIP object allocations"),
25900    AST_CLI_DEFINE(sip_show_peers, "List defined SIP peers"),
25901    AST_CLI_DEFINE(sip_show_registry, "List SIP registration status"),
25902    AST_CLI_DEFINE(sip_unregister, "Unregister (force expiration) a SIP peer from the registry"),
25903    AST_CLI_DEFINE(sip_show_settings, "Show SIP global settings"),
25904    AST_CLI_DEFINE(sip_show_mwi, "Show MWI subscriptions"),
25905    AST_CLI_DEFINE(sip_cli_notify, "Send a notify packet to a SIP peer"),
25906    AST_CLI_DEFINE(sip_show_channel, "Show detailed SIP channel info"),
25907    AST_CLI_DEFINE(sip_show_history, "Show SIP dialog history"),
25908    AST_CLI_DEFINE(sip_show_peer, "Show details on specific SIP peer"),
25909    AST_CLI_DEFINE(sip_show_users, "List defined SIP users"),
25910    AST_CLI_DEFINE(sip_show_user, "Show details on specific SIP user"),
25911    AST_CLI_DEFINE(sip_qualify_peer, "Send an OPTIONS packet to a peer"),
25912    AST_CLI_DEFINE(sip_show_sched, "Present a report on the status of the sched queue"),
25913    AST_CLI_DEFINE(sip_prune_realtime, "Prune cached Realtime users/peers"),
25914    AST_CLI_DEFINE(sip_do_debug, "Enable/Disable SIP debugging"),
25915    AST_CLI_DEFINE(sip_set_history, "Enable/Disable SIP history"),
25916    AST_CLI_DEFINE(sip_reload, "Reload SIP configuration"),
25917    AST_CLI_DEFINE(sip_show_tcp, "List TCP Connections")
25918 };
25919 
25920 /*! \brief PBX load module - initialization */
25921 static int load_module(void)
25922 {
25923    ast_verbose("SIP channel loading...\n");
25924    /* the fact that ao2_containers can't resize automatically is a major worry! */
25925    /* if the number of objects gets above MAX_XXX_BUCKETS, things will slow down */
25926    peers = ao2_t_container_alloc(HASH_PEER_SIZE, peer_hash_cb, peer_cmp_cb, "allocate peers");
25927    peers_by_ip = ao2_t_container_alloc(HASH_PEER_SIZE, peer_iphash_cb, peer_ipcmp_cb, "allocate peers_by_ip");
25928    dialogs = ao2_t_container_alloc(HASH_DIALOG_SIZE, dialog_hash_cb, dialog_cmp_cb, "allocate dialogs");
25929    threadt = ao2_t_container_alloc(HASH_DIALOG_SIZE, threadt_hash_cb, threadt_cmp_cb, "allocate threadt table");
25930    
25931    ASTOBJ_CONTAINER_INIT(&regl); /* Registry object list -- not searched for anything */
25932    ASTOBJ_CONTAINER_INIT(&submwil); /* MWI subscription object list */
25933 
25934    if (!(sched = sched_context_create())) {
25935       ast_log(LOG_ERROR, "Unable to create scheduler context\n");
25936       return AST_MODULE_LOAD_FAILURE;
25937    }
25938 
25939    if (!(io = io_context_create())) {
25940       ast_log(LOG_ERROR, "Unable to create I/O context\n");
25941       sched_context_destroy(sched);
25942       return AST_MODULE_LOAD_FAILURE;
25943    }
25944 
25945    sip_reloadreason = CHANNEL_MODULE_LOAD;
25946 
25947    if(reload_config(sip_reloadreason)) /* Load the configuration from sip.conf */
25948       return AST_MODULE_LOAD_DECLINE;
25949 
25950    /* Prepare the version that does not require DTMF BEGIN frames.
25951     * We need to use tricks such as memcpy and casts because the variable
25952     * has const fields.
25953     */
25954    memcpy(&sip_tech_info, &sip_tech, sizeof(sip_tech));
25955    memset((void *) &sip_tech_info.send_digit_begin, 0, sizeof(sip_tech_info.send_digit_begin));
25956 
25957    /* Make sure we can register our sip channel type */
25958    if (ast_channel_register(&sip_tech)) {
25959       ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
25960       io_context_destroy(io);
25961       sched_context_destroy(sched);
25962       return AST_MODULE_LOAD_FAILURE;
25963    }
25964 
25965    /* Register all CLI functions for SIP */
25966    ast_cli_register_multiple(cli_sip, ARRAY_LEN(cli_sip));
25967 
25968    /* Tell the RTP subdriver that we're here */
25969    ast_rtp_proto_register(&sip_rtp);
25970 
25971    /* Tell the UDPTL subdriver that we're here */
25972    ast_udptl_proto_register(&sip_udptl);
25973 
25974    /* Register dialplan applications */
25975    ast_register_application_xml(app_dtmfmode, sip_dtmfmode);
25976    ast_register_application_xml(app_sipaddheader, sip_addheader);
25977    ast_register_application_xml(app_sipremoveheader, sip_removeheader);
25978 
25979    /* Register dialplan functions */
25980    ast_custom_function_register(&sip_header_function);
25981    ast_custom_function_register(&sippeer_function);
25982    ast_custom_function_register(&sipchaninfo_function);
25983    ast_custom_function_register(&checksipdomain_function);
25984 
25985    /* Register manager commands */
25986    ast_manager_register2("SIPpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peers,
25987          "List SIP peers (text format)", mandescr_show_peers);
25988    ast_manager_register2("SIPshowpeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peer,
25989          "Show SIP peer (text format)", mandescr_show_peer);
25990    ast_manager_register2("SIPqualifypeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_qualify_peer,
25991          "Show SIP peer (text format)", mandescr_show_peer);   /*! \todo Fix this XXX This must be all wrong XXXX */
25992    ast_manager_register2("SIPshowregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_show_registry,
25993          "Show SIP registrations (text format)", mandescr_show_registry);
25994    ast_manager_register2("SIPnotify", EVENT_FLAG_SYSTEM, manager_sipnotify,
25995          "Send a SIP notify", mandescr_sipnotify);
25996    sip_poke_all_peers();   
25997    sip_send_all_registers();
25998    sip_send_all_mwi_subscriptions();
25999 
26000    /* And start the monitor for the first time */
26001    restart_monitor();
26002 
26003    ast_realtime_require_field(ast_check_realtime("sipregs") ? "sipregs" : "sippeers",
26004       "name", RQ_CHAR, 10,
26005       "ipaddr", RQ_CHAR, 15,
26006       "port", RQ_UINTEGER2, 5,
26007       "regseconds", RQ_INTEGER4, 11,
26008       "defaultuser", RQ_CHAR, 10,
26009       "fullcontact", RQ_CHAR, 35,
26010       "regserver", RQ_CHAR, 20,
26011       "useragent", RQ_CHAR, 20,
26012       "lastms", RQ_INTEGER4, 11,
26013       SENTINEL);
26014 
26015    return AST_MODULE_LOAD_SUCCESS;
26016 }
26017 
26018 /*! \brief PBX unload module API */
26019 static int unload_module(void)
26020 {
26021    struct sip_pvt *p;
26022    struct sip_threadinfo *th;
26023    struct ast_context *con;
26024    struct ao2_iterator i;
26025 
26026    ast_sched_dump(sched);
26027    
26028    /* First, take us out of the channel type list */
26029    ast_channel_unregister(&sip_tech);
26030 
26031    /* Unregister dial plan functions */
26032    ast_custom_function_unregister(&sipchaninfo_function);
26033    ast_custom_function_unregister(&sippeer_function);
26034    ast_custom_function_unregister(&sip_header_function);
26035    ast_custom_function_unregister(&checksipdomain_function);
26036 
26037    /* Unregister dial plan applications */
26038    ast_unregister_application(app_dtmfmode);
26039    ast_unregister_application(app_sipaddheader);
26040    ast_unregister_application(app_sipremoveheader);
26041 
26042    /* Unregister CLI commands */
26043    ast_cli_unregister_multiple(cli_sip, ARRAY_LEN(cli_sip));
26044 
26045    /* Disconnect from the RTP subsystem */
26046    ast_rtp_proto_unregister(&sip_rtp);
26047 
26048    /* Disconnect from UDPTL */
26049    ast_udptl_proto_unregister(&sip_udptl);
26050 
26051    /* Unregister AMI actions */
26052    ast_manager_unregister("SIPpeers");
26053    ast_manager_unregister("SIPshowpeer");
26054    ast_manager_unregister("SIPqualifypeer");
26055    ast_manager_unregister("SIPshowregistry");
26056    ast_manager_unregister("SIPnotify");
26057    
26058    /* Kill TCP/TLS server threads */
26059    if (sip_tcp_desc.master)
26060       ast_tcptls_server_stop(&sip_tcp_desc);
26061    if (sip_tls_desc.master)
26062       ast_tcptls_server_stop(&sip_tls_desc);
26063 
26064    /* Kill all existing TCP/TLS threads */
26065    i = ao2_iterator_init(threadt, 0);
26066    while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
26067       pthread_t thread = th->threadid;
26068       th->stop = 1;
26069       pthread_kill(thread, SIGURG);
26070       pthread_join(thread, NULL);
26071       ao2_t_ref(th, -1, "decrement ref from iterator");
26072    }
26073    ao2_iterator_destroy(&i);
26074 
26075    /* Hangup all dialogs if they have an owner */
26076    i = ao2_iterator_init(dialogs, 0);
26077    while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
26078       if (p->owner)
26079          ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
26080       ao2_t_ref(p, -1, "toss dialog ptr from iterator_next");
26081    }
26082    ao2_iterator_destroy(&i);
26083 
26084    ast_mutex_lock(&monlock);
26085    if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
26086       pthread_cancel(monitor_thread);
26087       pthread_kill(monitor_thread, SIGURG);
26088       pthread_join(monitor_thread, NULL);
26089    }
26090    monitor_thread = AST_PTHREADT_STOP;
26091    ast_mutex_unlock(&monlock);
26092 
26093    /* Destroy all the dialogs and free their memory */
26094    i = ao2_iterator_init(dialogs, 0);
26095    while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
26096       dialog_unlink_all(p, TRUE, TRUE);
26097       ao2_t_ref(p, -1, "throw away iterator result"); 
26098    }
26099    ao2_iterator_destroy(&i);
26100 
26101    /* Free memory for local network address mask */
26102    ast_free_ha(localaddr);
26103 
26104    clear_realm_authentication(authl);
26105 
26106 
26107    if (default_tls_cfg.certfile)
26108       ast_free(default_tls_cfg.certfile);
26109    if (default_tls_cfg.cipher)
26110       ast_free(default_tls_cfg.cipher);
26111    if (default_tls_cfg.cafile)
26112       ast_free(default_tls_cfg.cafile);
26113    if (default_tls_cfg.capath)
26114       ast_free(default_tls_cfg.capath);
26115 
26116    ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
26117    ASTOBJ_CONTAINER_DESTROY(&regl);
26118    ASTOBJ_CONTAINER_DESTROYALL(&submwil, sip_subscribe_mwi_destroy);
26119    ASTOBJ_CONTAINER_DESTROY(&submwil);
26120 
26121    ao2_t_ref(peers, -1, "unref the peers table");
26122    ao2_t_ref(peers_by_ip, -1, "unref the peers_by_ip table");
26123    ao2_t_ref(dialogs, -1, "unref the dialogs table");
26124    ao2_t_ref(threadt, -1, "unref the thread table");
26125 
26126    clear_sip_domains();
26127    ast_free_ha(global_contact_ha);
26128    close(sipsock);
26129    sched_context_destroy(sched);
26130    con = ast_context_find(used_context);
26131    if (con)
26132       ast_context_destroy(con, "SIP");
26133    ast_unload_realtime("sipregs");
26134    ast_unload_realtime("sippeers");
26135 
26136    return 0;
26137 }
26138 
26139 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Session Initiation Protocol (SIP)",
26140       .load = load_module,
26141       .unload = unload_module,
26142       .reload = reload,
26143           );