Wed Aug 11 01:05:07 2010

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: 277563 $")
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 
03108 /*!
03109  * helper functions to unreference various types of objects.
03110  * By handling them this way, we don't have to declare the
03111  * destructor on each call, which removes the chance of errors.
03112  */
03113 static void *unref_peer(struct sip_peer *peer, char *tag)
03114 {
03115    ao2_t_ref(peer, -1, tag);
03116    return NULL;
03117 }
03118 
03119 static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
03120 {
03121    ao2_t_ref(peer, 1, tag);
03122    return peer;
03123 }
03124 
03125 /*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
03126  *
03127  * This function sets pvt's outboundproxy pointer to the one referenced
03128  * by the proxy parameter. Because proxy may be a refcounted object, and
03129  * because pvt's old outboundproxy may also be a refcounted object, we need
03130  * to maintain the proper refcounts.
03131  *
03132  * \param pvt The sip_pvt for which we wish to set the outboundproxy
03133  * \param proxy The sip_proxy which we will point pvt towards.
03134  * \return Returns void
03135  */
03136 static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
03137 {
03138    struct sip_proxy *old_obproxy = pvt->outboundproxy;
03139    /* The sip_cfg.outboundproxy is statically allocated, and so
03140     * we don't ever need to adjust refcounts for it
03141     */
03142    if (proxy && proxy != &sip_cfg.outboundproxy) {
03143       ao2_ref(proxy, +1);
03144    }
03145    pvt->outboundproxy = proxy;
03146    if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
03147       ao2_ref(old_obproxy, -1);
03148    }
03149 }
03150 
03151 /*!
03152  * \brief Unlink a dialog from the dialogs container, as well as any other places
03153  * that it may be currently stored.
03154  *
03155  * \note A reference to the dialog must be held before calling this function, and this
03156  * function does not release that reference.
03157  */
03158 static void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist)
03159 {
03160    struct sip_pkt *cp;
03161 
03162    dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
03163 
03164    ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
03165 
03166    /* Unlink us from the owner (channel) if we have one */
03167    if (dialog->owner) {
03168       if (lockowner)
03169          ast_channel_lock(dialog->owner);
03170       ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
03171       dialog->owner->tech_pvt = dialog_unref(dialog->owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
03172       if (lockowner)
03173          ast_channel_unlock(dialog->owner);
03174    }
03175    if (dialog->registry) {
03176       if (dialog->registry->call == dialog)
03177          dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
03178       dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
03179    }
03180    if (dialog->stateid > -1) {
03181       ast_extension_state_del(dialog->stateid, NULL);
03182       dialog_unref(dialog, "removing extension_state, should unref the associated dialog ptr that was stored there.");
03183       dialog->stateid = -1; /* shouldn't we 'zero' this out? */
03184    }
03185    /* Remove link from peer to subscription of MWI */
03186    if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog)
03187       dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
03188    if (dialog->relatedpeer && dialog->relatedpeer->call == dialog)
03189       dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
03190 
03191    /* remove all current packets in this dialog */
03192    while((cp = dialog->packets)) {
03193       dialog->packets = dialog->packets->next;
03194       AST_SCHED_DEL(sched, cp->retransid);
03195       dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
03196       if (cp->data) {
03197          ast_free(cp->data);
03198       }
03199       ast_free(cp);
03200    }
03201 
03202    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"));
03203 
03204    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"));
03205    
03206    if (dialog->autokillid > -1)
03207       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"));
03208 
03209    if (dialog->request_queue_sched_id > -1) {
03210       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"));
03211    }
03212 
03213    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"));
03214 
03215    if (dialog->t38id > -1) {
03216       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"));
03217    }
03218 
03219    dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
03220    return NULL;
03221 }
03222 
03223 static void *registry_unref(struct sip_registry *reg, char *tag)
03224 {
03225    ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
03226    ASTOBJ_UNREF(reg, sip_registry_destroy);
03227    return NULL;
03228 }
03229 
03230 /*! \brief Add object reference to SIP registry */
03231 static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
03232 {
03233    ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
03234    return ASTOBJ_REF(reg); /* Add pointer to registry in packet */
03235 }
03236 
03237 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
03238 static struct ast_udptl_protocol sip_udptl = {
03239    type: "SIP",
03240    get_udptl_info: sip_get_udptl_peer,
03241    set_udptl_peer: sip_set_udptl_peer,
03242 };
03243 
03244 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03245    __attribute__((format(printf, 2, 3)));
03246 
03247 
03248 /*! \brief Convert transfer status to string */
03249 static const char *referstatus2str(enum referstatus rstatus)
03250 {
03251    return map_x_s(referstatusstrings, rstatus, "");
03252 }
03253 
03254 static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
03255 {
03256    append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
03257    pvt->needdestroy = 1;
03258 }
03259 
03260 /*! \brief Initialize the initital request packet in the pvt structure.
03261    This packet is used for creating replies and future requests in
03262    a dialog */
03263 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
03264 {
03265    if (p->initreq.headers)
03266       ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
03267    else
03268       ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
03269    /* Use this as the basis */
03270    copy_request(&p->initreq, req);
03271    parse_request(&p->initreq);
03272    if (req->debug)
03273       ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
03274 }
03275 
03276 /*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
03277 static void sip_alreadygone(struct sip_pvt *dialog)
03278 {
03279    ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
03280    dialog->alreadygone = 1;
03281 }
03282 
03283 /*! Resolve DNS srv name or host name in a sip_proxy structure */
03284 static int proxy_update(struct sip_proxy *proxy)
03285 {
03286    /* if it's actually an IP address and not a name,
03287            there's no need for a managed lookup */
03288    if (!inet_aton(proxy->name, &proxy->ip.sin_addr)) {
03289       /* Ok, not an IP address, then let's check if it's a domain or host */
03290       /* XXX Todo - if we have proxy port, don't do SRV */
03291       if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
03292          ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
03293          return FALSE;
03294       }
03295    }
03296    proxy->last_dnsupdate = time(NULL);
03297    return TRUE;
03298 }
03299 
03300 /*! \brief converts ascii port to int representation. If no
03301  *  pt buffer is provided or the pt has errors when being converted
03302  *  to an int value, the port provided as the standard is used.
03303  */
03304 static int port_str2int(const char *pt, unsigned int standard)
03305 {
03306    int port = standard;
03307    if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
03308       port = standard;
03309    }
03310 
03311    return port;
03312 }
03313 
03314 /*! \brief Allocate and initialize sip proxy */
03315 static struct sip_proxy *proxy_allocate(char *name, char *port, int force)
03316 {
03317    struct sip_proxy *proxy;
03318 
03319    if (ast_strlen_zero(name)) {
03320       return NULL;
03321    }
03322 
03323    proxy = ao2_alloc(sizeof(*proxy), NULL);
03324    if (!proxy)
03325       return NULL;
03326    proxy->force = force;
03327    ast_copy_string(proxy->name, name, sizeof(proxy->name));
03328    proxy->ip.sin_port = htons(port_str2int(port, STANDARD_SIP_PORT));
03329    proxy->ip.sin_family = AF_INET;
03330    proxy_update(proxy);
03331    return proxy;
03332 }
03333 
03334 /*! \brief Get default outbound proxy or global proxy */
03335 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
03336 {
03337    if (peer && peer->outboundproxy) {
03338       if (sipdebug)
03339          ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
03340       append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
03341       return peer->outboundproxy;
03342    }
03343    if (sip_cfg.outboundproxy.name[0]) {
03344       if (sipdebug)
03345          ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
03346       append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
03347       return &sip_cfg.outboundproxy;
03348    }
03349    if (sipdebug)
03350       ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
03351    return NULL;
03352 }
03353 
03354 /*! \brief returns true if 'name' (with optional trailing whitespace)
03355  * matches the sip method 'id'.
03356  * Strictly speaking, SIP methods are case SENSITIVE, but we do
03357  * a case-insensitive comparison to be more tolerant.
03358  * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
03359  */
03360 static int method_match(enum sipmethod id, const char *name)
03361 {
03362    int len = strlen(sip_methods[id].text);
03363    int l_name = name ? strlen(name) : 0;
03364    /* true if the string is long enough, and ends with whitespace, and matches */
03365    return (l_name >= len && name[len] < 33 &&
03366       !strncasecmp(sip_methods[id].text, name, len));
03367 }
03368 
03369 /*! \brief  find_sip_method: Find SIP method from header */
03370 static int find_sip_method(const char *msg)
03371 {
03372    int i, res = 0;
03373    
03374    if (ast_strlen_zero(msg))
03375       return 0;
03376    for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
03377       if (method_match(i, msg))
03378          res = sip_methods[i].id;
03379    }
03380    return res;
03381 }
03382 
03383 /*! \brief Parse supported header in incoming packet */
03384 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
03385 {
03386    char *next, *sep;
03387    char *temp;
03388    unsigned int profile = 0;
03389    int i, found;
03390 
03391    if (ast_strlen_zero(supported) )
03392       return 0;
03393    temp = ast_strdupa(supported);
03394 
03395    if (sipdebug)
03396       ast_debug(3, "Begin: parsing SIP \"Supported: %s\"\n", supported);
03397 
03398    for (next = temp; next; next = sep) {
03399       found = FALSE;
03400       if ( (sep = strchr(next, ',')) != NULL)
03401          *sep++ = '\0';
03402       next = ast_skip_blanks(next);
03403       if (sipdebug)
03404          ast_debug(3, "Found SIP option: -%s-\n", next);
03405       for (i = 0; i < ARRAY_LEN(sip_options); i++) {
03406          if (!strcasecmp(next, sip_options[i].text)) {
03407             profile |= sip_options[i].id;
03408             found = TRUE;
03409             if (sipdebug)
03410                ast_debug(3, "Matched SIP option: %s\n", next);
03411             break;
03412          }
03413       }
03414 
03415       /* This function is used to parse both Suported: and Require: headers.
03416       Let the caller of this function know that an unknown option tag was 
03417       encountered, so that if the UAC requires it then the request can be 
03418       rejected with a 420 response. */
03419       if (!found)
03420          profile |= SIP_OPT_UNKNOWN;
03421 
03422       if (!found && sipdebug) {
03423          if (!strncasecmp(next, "x-", 2))
03424             ast_debug(3, "Found private SIP option, not supported: %s\n", next);
03425          else
03426             ast_debug(3, "Found no match for SIP option: %s (Please file bug report!)\n", next);
03427       }
03428    }
03429 
03430    if (pvt)
03431       pvt->sipoptions = profile;
03432    return profile;
03433 }
03434 
03435 /*! \brief See if we pass debug IP filter */
03436 static inline int sip_debug_test_addr(const struct sockaddr_in *addr) 
03437 {
03438    if (!sipdebug)
03439       return 0;
03440    if (debugaddr.sin_addr.s_addr) {
03441       if (((ntohs(debugaddr.sin_port) != 0)
03442          && (debugaddr.sin_port != addr->sin_port))
03443          || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
03444          return 0;
03445    }
03446    return 1;
03447 }
03448 
03449 /*! \brief The real destination address for a write */
03450 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
03451 {
03452    if (p->outboundproxy)
03453       return &p->outboundproxy->ip;
03454 
03455    return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
03456 }
03457 
03458 /*! \brief Display SIP nat mode */
03459 static const char *sip_nat_mode(const struct sip_pvt *p)
03460 {
03461    return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
03462 }
03463 
03464 /*! \brief Test PVT for debugging output */
03465 static inline int sip_debug_test_pvt(struct sip_pvt *p) 
03466 {
03467    if (!sipdebug)
03468       return 0;
03469    return sip_debug_test_addr(sip_real_dst(p));
03470 }
03471 
03472 /*! \brief Return int representing a bit field of transport types found in const char *transport */
03473 static int get_transport_str2enum(const char *transport)
03474 {
03475    int res = 0;
03476 
03477    if (ast_strlen_zero(transport)) {
03478       return res;
03479    }
03480 
03481    if (!strcasecmp(transport, "udp")) {
03482       res |= SIP_TRANSPORT_UDP;
03483    }
03484    if (!strcasecmp(transport, "tcp")) {
03485       res |= SIP_TRANSPORT_TCP;
03486    }
03487    if (!strcasecmp(transport, "tls")) {
03488       res |= SIP_TRANSPORT_TLS;
03489    }
03490 
03491    return res;
03492 }
03493 
03494 /*! \brief Return configuration of transports for a device */
03495 static inline const char *get_transport_list(unsigned int transports) {
03496    switch (transports) {
03497       case SIP_TRANSPORT_UDP:
03498          return "UDP";
03499       case SIP_TRANSPORT_TCP:
03500          return "TCP";
03501       case SIP_TRANSPORT_TLS:
03502          return "TLS";
03503       case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
03504          return "TCP,UDP";
03505       case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
03506          return "TLS,UDP";
03507       case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
03508          return "TLS,TCP";
03509       default:
03510          return transports ? 
03511             "TLS,TCP,UDP" : "UNKNOWN"; 
03512    }
03513 }
03514 
03515 /*! \brief Return transport as string */
03516 static inline const char *get_transport(enum sip_transport t)
03517 {
03518    switch (t) {
03519    case SIP_TRANSPORT_UDP:
03520       return "UDP";
03521    case SIP_TRANSPORT_TCP:
03522       return "TCP";
03523    case SIP_TRANSPORT_TLS:
03524       return "TLS";
03525    }
03526 
03527    return "UNKNOWN";
03528 }
03529 
03530 /*! \brief Return transport of dialog.
03531    \note this is based on a false assumption. We don't always use the
03532    outbound proxy for all requests in a dialog. It depends on the
03533    "force" parameter. The FIRST request is always sent to the ob proxy.
03534    \todo Fix this function to work correctly
03535 */
03536 static inline const char *get_transport_pvt(struct sip_pvt *p)
03537 {
03538    if (p->outboundproxy && p->outboundproxy->transport) {
03539       set_socket_transport(&p->socket, p->outboundproxy->transport);
03540    }
03541 
03542    return get_transport(p->socket.type);
03543 }
03544 
03545 /*! \brief Transmit SIP message 
03546    Sends a SIP request or response on a given socket (in the pvt)
03547    Called by retrans_pkt, send_request, send_response and 
03548    __sip_reliable_xmit
03549 */
03550 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len)
03551 {
03552    int res = 0;
03553    const struct sockaddr_in *dst = sip_real_dst(p);
03554 
03555    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));
03556 
03557    if (sip_prepare_socket(p) < 0)
03558       return XMIT_ERROR;
03559 
03560    if (p->socket.type == SIP_TRANSPORT_UDP) {
03561       res = sendto(p->socket.fd, data->str, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
03562    } else if (p->socket.tcptls_session) {
03563       res = sip_tcptls_write(p->socket.tcptls_session, data->str, len);
03564    } else {
03565       ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
03566       return XMIT_ERROR;
03567    }
03568 
03569    if (res == -1) {
03570       switch (errno) {
03571       case EBADF:       /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
03572       case EHOSTUNREACH:   /* Host can't be reached */
03573       case ENETDOWN:       /* Inteface down */
03574       case ENETUNREACH: /* Network failure */
03575       case ECONNREFUSED:      /* ICMP port unreachable */ 
03576          res = XMIT_ERROR; /* Don't bother with trying to transmit again */
03577       }
03578    }
03579    if (res != len)
03580       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));
03581 
03582    return res;
03583 }
03584 
03585 /*! \brief Build a Via header for a request */
03586 static void build_via(struct sip_pvt *p)
03587 {
03588    /* Work around buggy UNIDEN UIP200 firmware */
03589    const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
03590 
03591    /* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
03592    snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s:%d;branch=z9hG4bK%08x%s",
03593        get_transport_pvt(p),
03594        ast_inet_ntoa(p->ourip.sin_addr),
03595        ntohs(p->ourip.sin_port), (int) p->branch, rport);
03596 }
03597 
03598 /*! \brief NAT fix - decide which IP address to use for Asterisk server?
03599  *
03600  * Using the localaddr structure built up with localnet statements in sip.conf
03601  * apply it to their address to see if we need to substitute our
03602  * externip or can get away with our internal bindaddr
03603  * 'us' is always overwritten.
03604  */
03605 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p)
03606 {
03607    struct sockaddr_in theirs;
03608    /* Set want_remap to non-zero if we want to remap 'us' to an externally
03609     * reachable IP address and port. This is done if:
03610     * 1. we have a localaddr list (containing 'internal' addresses marked
03611     *    as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
03612     *    and AST_SENSE_ALLOW on 'external' ones);
03613     * 2. either stunaddr or externip is set, so we know what to use as the
03614     *    externally visible address;
03615     * 3. the remote address, 'them', is external;
03616     * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
03617     *    when passed to ast_apply_ha() so it does need to be remapped.
03618     *    This fourth condition is checked later.
03619     */
03620    int want_remap;
03621 
03622    *us = internip;      /* starting guess for the internal address */
03623    /* now ask the system what would it use to talk to 'them' */
03624    ast_ouraddrfor(them, &us->sin_addr);
03625    theirs.sin_addr = *them;
03626 
03627    want_remap = localaddr &&
03628       (externip.sin_addr.s_addr || stunaddr.sin_addr.s_addr) &&
03629       ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
03630 
03631    if (want_remap &&
03632        (!sip_cfg.matchexterniplocally || !ast_apply_ha(localaddr, us)) ) {
03633       /* if we used externhost or stun, see if it is time to refresh the info */
03634       if (externexpire && time(NULL) >= externexpire) {
03635          if (stunaddr.sin_addr.s_addr) {
03636             ast_stun_request(sipsock, &stunaddr, NULL, &externip);
03637          } else {
03638             if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
03639                ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
03640          }
03641          externexpire = time(NULL) + externrefresh;
03642       }
03643       if (externip.sin_addr.s_addr)
03644          *us = externip;
03645       else
03646          ast_log(LOG_WARNING, "stun failed\n");
03647       ast_debug(1, "Target address %s is not local, substituting externip\n", 
03648          ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
03649    } else if (p) {
03650       /* no remapping, but we bind to a specific address, so use it. */
03651       switch (p->socket.type) {
03652       case SIP_TRANSPORT_TCP:
03653          if (sip_tcp_desc.local_address.sin_addr.s_addr) {
03654             *us = sip_tcp_desc.local_address;
03655          } else {
03656             us->sin_port = sip_tcp_desc.local_address.sin_port;
03657          }
03658          break;
03659       case SIP_TRANSPORT_TLS:
03660          if (sip_tls_desc.local_address.sin_addr.s_addr) {
03661             *us = sip_tls_desc.local_address;
03662          } else {
03663             us->sin_port = sip_tls_desc.local_address.sin_port;
03664          }
03665             break;
03666       case SIP_TRANSPORT_UDP:
03667          /* fall through on purpose */
03668       default:
03669          if (bindaddr.sin_addr.s_addr) {
03670             *us = bindaddr;
03671          }
03672       }
03673    } else if (bindaddr.sin_addr.s_addr) {
03674       *us = bindaddr;
03675    }
03676    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));
03677 }
03678 
03679 /*! \brief Append to SIP dialog history with arg list  */
03680 static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
03681 {
03682    char buf[80], *c = buf; /* max history length */
03683    struct sip_history *hist;
03684    int l;
03685 
03686    vsnprintf(buf, sizeof(buf), fmt, ap);
03687    strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
03688    l = strlen(buf) + 1;
03689    if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
03690       return;
03691    if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
03692       ast_free(hist);
03693       return;
03694    }
03695    memcpy(hist->event, buf, l);
03696    if (p->history_entries == MAX_HISTORY_ENTRIES) {
03697       struct sip_history *oldest;
03698       oldest = AST_LIST_REMOVE_HEAD(p->history, list);
03699       p->history_entries--;
03700       ast_free(oldest);
03701    }
03702    AST_LIST_INSERT_TAIL(p->history, hist, list);
03703    p->history_entries++;
03704 }
03705 
03706 /*! \brief Append to SIP dialog history with arg list  */
03707 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03708 {
03709    va_list ap;
03710 
03711    if (!p)
03712       return;
03713 
03714    if (!p->do_history && !recordhistory && !dumphistory)
03715       return;
03716 
03717    va_start(ap, fmt);
03718    append_history_va(p, fmt, ap);
03719    va_end(ap);
03720 
03721    return;
03722 }
03723 
03724 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
03725 static int retrans_pkt(const void *data)
03726 {
03727    struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
03728    int reschedule = DEFAULT_RETRANS;
03729    int xmitres = 0;
03730    
03731    /* Lock channel PVT */
03732    sip_pvt_lock(pkt->owner);
03733 
03734    if (pkt->retrans < MAX_RETRANS) {
03735       pkt->retrans++;
03736       if (!pkt->timer_t1) {   /* Re-schedule using timer_a and timer_t1 */
03737          if (sipdebug)
03738             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);
03739       } else {
03740          int siptimer_a;
03741 
03742          if (sipdebug)
03743             ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
03744          if (!pkt->timer_a)
03745             pkt->timer_a = 2 ;
03746          else
03747             pkt->timer_a = 2 * pkt->timer_a;
03748  
03749          /* For non-invites, a maximum of 4 secs */
03750          siptimer_a = pkt->timer_t1 * pkt->timer_a;   /* Double each time */
03751          if (pkt->method != SIP_INVITE && siptimer_a > 4000)
03752             siptimer_a = 4000;
03753       
03754          /* Reschedule re-transmit */
03755          reschedule = siptimer_a;
03756          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);
03757       } 
03758 
03759       if (sip_debug_test_pvt(pkt->owner)) {
03760          const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
03761          ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
03762             pkt->retrans, sip_nat_mode(pkt->owner),
03763             ast_inet_ntoa(dst->sin_addr),
03764             ntohs(dst->sin_port), pkt->data->str);
03765       }
03766 
03767       append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
03768       xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
03769       sip_pvt_unlock(pkt->owner);
03770       if (xmitres == XMIT_ERROR)
03771          ast_log(LOG_WARNING, "Network error on retransmit in dialog %s\n", pkt->owner->callid);
03772       else 
03773          return  reschedule;
03774    } 
03775    /* Too many retries */
03776    if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
03777       if (pkt->is_fatal || sipdebug)   /* Tell us if it's critical or if we're debugging */
03778          ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s) -- See doc/sip-retransmit.txt.\n",
03779             pkt->owner->callid, pkt->seqno,
03780             pkt->is_fatal ? "Critical" : "Non-critical", pkt->is_resp ? "Response" : "Request");
03781    } else if (pkt->method == SIP_OPTIONS && sipdebug) {
03782          ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s)  -- See doc/sip-retransmit.txt.\n", pkt->owner->callid);
03783 
03784    } 
03785    if (xmitres == XMIT_ERROR) {
03786       ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
03787       append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03788    } else 
03789       append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03790       
03791    pkt->retransid = -1;
03792 
03793    if (pkt->is_fatal) {
03794       while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
03795          sip_pvt_unlock(pkt->owner);   /* SIP_PVT, not channel */
03796          usleep(1);
03797          sip_pvt_lock(pkt->owner);
03798       }
03799 
03800       if (pkt->owner->owner && !pkt->owner->owner->hangupcause) 
03801          pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
03802       
03803       if (pkt->owner->owner) {
03804          sip_alreadygone(pkt->owner);
03805          ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet (see doc/sip-retransmit.txt).\n", pkt->owner->callid);
03806          ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_PROTOCOL_ERROR);
03807          ast_channel_unlock(pkt->owner->owner);
03808       } else {
03809          /* If no channel owner, destroy now */
03810 
03811          /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
03812          if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
03813             pvt_set_needdestroy(pkt->owner, "no response to critical packet");
03814             sip_alreadygone(pkt->owner);
03815             append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
03816          }
03817       }
03818    }
03819 
03820    if (pkt->method == SIP_BYE) {
03821       /* We're not getting answers on SIP BYE's.  Tear down the call anyway. */
03822       if (pkt->owner->owner) 
03823          ast_channel_unlock(pkt->owner->owner);
03824       append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
03825       pvt_set_needdestroy(pkt->owner, "no response to BYE");
03826    }
03827 
03828    /* Remove the packet */
03829    for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
03830       if (cur == pkt) {
03831          UNLINK(cur, pkt->owner->packets, prev);
03832          sip_pvt_unlock(pkt->owner);
03833          if (pkt->owner)
03834             pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03835          if (pkt->data)
03836             ast_free(pkt->data);
03837          pkt->data = NULL;
03838          ast_free(pkt);
03839          return 0;
03840       }
03841    }
03842    /* error case */
03843    ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
03844    sip_pvt_unlock(pkt->owner);
03845    return 0;
03846 }
03847 
03848 /*! \brief Transmit packet with retransmits 
03849    \return 0 on success, -1 on failure to allocate packet 
03850 */
03851 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)
03852 {
03853    struct sip_pkt *pkt = NULL;
03854    int siptimer_a = DEFAULT_RETRANS;
03855    int xmitres = 0;
03856    int respid;
03857 
03858    if (sipmethod == SIP_INVITE) {
03859       /* Note this is a pending invite */
03860       p->pendinginvite = seqno;
03861    }
03862 
03863    /* If the transport is something reliable (TCP or TLS) then don't really send this reliably */
03864    /* I removed the code from retrans_pkt that does the same thing so it doesn't get loaded into the scheduler */
03865    /*! \todo According to the RFC some packets need to be retransmitted even if its TCP, so this needs to get revisited */
03866    if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
03867       xmitres = __sip_xmit(p, data, len); /* Send packet */
03868       if (xmitres == XMIT_ERROR) {  /* Serious network trouble, no need to try again */
03869          append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
03870          return AST_FAILURE;
03871       } else {
03872          return AST_SUCCESS;
03873       }
03874    }
03875 
03876    if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
03877       return AST_FAILURE;
03878    /* copy data, add a terminator and save length */
03879    if (!(pkt->data = ast_str_create(len))) {
03880       ast_free(pkt);
03881       return AST_FAILURE;
03882    }
03883    ast_str_set(&pkt->data, 0, "%s%s", data->str, "\0");
03884    pkt->packetlen = len;
03885    /* copy other parameters from the caller */
03886    pkt->method = sipmethod;
03887    pkt->seqno = seqno;
03888    pkt->is_resp = resp;
03889    pkt->is_fatal = fatal;
03890    pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
03891    pkt->next = p->packets;
03892    p->packets = pkt; /* Add it to the queue */
03893    if (resp) {
03894       /* Parse out the response code */
03895       if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
03896          pkt->response_code = respid;
03897       }
03898    }
03899    pkt->timer_t1 = p->timer_t1;  /* Set SIP timer T1 */
03900    pkt->retransid = -1;
03901    if (pkt->timer_t1)
03902       siptimer_a = pkt->timer_t1 * 2;
03903 
03904    /* Schedule retransmission */
03905    AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
03906    if (sipdebug)
03907       ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id  #%d\n", pkt->retransid);
03908 
03909    xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);   /* Send packet */
03910 
03911    if (xmitres == XMIT_ERROR) {  /* Serious network trouble, no need to try again */
03912       append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03913       ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
03914       AST_SCHED_DEL(sched, pkt->retransid);
03915       p->packets = pkt->next;
03916       pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03917       ast_free(pkt->data);
03918       ast_free(pkt);
03919       return AST_FAILURE;
03920    } else {
03921       return AST_SUCCESS;
03922    }
03923 }
03924 
03925 /*! \brief Kill a SIP dialog (called only by the scheduler)
03926  * The scheduler has a reference to this dialog when p->autokillid != -1,
03927  * and we are called using that reference. So if the event is not
03928  * rescheduled, we need to call dialog_unref().
03929  */
03930 static int __sip_autodestruct(const void *data)
03931 {
03932    struct sip_pvt *p = (struct sip_pvt *)data;
03933 
03934    /* If this is a subscription, tell the phone that we got a timeout */
03935    if (p->subscribed) {
03936       transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);  /* Send last notification */
03937       p->subscribed = NONE;
03938       append_history(p, "Subscribestatus", "timeout");
03939       ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
03940       return 10000;  /* Reschedule this destruction so that we know that it's gone */
03941    }
03942 
03943    /* If there are packets still waiting for delivery, delay the destruction */
03944    if (p->packets) {
03945       if (!p->needdestroy) {
03946          char method_str[31];
03947          ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
03948          append_history(p, "ReliableXmit", "timeout");
03949          if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
03950             if (method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
03951                pvt_set_needdestroy(p, "autodestruct");
03952             }
03953          }
03954          return 10000;
03955       } else {
03956          /* They've had their chance to respond. Time to bail */
03957          __sip_pretend_ack(p);
03958       }
03959    }
03960 
03961    if (p->subscribed == MWI_NOTIFICATION)
03962       if (p->relatedpeer)
03963          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) */
03964 
03965    /* Reset schedule ID */
03966    p->autokillid = -1;
03967 
03968    if (p->owner) {
03969       ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
03970       ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
03971    } else if (p->refer && !p->alreadygone) {
03972       ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
03973       transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
03974       append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
03975       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
03976    } else {
03977       append_history(p, "AutoDestroy", "%s", p->callid);
03978       ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
03979       dialog_unlink_all(p, TRUE, TRUE); /* once it's unlinked and unrefd everywhere, it'll be freed automagically */
03980       /* dialog_unref(p, "unref dialog-- no other matching conditions"); -- unlink all now should finish off the dialog's references and free it. */
03981       /* sip_destroy(p); */      /* Go ahead and destroy dialog. All attempts to recover is done */
03982       /* sip_destroy also absorbs the reference */
03983    }
03984    dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
03985    return 0;
03986 }
03987 
03988 /*! \brief Schedule destruction of SIP dialog */
03989 static void sip_scheddestroy(struct sip_pvt *p, int ms)
03990 {
03991    if (ms < 0) {
03992       if (p->timer_t1 == 0) {
03993          p->timer_t1 = global_t1;   /* Set timer T1 if not set (RFC 3261) */
03994          p->timer_b = global_timer_b;  /* Set timer B if not set (RFC 3261) */
03995       }
03996       ms = p->timer_t1 * 64;
03997    }
03998    if (sip_debug_test_pvt(p))
03999       ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
04000    if (sip_cancel_destroy(p))
04001       ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
04002 
04003    if (p->do_history)
04004       append_history(p, "SchedDestroy", "%d ms", ms);
04005    p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
04006 
04007    if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0)
04008       stop_session_timer(p);
04009 }
04010 
04011 /*! \brief Cancel destruction of SIP dialog.
04012  * Be careful as this also absorbs the reference - if you call it
04013  * from within the scheduler, this might be the last reference.
04014  */
04015 static int sip_cancel_destroy(struct sip_pvt *p)
04016 {
04017    int res = 0;
04018    if (p->autokillid > -1) {
04019       int res3;
04020 
04021       if (!(res3 = ast_sched_del(sched, p->autokillid))) {
04022          append_history(p, "CancelDestroy", "");
04023          p->autokillid = -1;
04024          dialog_unref(p, "dialog unrefd because autokillid is de-sched'd");
04025       }
04026    }
04027    return res;
04028 }
04029 
04030 /*! \brief Acknowledges receipt of a packet and stops retransmission 
04031  * called with p locked*/
04032 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
04033 {
04034    struct sip_pkt *cur, *prev = NULL;
04035    const char *msg = "Not Found";   /* used only for debugging */
04036    int res = FALSE;
04037 
04038    /* If we have an outbound proxy for this dialog, then delete it now since
04039      the rest of the requests in this dialog needs to follow the routing.
04040      If obforcing is set, we will keep the outbound proxy during the whole
04041      dialog, regardless of what the SIP rfc says
04042    */
04043    if (p->outboundproxy && !p->outboundproxy->force){
04044       ref_proxy(p, NULL);
04045    }
04046 
04047    for (cur = p->packets; cur; prev = cur, cur = cur->next) {
04048       if (cur->seqno != seqno || cur->is_resp != resp)
04049          continue;
04050       if (cur->is_resp || cur->method == sipmethod) {
04051          res = TRUE;
04052          msg = "Found";
04053          if (!resp && (seqno == p->pendinginvite)) {
04054             ast_debug(1, "Acked pending invite %d\n", p->pendinginvite);
04055             p->pendinginvite = 0;
04056          }
04057          if (cur->retransid > -1) {
04058             if (sipdebug)
04059                ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
04060          }
04061          /* This odd section is designed to thwart a 
04062           * race condition in the packet scheduler. There are
04063           * two conditions under which deleting the packet from the
04064           * scheduler can fail.
04065           *
04066           * 1. The packet has been removed from the scheduler because retransmission
04067           * is being attempted. The problem is that if the packet is currently attempting
04068           * retransmission and we are at this point in the code, then that MUST mean
04069           * that retrans_pkt is waiting on p's lock. Therefore we will relinquish the
04070           * lock temporarily to allow retransmission.
04071           *
04072           * 2. The packet has reached its maximum number of retransmissions and has
04073           * been permanently removed from the packet scheduler. If this is the case, then
04074           * the packet's retransid will be set to -1. The atomicity of the setting and checking
04075           * of the retransid to -1 is ensured since in both cases p's lock is held.
04076           */
04077          while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
04078             sip_pvt_unlock(p);
04079             usleep(1);
04080             sip_pvt_lock(p);
04081          }
04082          UNLINK(cur, p->packets, prev);
04083          dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
04084          if (cur->data)
04085             ast_free(cur->data);
04086          ast_free(cur);
04087          break;
04088       }
04089    }
04090    ast_debug(1, "Stopping retransmission on '%s' of %s %d: Match %s\n",
04091       p->callid, resp ? "Response" : "Request", seqno, msg);
04092    return res;
04093 }
04094 
04095 /*! \brief Pretend to ack all packets
04096  * called with p locked */
04097 static void __sip_pretend_ack(struct sip_pvt *p)
04098 {
04099    struct sip_pkt *cur = NULL;
04100 
04101    while (p->packets) {
04102       int method;
04103       if (cur == p->packets) {
04104          ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
04105          return;
04106       }
04107       cur = p->packets;
04108       method = (cur->method) ? cur->method : find_sip_method(cur->data->str);
04109       __sip_ack(p, cur->seqno, cur->is_resp, method);
04110    }
04111 }
04112 
04113 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
04114 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
04115 {
04116    struct sip_pkt *cur;
04117    int res = FALSE;
04118 
04119    for (cur = p->packets; cur; cur = cur->next) {
04120       if (cur->seqno == seqno && cur->is_resp == resp &&
04121          (cur->is_resp || method_match(sipmethod, cur->data->str))) {
04122          /* this is our baby */
04123          if (cur->retransid > -1) {
04124             if (sipdebug)
04125                ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
04126          }
04127          AST_SCHED_DEL(sched, cur->retransid);
04128          res = TRUE;
04129          break;
04130       }
04131    }
04132    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");
04133    return res;
04134 }
04135 
04136 
04137 /*! \brief Copy SIP request, parse it */
04138 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
04139 {
04140    copy_request(dst, src);
04141    parse_request(dst);
04142 }
04143 
04144 /*! \brief add a blank line if no body */
04145 static void add_blank(struct sip_request *req)
04146 {
04147    if (!req->lines) {
04148       /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
04149       ast_str_append(&req->data, 0, "\r\n");
04150       req->len = ast_str_strlen(req->data);
04151    }
04152 }
04153 
04154 static int send_provisional_keepalive_full(struct sip_pvt *pvt, int with_sdp)
04155 {
04156    const char *msg = NULL;
04157 
04158    if (!pvt->last_provisional || !strncasecmp(pvt->last_provisional, "100", 3)) {
04159       msg = "183 Session Progress";
04160    }
04161 
04162    if (pvt->invitestate < INV_COMPLETED) {
04163       if (with_sdp) {
04164          transmit_response_with_sdp(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq, XMIT_UNRELIABLE, FALSE);
04165       } else {
04166          transmit_response(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq);
04167       }
04168       return PROVIS_KEEPALIVE_TIMEOUT;
04169    }
04170 
04171    return 0;
04172 }
04173 
04174 static int send_provisional_keepalive(const void *data) {
04175    struct sip_pvt *pvt = (struct sip_pvt *) data;
04176 
04177    return send_provisional_keepalive_full(pvt, 0);
04178 }
04179 
04180 static int send_provisional_keepalive_with_sdp(const void *data) {
04181    struct sip_pvt *pvt = (void *)data;
04182 
04183    return send_provisional_keepalive_full(pvt, 1);
04184 }
04185 
04186 static void update_provisional_keepalive(struct sip_pvt *pvt, int with_sdp)
04187 {
04188    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"));
04189 
04190    pvt->provisional_keepalive_sched_id = ast_sched_add(sched, PROVIS_KEEPALIVE_TIMEOUT,
04191       with_sdp ? send_provisional_keepalive_with_sdp : send_provisional_keepalive, dialog_ref(pvt, "Increment refcount to pass dialog pointer to sched callback"));
04192 }
04193 
04194 /*! \brief Transmit response on SIP request*/
04195 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
04196 {
04197    int res;
04198 
04199    finalize_content(req);
04200    add_blank(req);
04201    if (sip_debug_test_pvt(p)) {
04202       const struct sockaddr_in *dst = sip_real_dst(p);
04203 
04204       ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
04205          reliable ? "Reliably " : "", sip_nat_mode(p),
04206          ast_inet_ntoa(dst->sin_addr),
04207          ntohs(dst->sin_port), req->data->str);
04208    }
04209    if (p->do_history) {
04210       struct sip_request tmp = { .rlPart1 = 0, };
04211       parse_copy(&tmp, req);
04212       append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), 
04213          (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlPart2) : sip_methods[tmp.method].text);
04214       deinit_req(&tmp);
04215    }
04216 
04217    /* If we are sending a final response to an INVITE, stop retransmitting provisional responses */
04218    if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
04219       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"));
04220    }
04221 
04222    res = (reliable) ?
04223        __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
04224       __sip_xmit(p, req->data, req->len);
04225    deinit_req(req);
04226    if (res > 0)
04227       return 0;
04228    return res;
04229 }
04230 
04231 /*! \brief Send SIP Request to the other part of the dialogue */
04232 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
04233 {
04234    int res;
04235 
04236    /* If we have an outbound proxy, reset peer address 
04237       Only do this once.
04238    */
04239    if (p->outboundproxy) {
04240       p->sa = p->outboundproxy->ip;
04241    }
04242 
04243    finalize_content(req);
04244    add_blank(req);
04245    if (sip_debug_test_pvt(p)) {
04246       if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
04247          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);
04248       else
04249          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);
04250    }
04251    if (p->do_history) {
04252       struct sip_request tmp = { .rlPart1 = 0, };
04253       parse_copy(&tmp, req);
04254       append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
04255       deinit_req(&tmp);
04256    }
04257    res = (reliable) ?
04258       __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
04259       __sip_xmit(p, req->data, req->len);
04260    deinit_req(req);
04261    return res;
04262 }
04263 
04264 /*! \brief Query an option on a SIP dialog */
04265 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
04266 {
04267    int res = -1;
04268    enum ast_t38_state state = T38_STATE_UNAVAILABLE;
04269    struct sip_pvt *p = (struct sip_pvt *) chan->tech_pvt;
04270 
04271    switch (option) {
04272    case AST_OPTION_T38_STATE:
04273       /* Make sure we got an ast_t38_state enum passed in */
04274       if (*datalen != sizeof(enum ast_t38_state)) {
04275          ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
04276          return -1;
04277       }
04278 
04279       sip_pvt_lock(p);
04280 
04281       /* 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 */
04282       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
04283          switch (p->t38.state) {
04284          case T38_LOCAL_REINVITE:
04285          case T38_PEER_REINVITE:
04286             state = T38_STATE_NEGOTIATING;
04287             break;
04288          case T38_ENABLED:
04289             state = T38_STATE_NEGOTIATED;
04290             break;
04291          default:
04292             state = T38_STATE_UNKNOWN;
04293          }
04294       }
04295 
04296       sip_pvt_unlock(p);
04297 
04298       *((enum ast_t38_state *) data) = state;
04299       res = 0;
04300 
04301       break;
04302    default:
04303       break;
04304    }
04305 
04306    return res;
04307 }
04308 
04309 /*! \brief Locate closing quote in a string, skipping escaped quotes.
04310  * optionally with a limit on the search.
04311  * start must be past the first quote.
04312  */
04313 static const char *find_closing_quote(const char *start, const char *lim)
04314 {
04315    char last_char = '\0';
04316    const char *s;
04317    for (s = start; *s && s != lim; last_char = *s++) {
04318       if (*s == '"' && last_char != '\\')
04319          break;
04320    }
04321    return s;
04322 }
04323 
04324 /*! \brief Pick out text in brackets from character string
04325    \return pointer to terminated stripped string
04326    \param tmp input string that will be modified
04327    Examples:
04328 \verbatim
04329    "foo" <bar> valid input, returns bar
04330    foo      returns the whole string
04331    < "foo ... >   returns the string between brackets
04332    < "foo...   bogus (missing closing bracket), returns the whole string
04333          XXX maybe should still skip the opening bracket
04334 \endverbatim
04335  */
04336 static char *get_in_brackets(char *tmp)
04337 {
04338    const char *parse = tmp;
04339    char *first_bracket;
04340 
04341    /*
04342     * Skip any quoted text until we find the part in brackets.
04343    * On any error give up and return the full string.
04344    */
04345    while ( (first_bracket = strchr(parse, '<')) ) {
04346       char *first_quote = strchr(parse, '"');
04347 
04348       if (!first_quote || first_quote > first_bracket)
04349          break; /* no need to look at quoted part */
04350       /* the bracket is within quotes, so ignore it */
04351       parse = find_closing_quote(first_quote + 1, NULL);
04352       if (!*parse) { /* not found, return full string ? */
04353          /* XXX or be robust and return in-bracket part ? */
04354          ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
04355          break;
04356       }
04357       parse++;
04358    }
04359    if (first_bracket) {
04360       char *second_bracket = strchr(first_bracket + 1, '>');
04361       if (second_bracket) {
04362          *second_bracket = '\0';
04363          tmp = first_bracket + 1;
04364       } else {
04365          ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
04366       }
04367    }
04368    
04369    return tmp;
04370 }
04371 
04372 /*! \brief * parses a URI in its components.
04373  *
04374  * \note 
04375  * - If scheme is specified, drop it from the top.
04376  * - If a component is not requested, do not split around it.
04377  * - Multiple scheme's can be specified ',' delimited. ex: "sip:,sips:"
04378  *
04379  * This means that if we don't have domain, we cannot split
04380  * name:pass and domain:port.
04381  * It is safe to call with ret_name, pass, domain, port
04382  * pointing all to the same place.
04383  * Init pointers to empty string so we never get NULL dereferencing.
04384  * Overwrites the string.
04385  * return 0 on success, other values on error.
04386  * \verbatim 
04387  * general form we are expecting is sip[s]:username[:password][;parameter]@host[:port][;...] 
04388  * \endverbatim
04389  * 
04390  */
04391 static int parse_uri(char *uri, const char *scheme,
04392    char **ret_name, char **pass, char **domain, char **port, char **options, char **transport)
04393 {
04394    char *name = NULL;
04395    int error = 0;
04396 
04397    /* init field as required */
04398    if (pass)
04399       *pass = "";
04400    if (port)
04401       *port = "";
04402    if (scheme) {
04403       int l;
04404       char *scheme2 = ast_strdupa(scheme);
04405       char *cur = strsep(&scheme2, ",");
04406       for (; !ast_strlen_zero(cur); cur = strsep(&scheme2, ",")) {
04407          l = strlen(cur);
04408          if (!strncasecmp(uri, cur, l)) {
04409             uri += l;
04410             break;
04411          }
04412       }
04413       if (ast_strlen_zero(cur)) {
04414          ast_debug(1, "No supported scheme found in '%s' using the scheme[s] %s\n", uri, scheme);
04415          error = -1;
04416       }
04417    }
04418    if (transport) {
04419       char *t, *type = "";
04420       *transport = "";
04421       if ((t = strstr(uri, "transport="))) {
04422          strsep(&t, "=");
04423          if ((type = strsep(&t, ";"))) {
04424             *transport = type;
04425          }
04426       }
04427    }
04428 
04429    if (!domain) {
04430       /* if we don't want to split around domain, keep everything as a name,
04431        * so we need to do nothing here, except remember why.
04432        */
04433    } else {
04434       /* store the result in a temp. variable to avoid it being
04435        * overwritten if arguments point to the same place.
04436        */
04437       char *c, *dom = "";
04438 
04439       if ((c = strchr(uri, '@')) == NULL) {
04440          /* domain-only URI, according to the SIP RFC. */
04441          dom = uri;
04442          name = "";
04443       } else {
04444          *c++ = '\0';
04445          dom = c;
04446          name = uri;
04447       }
04448 
04449       /* Remove options in domain and name */
04450       dom = strsep(&dom, ";");
04451       name = strsep(&name, ";");
04452 
04453       if (port && (c = strchr(dom, ':'))) { /* Remove :port */
04454          *c++ = '\0';
04455          *port = c;
04456       }
04457       if (pass && (c = strchr(name, ':'))) { /* user:password */
04458          *c++ = '\0';
04459          *pass = c;
04460       }
04461       *domain = dom;
04462    }
04463    if (ret_name)  /* same as for domain, store the result only at the end */
04464       *ret_name = name;
04465    if (options)
04466       *options = uri ? uri : "";
04467 
04468    return error;
04469 }
04470 
04471 /*! \brief Send message with Access-URL header, if this is an HTML URL only! */
04472 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
04473 {
04474    struct sip_pvt *p = chan->tech_pvt;
04475 
04476    if (subclass != AST_HTML_URL)
04477       return -1;
04478 
04479    ast_string_field_build(p, url, "<%s>;mode=active", data);
04480 
04481    if (sip_debug_test_pvt(p))
04482       ast_debug(1, "Send URL %s, state = %d!\n", data, chan->_state);
04483 
04484    switch (chan->_state) {
04485    case AST_STATE_RING:
04486       transmit_response(p, "100 Trying", &p->initreq);
04487       break;
04488    case AST_STATE_RINGING:
04489       transmit_response(p, "180 Ringing", &p->initreq);
04490       break;
04491    case AST_STATE_UP:
04492       if (!p->pendinginvite) {      /* We are up, and have no outstanding invite */
04493          transmit_reinvite_with_sdp(p, FALSE, FALSE);
04494       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
04495          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);   
04496       }  
04497       break;
04498    default:
04499       ast_log(LOG_WARNING, "Don't know how to send URI when state is %d!\n", chan->_state);
04500    }
04501 
04502    return 0;
04503 }
04504 
04505 /*! \brief Deliver SIP call ID for the call */
04506 static const char *sip_get_callid(struct ast_channel *chan)
04507 {
04508    return chan->tech_pvt ? ((struct sip_pvt *) chan->tech_pvt)->callid : "";
04509 }
04510 
04511 /*! \brief Send SIP MESSAGE text within a call
04512    Called from PBX core sendtext() application */
04513 static int sip_sendtext(struct ast_channel *ast, const char *text)
04514 {
04515    struct sip_pvt *p = ast->tech_pvt;
04516    int debug = sip_debug_test_pvt(p);
04517 
04518    if (debug)
04519       ast_verbose("Sending text %s on %s\n", text, ast->name);
04520    if (!p)
04521       return -1;
04522    /* NOT ast_strlen_zero, because a zero-length message is specifically
04523     * allowed by RFC 3428 (See section 10, Examples) */
04524    if (!text)
04525       return 0;
04526    if (debug)
04527       ast_verbose("Really sending text %s on %s\n", text, ast->name);
04528    transmit_message_with_text(p, text);
04529    return 0;   
04530 }
04531 
04532 /*! \brief Update peer object in realtime storage 
04533    If the Asterisk system name is set in asterisk.conf, we will use
04534    that name and store that in the "regserver" field in the sippeers
04535    table to facilitate multi-server setups.
04536 */
04537 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)
04538 {
04539    char port[10];
04540    char ipaddr[INET_ADDRSTRLEN];
04541    char regseconds[20];
04542    char *tablename = NULL;
04543    char str_lastms[20];
04544 
04545    const char *sysname = ast_config_AST_SYSTEM_NAME;
04546    char *syslabel = NULL;
04547 
04548    time_t nowtime = time(NULL) + expirey;
04549    const char *fc = fullcontact ? "fullcontact" : NULL;
04550 
04551    int realtimeregs = ast_check_realtime("sipregs");
04552 
04553    tablename = realtimeregs ? "sipregs" : "sippeers";
04554    
04555 
04556    snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
04557    snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);  /* Expiration time */
04558    ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
04559    snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
04560    
04561    if (ast_strlen_zero(sysname)) /* No system name, disable this */
04562       sysname = NULL;
04563    else if (sip_cfg.rtsave_sysname)
04564       syslabel = "regserver";
04565 
04566    if (fc) {
04567       ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04568          "port", port, "regseconds", regseconds,
04569          deprecated_username ? "username" : "defaultuser", defaultuser,
04570          "useragent", useragent, "lastms", str_lastms,
04571          fc, fullcontact, syslabel, sysname, SENTINEL); /* note fc and syslabel _can_ be NULL */
04572    } else {
04573       ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04574          "port", port, "regseconds", regseconds,
04575          "useragent", useragent, "lastms", str_lastms,
04576          deprecated_username ? "username" : "defaultuser", defaultuser,
04577          syslabel, sysname, SENTINEL); /* note syslabel _can_ be NULL */
04578    }
04579 }
04580 
04581 /*! \brief Automatically add peer extension to dial plan */
04582 static void register_peer_exten(struct sip_peer *peer, int onoff)
04583 {
04584    char multi[256];
04585    char *stringp, *ext, *context;
04586    struct pbx_find_info q = { .stacklen = 0 };
04587 
04588    /* XXX note that global_regcontext is both a global 'enable' flag and
04589     * the name of the global regexten context, if not specified
04590     * individually.
04591     */
04592    if (ast_strlen_zero(global_regcontext))
04593       return;
04594 
04595    ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
04596    stringp = multi;
04597    while ((ext = strsep(&stringp, "&"))) {
04598       if ((context = strchr(ext, '@'))) {
04599          *context++ = '\0';   /* split ext@context */
04600          if (!ast_context_find(context)) {
04601             ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
04602             continue;
04603          }
04604       } else {
04605          context = global_regcontext;
04606       }
04607       if (onoff) {
04608          if (!ast_exists_extension(NULL, context, ext, 1, NULL)) {
04609             ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
04610                 ast_strdup(peer->name), ast_free_ptr, "SIP");
04611          }
04612       } else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
04613          ast_context_remove_extension(context, ext, 1, NULL);
04614       }
04615    }
04616 }
04617 
04618 /*! Destroy mailbox subscriptions */
04619 static void destroy_mailbox(struct sip_mailbox *mailbox)
04620 {
04621    if (mailbox->mailbox)
04622       ast_free(mailbox->mailbox);
04623    if (mailbox->context)
04624       ast_free(mailbox->context);
04625    if (mailbox->event_sub)
04626       ast_event_unsubscribe(mailbox->event_sub);
04627    ast_free(mailbox);
04628 }
04629 
04630 /*! Destroy all peer-related mailbox subscriptions */
04631 static void clear_peer_mailboxes(struct sip_peer *peer)
04632 {
04633    struct sip_mailbox *mailbox;
04634 
04635    while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
04636       destroy_mailbox(mailbox);
04637 }
04638 
04639 static void sip_destroy_peer_fn(void *peer)
04640 {
04641    sip_destroy_peer(peer);
04642 }
04643 
04644 /*! \brief Destroy peer object from memory */
04645 static void sip_destroy_peer(struct sip_peer *peer)
04646 {
04647    ast_debug(3, "Destroying SIP peer %s\n", peer->name);
04648    if (peer->outboundproxy)
04649       ao2_ref(peer->outboundproxy, -1);
04650    peer->outboundproxy = NULL;
04651 
04652    /* Delete it, it needs to disappear */
04653    if (peer->call) {
04654       dialog_unlink_all(peer->call, TRUE, TRUE);
04655       peer->call = dialog_unref(peer->call, "peer->call is being unset");
04656    }
04657    
04658 
04659    if (peer->mwipvt) {  /* We have an active subscription, delete it */
04660       dialog_unlink_all(peer->mwipvt, TRUE, TRUE);
04661       peer->mwipvt = dialog_unref(peer->mwipvt, "unreffing peer->mwipvt");
04662    }
04663    
04664    if (peer->chanvars) {
04665       ast_variables_destroy(peer->chanvars);
04666       peer->chanvars = NULL;
04667    }
04668    
04669    register_peer_exten(peer, FALSE);
04670    ast_free_ha(peer->ha);
04671    if (peer->selfdestruct)
04672       ast_atomic_fetchadd_int(&apeerobjs, -1);
04673    else if (peer->is_realtime) {
04674       ast_atomic_fetchadd_int(&rpeerobjs, -1);
04675       ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
04676    } else
04677       ast_atomic_fetchadd_int(&speerobjs, -1);
04678    clear_realm_authentication(peer->auth);
04679    peer->auth = NULL;
04680    if (peer->dnsmgr)
04681       ast_dnsmgr_release(peer->dnsmgr);
04682    clear_peer_mailboxes(peer);
04683 
04684    if (peer->socket.tcptls_session) {
04685       ao2_ref(peer->socket.tcptls_session, -1);
04686       peer->socket.tcptls_session = NULL;
04687    }
04688 
04689    ast_string_field_free_memory(peer);
04690 }
04691 
04692 /*! \brief Update peer data in database (if used) */
04693 static void update_peer(struct sip_peer *p, int expire)
04694 {
04695    int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
04696    if (sip_cfg.peer_rtupdate &&
04697        (p->is_realtime || rtcachefriends)) {
04698       realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, p->useragent, expire, p->deprecated_username, p->lastms);
04699    }
04700 }
04701 
04702 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *cfg)
04703 {
04704    struct ast_variable *var = NULL;
04705    struct ast_flags flags = {0};
04706    char *cat = NULL;
04707    const char *insecure;
04708    while ((cat = ast_category_browse(cfg, cat))) {
04709       insecure = ast_variable_retrieve(cfg, cat, "insecure");
04710       set_insecure_flags(&flags, insecure, -1);
04711       if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
04712          var = ast_category_root(cfg, cat);
04713          break;
04714       }
04715    }
04716    return var;
04717 }
04718 
04719 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername)
04720 {
04721    struct ast_variable *tmp;
04722    for (tmp = var; tmp; tmp = tmp->next) {
04723       if (!newpeername && !strcasecmp(tmp->name, "name"))
04724          newpeername = tmp->value;
04725    }
04726    return newpeername;
04727 }
04728 
04729 /*! \brief  realtime_peer: Get peer from realtime storage
04730  * Checks the "sippeers" realtime family from extconfig.conf 
04731  * Checks the "sipregs" realtime family from extconfig.conf if it's configured.
04732  * This returns a pointer to a peer and because we use build_peer, we can rest
04733  * assured that the refcount is bumped.
04734 */
04735 static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin, int devstate_only)
04736 {
04737    struct sip_peer *peer;
04738    struct ast_variable *var = NULL;
04739    struct ast_variable *varregs = NULL;
04740    struct ast_variable *tmp;
04741    struct ast_config *peerlist = NULL;
04742    char ipaddr[INET_ADDRSTRLEN];
04743    char portstring[6]; /*up to 5 digits plus null terminator*/
04744    char *cat = NULL;
04745    unsigned short portnum;
04746    int realtimeregs = ast_check_realtime("sipregs");
04747 
04748    /* First check on peer name */
04749    if (newpeername) {
04750       if (realtimeregs)
04751          varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04752 
04753       var = ast_load_realtime("sippeers", "name", newpeername, "host", "dynamic", SENTINEL);
04754       if (!var && sin)
04755          var = ast_load_realtime("sippeers", "name", newpeername, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
04756       if (!var) {
04757          var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04758          /*!\note
04759           * If this one loaded something, then we need to ensure that the host
04760           * field matched.  The only reason why we can't have this as a criteria
04761           * is because we only have the IP address and the host field might be
04762           * set as a name (and the reverse PTR might not match).
04763           */
04764          if (var && sin) {
04765             for (tmp = var; tmp; tmp = tmp->next) {
04766                if (!strcasecmp(tmp->name, "host")) {
04767                   struct hostent *hp;
04768                   struct ast_hostent ahp;
04769                   if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
04770                      /* No match */
04771                      ast_variables_destroy(var);
04772                      var = NULL;
04773                   }
04774                   break;
04775                }
04776             }
04777          }
04778       }
04779    }
04780 
04781    if (!var && sin) {   /* Then check on IP address for dynamic peers */
04782       ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
04783       portnum = ntohs(sin->sin_port);
04784       sprintf(portstring, "%u", portnum);
04785       var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, SENTINEL);  /* First check for fixed IP hosts */
04786       if (var) {
04787          if (realtimeregs) {
04788             newpeername = get_name_from_variable(var, newpeername);
04789             varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04790          }
04791       } else {
04792          if (realtimeregs)
04793             varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, "port", portstring, SENTINEL); /* Then check for registered hosts */
04794          else
04795             var = ast_load_realtime("sippeers", "ipaddr", ipaddr, "port", portstring, SENTINEL); /* Then check for registered hosts */
04796          if (varregs) {
04797             newpeername = get_name_from_variable(varregs, newpeername);
04798             var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04799          }
04800       }
04801       if (!var) { /*We couldn't match on ipaddress and port, so we need to check if port is insecure*/
04802          peerlist = ast_load_realtime_multientry("sippeers", "host", ipaddr, SENTINEL);
04803          if (peerlist) {
04804             var = get_insecure_variable_from_config(peerlist);
04805             if(var) {
04806                if (realtimeregs) {
04807                   newpeername = get_name_from_variable(var, newpeername);
04808                   varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04809                }
04810             } else { /*var wasn't found in the list of "hosts", so try "ipaddr"*/
04811                peerlist = NULL;
04812                cat = NULL;
04813                peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, SENTINEL);
04814                if(peerlist) {
04815                   var = get_insecure_variable_from_config(peerlist);
04816                   if(var) {
04817                      if (realtimeregs) {
04818                         newpeername = get_name_from_variable(var, newpeername);
04819                         varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04820                      }
04821                   }
04822                }
04823             }
04824          } else {
04825             if (realtimeregs) {
04826                peerlist = ast_load_realtime_multientry("sipregs", "ipaddr", ipaddr, SENTINEL);
04827                if (peerlist) {
04828                   varregs = get_insecure_variable_from_config(peerlist);
04829                   if (varregs) {
04830                      newpeername = get_name_from_variable(varregs, newpeername);
04831                      var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04832                   }
04833                }
04834             } else {
04835                peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, SENTINEL);
04836                if (peerlist) {
04837                   var = get_insecure_variable_from_config(peerlist);
04838                   if (var) {
04839                      newpeername = get_name_from_variable(var, newpeername);
04840                      varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04841                   }
04842                }
04843             }
04844          }
04845       }
04846    }
04847 
04848    if (!var) {
04849       if (peerlist)
04850          ast_config_destroy(peerlist);
04851       return NULL;
04852    }
04853 
04854    for (tmp = var; tmp; tmp = tmp->next) {
04855       if (!newpeername && !strcasecmp(tmp->name, "name")) {
04856          newpeername = tmp->value;
04857       }
04858    }
04859    
04860    if (!newpeername) {  /* Did not find peer in realtime */
04861       ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", ipaddr);
04862       if(peerlist)
04863          ast_config_destroy(peerlist);
04864       else
04865          ast_variables_destroy(var);
04866       return NULL;
04867    }
04868 
04869 
04870    /* Peer found in realtime, now build it in memory */
04871    peer = build_peer(newpeername, var, varregs, TRUE, devstate_only);
04872    if (!peer) {
04873       if(peerlist)
04874          ast_config_destroy(peerlist);
04875       else {
04876          ast_variables_destroy(var);
04877          ast_variables_destroy(varregs);
04878       }
04879       return NULL;
04880    }
04881 
04882    ast_debug(3, "-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
04883 
04884    if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && !devstate_only) {
04885       /* Cache peer */
04886       ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
04887       if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
04888          AST_SCHED_REPLACE_UNREF(peer->expire, sched, sip_cfg.rtautoclear * 1000, expire_register, peer,
04889                unref_peer(_data, "remove registration ref"),
04890                unref_peer(peer, "remove registration ref"),
04891                ref_peer(peer, "add registration ref"));
04892       }
04893       ao2_t_link(peers, peer, "link peer into peers table");
04894       if (peer->addr.sin_addr.s_addr) {
04895          ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
04896       }
04897    }
04898    peer->is_realtime = 1;
04899    if (peerlist)
04900       ast_config_destroy(peerlist);
04901    else {
04902       ast_variables_destroy(var);
04903       ast_variables_destroy(varregs);
04904    }
04905 
04906    return peer;
04907 }
04908 
04909 /* Function to assist finding peers by name only */
04910 static int find_by_name(void *obj, void *arg, void *data, int flags)
04911 {
04912    struct sip_peer *search = obj, *match = arg;
04913    int *which_objects = data;
04914 
04915    /* Usernames in SIP uri's are case sensitive. Domains are not */
04916    if (strcmp(search->name, match->name)) {
04917       return 0;
04918    }
04919 
04920    switch (*which_objects) {
04921    case FINDUSERS:
04922       if (!(search->type & SIP_TYPE_USER)) {
04923          return 0;
04924       }
04925       break;
04926    case FINDPEERS:
04927       if (!(search->type & SIP_TYPE_PEER)) {
04928          return 0;
04929       }
04930       break;
04931    case FINDALLDEVICES:
04932       break;
04933    }
04934 
04935    return CMP_MATCH | CMP_STOP;
04936 }
04937 
04938 /*! 
04939  * \brief Locate device by name or ip address 
04940  *
04941  * \param which_objects Define which objects should be matched when doing a lookup
04942  *        by name.  Valid options are FINDUSERS, FINDPEERS, or FINDALLDEVICES.
04943  *        Note that this option is not used at all when doing a lookup by IP.
04944  *
04945  * This is used on find matching device on name or ip/port.
04946  * If the device was declared as type=peer, we don't match on peer name on incoming INVITEs.
04947  *
04948  * \note Avoid using this function in new functions if there is a way to avoid it,
04949  * since it might cause a database lookup.
04950  */
04951 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int which_objects, int devstate_only, int transport)
04952 {
04953    struct sip_peer *p = NULL;
04954    struct sip_peer tmp_peer;
04955 
04956    if (peer) {
04957       ast_copy_string(tmp_peer.name, peer, sizeof(tmp_peer.name));
04958       p = ao2_t_callback_data(peers, OBJ_POINTER, find_by_name, &tmp_peer, &which_objects, "ao2_find in peers table");
04959    } else if (sin) { /* search by addr? */
04960       tmp_peer.addr.sin_addr.s_addr = sin->sin_addr.s_addr;
04961       tmp_peer.addr.sin_port = sin->sin_port;
04962       tmp_peer.flags[0].flags = 0;
04963       tmp_peer.transports = transport;
04964       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); */
04965       if (!p) {
04966          ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
04967          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); */
04968          if (p) {
04969             return p;
04970          }
04971       }
04972    }
04973 
04974    if (!p && (realtime || devstate_only)) {
04975       p = realtime_peer(peer, sin, devstate_only);
04976       if (p) {
04977          switch (which_objects) {
04978          case FINDUSERS:
04979             if (!(p->type & SIP_TYPE_USER)) {
04980                unref_peer(p, "Wrong type of realtime SIP endpoint");
04981                return NULL;
04982             }
04983             break;
04984          case FINDPEERS:
04985             if (!(p->type & SIP_TYPE_PEER)) {
04986                unref_peer(p, "Wrong type of realtime SIP endpoint");
04987                return NULL;
04988             }
04989             break;
04990          case FINDALLDEVICES:
04991             break;
04992          }
04993       }
04994    }
04995 
04996    return p;
04997 }
04998 
04999 /*! \brief Set nat mode on the various data sockets */
05000 static void do_setnat(struct sip_pvt *p, int natflags)
05001 {
05002    const char *mode = natflags ? "On" : "Off";
05003 
05004    if (p->rtp) {
05005       ast_debug(1, "Setting NAT on RTP to %s\n", mode);
05006       ast_rtp_setnat(p->rtp, natflags);
05007    }
05008    if (p->vrtp) {
05009       ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
05010       ast_rtp_setnat(p->vrtp, natflags);
05011    }
05012    if (p->udptl) {
05013       ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
05014       ast_udptl_setnat(p->udptl, natflags);
05015    }
05016    if (p->trtp) {
05017       ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
05018       ast_rtp_setnat(p->trtp, natflags);
05019    }
05020 }
05021 
05022 /*! \brief Change the T38 state on a SIP dialog */
05023 static void change_t38_state(struct sip_pvt *p, int state)
05024 {
05025    int old = p->t38.state;
05026    struct ast_channel *chan = p->owner;
05027    struct ast_control_t38_parameters parameters = { .request_response = 0 };
05028 
05029    /* Don't bother changing if we are already in the state wanted */
05030    if (old == state)
05031       return;
05032 
05033    p->t38.state = state;
05034    ast_debug(2, "T38 state changed to %d on channel %s\n", p->t38.state, chan ? chan->name : "<none>");
05035 
05036    /* If no channel was provided we can't send off a control frame */
05037    if (!chan)
05038       return;
05039 
05040    /* Given the state requested and old state determine what control frame we want to queue up */
05041    switch (state) {
05042    case T38_PEER_REINVITE:
05043       parameters = p->t38.their_parms;
05044       parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05045       parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
05046       ast_udptl_set_tag(p->udptl, "SIP/%s", p->username);
05047       break;
05048    case T38_ENABLED:
05049       parameters = p->t38.their_parms;
05050       parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05051       parameters.request_response = AST_T38_NEGOTIATED;
05052       ast_udptl_set_tag(p->udptl, "SIP/%s", p->username);
05053       break;
05054    case T38_DISABLED:
05055       if (old == T38_ENABLED) {
05056          parameters.request_response = AST_T38_TERMINATED;
05057       } else if (old == T38_LOCAL_REINVITE) {
05058          parameters.request_response = AST_T38_REFUSED;
05059       }
05060       break;
05061    case T38_LOCAL_REINVITE:
05062       /* wait until we get a peer response before responding to local reinvite */
05063       break;
05064    }
05065 
05066    /* Woot we got a message, create a control frame and send it on! */
05067    if (parameters.request_response)
05068       ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
05069 }
05070 
05071 /*! \brief Set the global T38 capabilities on a SIP dialog structure */
05072 static void set_t38_capabilities(struct sip_pvt *p)
05073 {
05074    if (p->udptl) {
05075       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY) {
05076                         ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
05077       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_FEC) {
05078          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
05079       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL) {
05080          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
05081       }
05082    }
05083 }
05084 
05085 static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
05086 {
05087    if (to_sock->tcptls_session) {
05088       ao2_ref(to_sock->tcptls_session, -1);
05089       to_sock->tcptls_session = NULL;
05090    }
05091 
05092    if (from_sock->tcptls_session) {
05093       ao2_ref(from_sock->tcptls_session, +1);
05094    }
05095 
05096    *to_sock = *from_sock;
05097 }
05098 
05099 /*! \brief Create address structure from peer reference.
05100  * This function copies data from peer to the dialog, so we don't have to look up the peer
05101  * again from memory or database during the life time of the dialog.
05102  *
05103  * \return -1 on error, 0 on success.
05104  *
05105  */
05106 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
05107 {
05108 
05109    /* this checks that the dialog is contacting the peer on a valid
05110     * transport type based on the peers transport configuration,
05111     * otherwise, this function bails out */
05112    if (dialog->socket.type && check_request_transport(peer, dialog))
05113       return -1;
05114    copy_socket_data(&dialog->socket, &peer->socket);
05115 
05116    if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
05117        (!peer->maxms || ((peer->lastms >= 0)  && (peer->lastms <= peer->maxms)))) {
05118       dialog->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
05119       dialog->recv = dialog->sa;
05120    } else 
05121       return -1;
05122 
05123    ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
05124    ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
05125    dialog->capability = peer->capability;
05126    if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) &&
05127          (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
05128             !(dialog->capability & AST_FORMAT_VIDEO_MASK)) &&
05129          dialog->vrtp) {
05130       ast_rtp_destroy(dialog->vrtp);
05131       dialog->vrtp = NULL;
05132    }
05133    if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT) && dialog->trtp) {
05134       ast_rtp_destroy(dialog->trtp);
05135       dialog->trtp = NULL;
05136    }
05137    dialog->prefs = peer->prefs;
05138    if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
05139       /* t38pt_udptl was enabled in the peer and not in [general] */
05140       if (dialog->udptl || (!dialog->udptl && (dialog->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr)))) {
05141          dialog->t38_maxdatagram = peer->t38_maxdatagram;
05142          set_t38_capabilities(dialog);
05143       } else {
05144          /* It is impossible to support T38 without udptl */
05145          ast_debug(1, "UDPTL creation failed on dialog.\n");
05146          ast_clear_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT);
05147       }
05148    } else if (dialog->udptl) {
05149       ast_udptl_destroy(dialog->udptl);
05150       dialog->udptl = NULL;
05151    }
05152    do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
05153 
05154    if (dialog->rtp) { /* Audio */
05155       ast_rtp_setdtmf(dialog->rtp, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
05156       ast_rtp_setdtmfcompensate(dialog->rtp, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
05157       ast_rtp_set_rtptimeout(dialog->rtp, peer->rtptimeout);
05158       ast_rtp_set_rtpholdtimeout(dialog->rtp, peer->rtpholdtimeout);
05159       ast_rtp_set_rtpkeepalive(dialog->rtp, peer->rtpkeepalive);
05160       /* Set Frame packetization */
05161       ast_rtp_codec_setpref(dialog->rtp, &dialog->prefs);
05162       dialog->autoframing = peer->autoframing;
05163    }
05164    if (dialog->vrtp) { /* Video */
05165       ast_rtp_setdtmf(dialog->vrtp, 0);
05166       ast_rtp_setdtmfcompensate(dialog->vrtp, 0);
05167       ast_rtp_set_rtptimeout(dialog->vrtp, peer->rtptimeout);
05168       ast_rtp_set_rtpholdtimeout(dialog->vrtp, peer->rtpholdtimeout);
05169       ast_rtp_set_rtpkeepalive(dialog->vrtp, peer->rtpkeepalive);
05170    }
05171    if (dialog->trtp) { /* Realtime text */
05172       ast_rtp_setdtmf(dialog->trtp, 0);
05173       ast_rtp_setdtmfcompensate(dialog->trtp, 0);
05174       ast_rtp_set_rtptimeout(dialog->trtp, peer->rtptimeout);
05175       ast_rtp_set_rtpholdtimeout(dialog->trtp, peer->rtpholdtimeout);
05176       ast_rtp_set_rtpkeepalive(dialog->trtp, peer->rtpkeepalive);
05177    }
05178 
05179    ast_string_field_set(dialog, peername, peer->name);
05180    ast_string_field_set(dialog, authname, peer->username);
05181    ast_string_field_set(dialog, username, peer->username);
05182    ast_string_field_set(dialog, peersecret, peer->secret);
05183    ast_string_field_set(dialog, peermd5secret, peer->md5secret);
05184    ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
05185    ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
05186    ast_string_field_set(dialog, tohost, peer->tohost);
05187    ast_string_field_set(dialog, fullcontact, peer->fullcontact);
05188    ast_string_field_set(dialog, context, peer->context);
05189    ast_string_field_set(dialog, parkinglot, peer->parkinglot);
05190    ref_proxy(dialog, obproxy_get(dialog, peer));
05191    dialog->callgroup = peer->callgroup;
05192    dialog->pickupgroup = peer->pickupgroup;
05193    dialog->allowtransfer = peer->allowtransfer;
05194    dialog->jointnoncodeccapability = dialog->noncodeccapability;
05195    dialog->rtptimeout = peer->rtptimeout;
05196    dialog->peerauth = peer->auth;
05197    dialog->maxcallbitrate = peer->maxcallbitrate;
05198    if (ast_strlen_zero(dialog->tohost))
05199       ast_string_field_set(dialog, tohost, ast_inet_ntoa(dialog->sa.sin_addr));
05200    if (!ast_strlen_zero(peer->fromdomain)) {
05201       ast_string_field_set(dialog, fromdomain, peer->fromdomain);
05202       if (!dialog->initreq.headers) {
05203          char *c;
05204          char *tmpcall = ast_strdupa(dialog->callid);
05205          /* this sure looks to me like we are going to change the callid on this dialog!! */
05206          c = strchr(tmpcall, '@');
05207          if (c) {
05208             *c = '\0';
05209             ao2_t_unlink(dialogs, dialog, "About to change the callid -- remove the old name");
05210             ast_string_field_build(dialog, callid, "%s@%s", tmpcall, peer->fromdomain);
05211             ao2_t_link(dialogs, dialog, "New dialog callid -- inserted back into table");
05212          }
05213       }
05214    }
05215    if (!ast_strlen_zero(peer->fromuser)) 
05216       ast_string_field_set(dialog, fromuser, peer->fromuser);
05217    if (!ast_strlen_zero(peer->language))
05218       ast_string_field_set(dialog, language, peer->language);
05219    /* Set timer T1 to RTT for this peer (if known by qualify=) */
05220    /* Minimum is settable or default to 100 ms */
05221    /* If there is a maxms and lastms from a qualify use that over a manual T1
05222       value. Otherwise, use the peer's T1 value. */
05223    if (peer->maxms && peer->lastms)
05224       dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
05225    else
05226       dialog->timer_t1 = peer->timer_t1;
05227 
05228    /* Set timer B to control transaction timeouts, the peer setting is the default and overrides
05229       the known timer */
05230    if (peer->timer_b)
05231       dialog->timer_b = peer->timer_b;
05232    else
05233       dialog->timer_b = 64 * dialog->timer_t1;
05234 
05235    if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
05236        (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
05237       dialog->noncodeccapability |= AST_RTP_DTMF;
05238    else
05239       dialog->noncodeccapability &= ~AST_RTP_DTMF;
05240    if (peer->call_limit)
05241       ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
05242    if (!dialog->portinuri)
05243       dialog->portinuri = peer->portinuri;
05244    
05245    dialog->chanvars = copy_vars(peer->chanvars);
05246 
05247    return 0;
05248 }
05249 
05250 /*! \brief create address structure from device name
05251  *      Or, if peer not found, find it in the global DNS 
05252  *      returns TRUE (-1) on failure, FALSE on success */
05253 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog)
05254 {
05255    struct hostent *hp;
05256    struct ast_hostent ahp;
05257    struct sip_peer *peer;
05258    char *port;
05259    int portno = 0;
05260    char host[MAXHOSTNAMELEN], *hostn;
05261    char peername[256];
05262    int srv_ret = 0;
05263 
05264    ast_copy_string(peername, opeer, sizeof(peername));
05265    port = strchr(peername, ':');
05266    if (port) {
05267       *port++ = '\0';
05268       dialog->portinuri = 1;
05269    }
05270    dialog->sa.sin_family = AF_INET;
05271    dialog->timer_t1 = global_t1; /* Default SIP retransmission timer T1 (RFC 3261) */
05272    dialog->timer_b = global_timer_b; /* Default SIP transaction timer B (RFC 3261) */
05273    peer = find_peer(peername, NULL, TRUE, FINDPEERS, FALSE, 0);
05274 
05275    if (peer) {
05276       int res;
05277       if (newdialog) {
05278          set_socket_transport(&dialog->socket, 0);
05279       }
05280       res = create_addr_from_peer(dialog, peer);
05281       if (!ast_strlen_zero(port)) {
05282          if ((portno = atoi(port))) {
05283             dialog->sa.sin_port = dialog->recv.sin_port = htons(portno);
05284          }
05285       }
05286       unref_peer(peer, "create_addr: unref peer from find_peer hashtab lookup");
05287       return res;
05288    }
05289 
05290    do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
05291 
05292    ast_string_field_set(dialog, tohost, peername);
05293 
05294    /* Get the outbound proxy information */
05295    ref_proxy(dialog, obproxy_get(dialog, NULL));
05296 
05297    if (sin) {
05298       /* This address should be updated using dnsmgr */
05299       memcpy(&dialog->sa.sin_addr, &sin->sin_addr, sizeof(dialog->sa.sin_addr));
05300       if (!sin->sin_port) {
05301          portno = port_str2int(port, (dialog->socket.type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
05302       } else {
05303          portno = ntohs(sin->sin_port);
05304       }
05305    } else {
05306 
05307       /* Let's see if we can find the host in DNS. First try DNS SRV records,
05308          then hostname lookup */
05309       /*! \todo Fix this function. When we ask for SRV, we should check all transports 
05310            In the future, we should first check NAPTR to find out transport preference
05311        */
05312       hostn = peername;
05313       /* Section 4.2 of RFC 3263 specifies that if a port number is specified, then
05314        * an A record lookup should be used instead of SRV.
05315        */
05316       if (!port && sip_cfg.srvlookup) {
05317          char service[MAXHOSTNAMELEN];
05318          int tportno;
05319    
05320          snprintf(service, sizeof(service), "_sip._%s.%s", get_transport(dialog->socket.type), peername);
05321          srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
05322          if (srv_ret > 0) {
05323             hostn = host;
05324             portno = tportno;
05325          }
05326       }
05327       if (!portno)
05328          portno = port_str2int(port, (dialog->socket.type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
05329       hp = ast_gethostbyname(hostn, &ahp);
05330       if (!hp) {
05331          ast_log(LOG_WARNING, "No such host: %s\n", peername);
05332          return -1;
05333       }
05334       memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
05335    }
05336 
05337    if (!dialog->socket.type)
05338       set_socket_transport(&dialog->socket, SIP_TRANSPORT_UDP);
05339    if (!dialog->socket.port)
05340       dialog->socket.port = bindaddr.sin_port;
05341    dialog->sa.sin_port = htons(portno);
05342    dialog->recv = dialog->sa;
05343    return 0;
05344 }
05345 
05346 /*! \brief Scheduled congestion on a call.
05347  * Only called by the scheduler, must return the reference when done.
05348  */
05349 static int auto_congest(const void *arg)
05350 {
05351    struct sip_pvt *p = (struct sip_pvt *)arg;
05352 
05353    sip_pvt_lock(p);
05354    p->initid = -1;   /* event gone, will not be rescheduled */
05355    if (p->owner) {
05356       /* XXX fails on possible deadlock */
05357       if (!ast_channel_trylock(p->owner)) {
05358          append_history(p, "Cong", "Auto-congesting (timer)");
05359          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
05360          ast_channel_unlock(p->owner);
05361       }
05362 
05363       /* Give the channel a chance to act before we proceed with destruction */
05364       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05365    }
05366    sip_pvt_unlock(p);
05367    dialog_unref(p, "unreffing arg passed into auto_congest callback (p->initid)");
05368    return 0;
05369 }
05370 
05371 
05372 /*! \brief Initiate SIP call from PBX 
05373  *      used from the dial() application      */
05374 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
05375 {
05376    int res;
05377    struct sip_pvt *p = ast->tech_pvt;  /* chan is locked, so the reference cannot go away */
05378    struct varshead *headp;
05379    struct ast_var_t *current;
05380    const char *referer = NULL;   /* SIP referrer */
05381 
05382    if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
05383       ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
05384       return -1;
05385    }
05386 
05387    /* Check whether there is vxml_url, distinctive ring variables */
05388    headp=&ast->varshead;
05389    AST_LIST_TRAVERSE(headp, current, entries) {
05390       /* Check whether there is a VXML_URL variable */
05391       if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
05392          p->options->vxml_url = ast_var_value(current);
05393       } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
05394          p->options->uri_options = ast_var_value(current);
05395       } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
05396          /* Check whether there is a variable with a name starting with SIPADDHEADER */
05397          p->options->addsipheaders = 1;
05398       } else if (!strcasecmp(ast_var_name(current), "SIPFROMDOMAIN")) {
05399          ast_string_field_set(p, fromdomain, ast_var_value(current));
05400       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
05401          /* This is a transfered call */
05402          p->options->transfer = 1;
05403       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
05404          /* This is the referrer */
05405          referer = ast_var_value(current);
05406       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
05407          /* We're replacing a call. */
05408          p->options->replaces = ast_var_value(current);
05409       }
05410    }
05411 
05412    res = 0;
05413    ast_set_flag(&p->flags[0], SIP_OUTGOING);
05414 
05415    /* T.38 re-INVITE FAX detection should never be done for outgoing calls,
05416     * so ensure it is disabled.
05417     */
05418    ast_clear_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38);
05419 
05420    if (p->options->transfer) {
05421       char buf[SIPBUFSIZE/2];
05422 
05423       if (referer) {
05424          if (sipdebug)
05425             ast_debug(3, "Call for %s transfered by %s\n", p->username, referer);
05426          snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
05427       } else 
05428          snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
05429       ast_string_field_set(p, cid_name, buf);
05430    } 
05431    ast_debug(1, "Outgoing Call for %s\n", p->username);
05432 
05433    res = update_call_counter(p, INC_CALL_RINGING);
05434 
05435    if (res == -1) {
05436       ast->hangupcause = AST_CAUSE_USER_BUSY;
05437       return res;
05438    }
05439    p->callingpres = ast->cid.cid_pres;
05440    p->jointcapability = ast_translate_available_formats(p->capability, p->prefcodec);
05441    p->jointnoncodeccapability = p->noncodeccapability;
05442 
05443    /* If there are no audio formats left to offer, punt */
05444    if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
05445       ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
05446       res = -1;
05447    } else {
05448       int xmitres;
05449 
05450       xmitres = transmit_invite(p, SIP_INVITE, 1, 2);
05451       if (xmitres == XMIT_ERROR)
05452          return -1;
05453       p->invitestate = INV_CALLING;
05454    
05455       /* Initialize auto-congest time */
05456       AST_SCHED_REPLACE_UNREF(p->initid, sched, p->timer_b, auto_congest, p, 
05457                         dialog_unref(_data, "dialog ptr dec when SCHED_REPLACE del op succeeded"), 
05458                         dialog_unref(p, "dialog ptr dec when SCHED_REPLACE add failed"),
05459                         dialog_ref(p, "dialog ptr inc when SCHED_REPLACE add succeeded") );
05460    }
05461    return res;
05462 }
05463 
05464 /*! \brief Destroy registry object
05465    Objects created with the register= statement in static configuration */
05466 static void sip_registry_destroy(struct sip_registry *reg)
05467 {
05468    /* Really delete */
05469    ast_debug(3, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
05470 
05471    if (reg->call) {
05472       /* Clear registry before destroying to ensure
05473          we don't get reentered trying to grab the registry lock */
05474       reg->call->registry = registry_unref(reg->call->registry, "destroy reg->call->registry");
05475       ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
05476       dialog_unlink_all(reg->call, TRUE, TRUE);
05477       reg->call = dialog_unref(reg->call, "unref reg->call");
05478       /* reg->call = sip_destroy(reg->call); */
05479    }
05480    AST_SCHED_DEL(sched, reg->expire);  
05481    AST_SCHED_DEL(sched, reg->timeout);
05482    
05483    ast_string_field_free_memory(reg);
05484    ast_atomic_fetchadd_int(&regobjs, -1);
05485    ast_dnsmgr_release(reg->dnsmgr);
05486    ast_free(reg);
05487 }
05488 
05489 /*! \brief Destroy MWI subscription object */
05490 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi)
05491 {
05492    if (mwi->call) {
05493       mwi->call->mwi = NULL;
05494       sip_destroy(mwi->call);
05495    }
05496    
05497    AST_SCHED_DEL(sched, mwi->resub);
05498    ast_string_field_free_memory(mwi);
05499    ast_dnsmgr_release(mwi->dnsmgr);
05500    ast_free(mwi);
05501 }
05502 
05503 /*! \brief Execute destruction of SIP dialog structure, release memory */
05504 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
05505 {
05506    struct sip_request *req;
05507 
05508    if (p->stimer) {
05509       ast_free(p->stimer);
05510       p->stimer = NULL;
05511    }
05512 
05513    if (sip_debug_test_pvt(p))
05514       ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
05515 
05516    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05517       update_call_counter(p, DEC_CALL_LIMIT);
05518       ast_debug(2, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
05519    }
05520 
05521    /* Unlink us from the owner if we have one */
05522    if (p->owner) {
05523       if (lockowner)
05524          ast_channel_lock(p->owner);
05525       if (option_debug)
05526          ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
05527       p->owner->tech_pvt = NULL;
05528       /* Make sure that the channel knows its backend is going away */
05529       p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
05530       if (lockowner)
05531          ast_channel_unlock(p->owner);
05532       /* Give the channel a chance to react before deallocation */
05533       usleep(1);
05534    }
05535 
05536    /* Remove link from peer to subscription of MWI */
05537    if (p->relatedpeer && p->relatedpeer->mwipvt)
05538       p->relatedpeer->mwipvt = dialog_unref(p->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
05539    if (p->relatedpeer && p->relatedpeer->call == p)
05540       p->relatedpeer->call = dialog_unref(p->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
05541    
05542    if (p->relatedpeer)
05543       p->relatedpeer = unref_peer(p->relatedpeer,"unsetting a dialog relatedpeer field in sip_destroy");
05544    
05545    if (p->registry) {
05546       if (p->registry->call == p)
05547          p->registry->call = dialog_unref(p->registry->call, "nulling out the registry's call dialog field in unlink_all");
05548       p->registry = registry_unref(p->registry, "delete p->registry");
05549    }
05550    
05551    if (p->mwi) {
05552       p->mwi->call = NULL;
05553    }
05554 
05555    if (dumphistory)
05556       sip_dump_history(p);
05557 
05558    if (p->options)
05559       ast_free(p->options);
05560 
05561    if (p->notify_headers) {
05562       ast_variables_destroy(p->notify_headers);
05563       p->notify_headers = NULL;
05564    }
05565    if (p->rtp) {
05566       ast_rtp_destroy(p->rtp);
05567    }
05568    if (p->vrtp) {
05569       ast_rtp_destroy(p->vrtp);
05570    }
05571    if (p->trtp) {
05572       while (ast_rtp_get_bridged(p->trtp))
05573          usleep(1);
05574       ast_rtp_destroy(p->trtp);
05575    }
05576    if (p->udptl)
05577       ast_udptl_destroy(p->udptl);
05578    if (p->refer)
05579       ast_free(p->refer);
05580    if (p->route) {
05581       free_old_route(p->route);
05582       p->route = NULL;
05583    }
05584    deinit_req(&p->initreq);
05585 
05586    /* Destroy Session-Timers if allocated */
05587    if (p->stimer) {
05588       p->stimer->quit_flag = 1;
05589       if (p->stimer->st_active == TRUE && p->stimer->st_schedid > -1) {
05590          AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
05591                dialog_unref(p, "removing session timer ref"));
05592       }
05593       ast_free(p->stimer);
05594       p->stimer = NULL;
05595    }
05596 
05597    /* Clear history */
05598    if (p->history) {
05599       struct sip_history *hist;
05600       while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
05601          ast_free(hist);
05602          p->history_entries--;
05603       }
05604       ast_free(p->history);
05605       p->history = NULL;
05606    }
05607 
05608    while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
05609       ast_free(req);
05610    }
05611 
05612    if (p->chanvars) {
05613       ast_variables_destroy(p->chanvars);
05614       p->chanvars = NULL;
05615    }
05616 
05617    ast_string_field_free_memory(p);
05618 
05619    if (p->socket.tcptls_session) {
05620       ao2_ref(p->socket.tcptls_session, -1);
05621       p->socket.tcptls_session = NULL;
05622    }
05623 }
05624 
05625 /*! \brief  update_call_counter: Handle call_limit for SIP devices
05626  * Setting a call-limit will cause calls above the limit not to be accepted.
05627  *
05628  * Remember that for a type=friend, there's one limit for the user and
05629  * another for the peer, not a combined call limit.
05630  * This will cause unexpected behaviour in subscriptions, since a "friend"
05631  * is *two* devices in Asterisk, not one.
05632  *
05633  * Thought: For realtime, we should probably update storage with inuse counter... 
05634  *
05635  * \return 0 if call is ok (no call limit, below threshold)
05636  * -1 on rejection of call
05637  *    
05638  */
05639 static int update_call_counter(struct sip_pvt *fup, int event)
05640 {
05641    char name[256];
05642    int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
05643    int outgoing = fup->outgoing_call;
05644    struct sip_peer *p = NULL;
05645 
05646    ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
05647 
05648 
05649    /* Test if we need to check call limits, in order to avoid 
05650       realtime lookups if we do not need it */
05651    if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
05652       return 0;
05653 
05654    ast_copy_string(name, fup->username, sizeof(name));
05655 
05656    /* Check the list of devices */
05657    if ((p = find_peer(ast_strlen_zero(fup->peername) ? name : fup->peername, NULL, TRUE, FINDALLDEVICES, FALSE, 0))) { 
05658       inuse = &p->inUse;
05659       call_limit = &p->call_limit;
05660       inringing = &p->inRinging;
05661       ast_copy_string(name, fup->peername, sizeof(name));
05662    }
05663    if (!p) {
05664       ast_debug(2, "%s is not a local device, no call limit\n", name);
05665       return 0;
05666    }
05667 
05668    switch(event) {
05669    /* incoming and outgoing affects the inUse counter */
05670    case DEC_CALL_LIMIT:
05671       /* Decrement inuse count if applicable */
05672       if (inuse) {
05673          sip_pvt_lock(fup);
05674          ao2_lock(p);
05675          if (*inuse > 0) {
05676             if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
05677                (*inuse)--;
05678                ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
05679             }
05680          } else {
05681             *inuse = 0;
05682          }
05683          ao2_unlock(p);
05684          sip_pvt_unlock(fup);
05685       }
05686 
05687       /* Decrement ringing count if applicable */
05688       if (inringing) {
05689          sip_pvt_lock(fup);
05690          ao2_lock(p);
05691          if (*inringing > 0) {
05692             if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05693                (*inringing)--;
05694                ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
05695             }
05696          } else {
05697             *inringing = 0;
05698          }
05699          ao2_unlock(p);
05700          sip_pvt_unlock(fup);
05701       }
05702 
05703       /* Decrement onhold count if applicable */
05704       sip_pvt_lock(fup);
05705       ao2_lock(p);
05706       if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && sip_cfg.notifyhold) {
05707          ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
05708          ao2_unlock(p);
05709          sip_pvt_unlock(fup);
05710          sip_peer_hold(fup, FALSE);
05711       } else {
05712          ao2_unlock(p);
05713          sip_pvt_unlock(fup);
05714       }
05715       if (sipdebug)
05716          ast_debug(2, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
05717       break;
05718 
05719    case INC_CALL_RINGING:
05720    case INC_CALL_LIMIT:
05721       /* If call limit is active and we have reached the limit, reject the call */
05722       if (*call_limit > 0 ) {
05723          if (*inuse >= *call_limit) {
05724             ast_log(LOG_NOTICE, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
05725             unref_peer(p, "update_call_counter: unref peer p, call limit exceeded");
05726             return -1; 
05727          }
05728       }
05729       if (inringing && (event == INC_CALL_RINGING)) {
05730          sip_pvt_lock(fup);
05731          ao2_lock(p);
05732          if (!ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05733             (*inringing)++;
05734             ast_set_flag(&fup->flags[0], SIP_INC_RINGING);
05735          }
05736          ao2_unlock(p);
05737          sip_pvt_unlock(fup);
05738       }
05739       if (inuse) {
05740          sip_pvt_lock(fup);
05741          ao2_lock(p);
05742          if (!ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
05743             (*inuse)++;
05744             ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
05745          }
05746          ao2_unlock(p);
05747          sip_pvt_unlock(fup);
05748       }
05749       if (sipdebug) {
05750          ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", "peer", name, *inuse, *call_limit);
05751       }
05752       break;
05753 
05754    case DEC_CALL_RINGING:
05755       if (inringing) {
05756          sip_pvt_lock(fup);
05757          ao2_lock(p);
05758          if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05759             if (*inringing > 0) {
05760                (*inringing)--;
05761             }
05762             ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
05763          }
05764          ao2_unlock(p);
05765          sip_pvt_unlock(fup);
05766       }
05767       break;
05768 
05769    default:
05770       ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
05771    }
05772 
05773    if (p) {
05774       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", p->name);
05775       unref_peer(p, "update_call_counter: unref_peer from call counter");
05776    } 
05777    return 0;
05778 }
05779 
05780 
05781 static void sip_destroy_fn(void *p)
05782 {
05783    sip_destroy(p);
05784 }
05785 
05786 /*! \brief Destroy SIP call structure.
05787  * Make it return NULL so the caller can do things like
05788  * foo = sip_destroy(foo);
05789  * and reduce the chance of bugs due to dangling pointers.
05790  */
05791 static struct sip_pvt * sip_destroy(struct sip_pvt *p)
05792 {
05793    ast_debug(3, "Destroying SIP dialog %s\n", p->callid);
05794    __sip_destroy(p, TRUE, TRUE);
05795    return NULL;
05796 }
05797 
05798 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
05799 static int hangup_sip2cause(int cause)
05800 {
05801    /* Possible values taken from causes.h */
05802 
05803    switch(cause) {
05804       case 401:   /* Unauthorized */
05805          return AST_CAUSE_CALL_REJECTED;
05806       case 403:   /* Not found */
05807          return AST_CAUSE_CALL_REJECTED;
05808       case 404:   /* Not found */
05809          return AST_CAUSE_UNALLOCATED;
05810       case 405:   /* Method not allowed */
05811          return AST_CAUSE_INTERWORKING;
05812       case 407:   /* Proxy authentication required */
05813          return AST_CAUSE_CALL_REJECTED;
05814       case 408:   /* No reaction */
05815          return AST_CAUSE_NO_USER_RESPONSE;
05816       case 409:   /* Conflict */
05817          return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
05818       case 410:   /* Gone */
05819          return AST_CAUSE_NUMBER_CHANGED;
05820       case 411:   /* Length required */
05821          return AST_CAUSE_INTERWORKING;
05822       case 413:   /* Request entity too large */
05823          return AST_CAUSE_INTERWORKING;
05824       case 414:   /* Request URI too large */
05825          return AST_CAUSE_INTERWORKING;
05826       case 415:   /* Unsupported media type */
05827          return AST_CAUSE_INTERWORKING;
05828       case 420:   /* Bad extension */
05829          return AST_CAUSE_NO_ROUTE_DESTINATION;
05830       case 480:   /* No answer */
05831          return AST_CAUSE_NO_ANSWER;
05832       case 481:   /* No answer */
05833          return AST_CAUSE_INTERWORKING;
05834       case 482:   /* Loop detected */
05835          return AST_CAUSE_INTERWORKING;
05836       case 483:   /* Too many hops */
05837          return AST_CAUSE_NO_ANSWER;
05838       case 484:   /* Address incomplete */
05839          return AST_CAUSE_INVALID_NUMBER_FORMAT;
05840       case 485:   /* Ambiguous */
05841          return AST_CAUSE_UNALLOCATED;
05842       case 486:   /* Busy everywhere */
05843          return AST_CAUSE_BUSY;
05844       case 487:   /* Request terminated */
05845          return AST_CAUSE_INTERWORKING;
05846       case 488:   /* No codecs approved */
05847          return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05848       case 491:   /* Request pending */
05849          return AST_CAUSE_INTERWORKING;
05850       case 493:   /* Undecipherable */
05851          return AST_CAUSE_INTERWORKING;
05852       case 500:   /* Server internal failure */
05853          return AST_CAUSE_FAILURE;
05854       case 501:   /* Call rejected */
05855          return AST_CAUSE_FACILITY_REJECTED;
05856       case 502:   
05857          return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
05858       case 503:   /* Service unavailable */
05859          return AST_CAUSE_CONGESTION;
05860       case 504:   /* Gateway timeout */
05861          return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
05862       case 505:   /* SIP version not supported */
05863          return AST_CAUSE_INTERWORKING;
05864       case 600:   /* Busy everywhere */
05865          return AST_CAUSE_USER_BUSY;
05866       case 603:   /* Decline */
05867          return AST_CAUSE_CALL_REJECTED;
05868       case 604:   /* Does not exist anywhere */
05869          return AST_CAUSE_UNALLOCATED;
05870       case 606:   /* Not acceptable */
05871          return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05872       default:
05873          return AST_CAUSE_NORMAL;
05874    }
05875    /* Never reached */
05876    return 0;
05877 }
05878 
05879 /*! \brief Convert Asterisk hangup causes to SIP codes 
05880 \verbatim
05881  Possible values from causes.h
05882         AST_CAUSE_NOTDEFINED    AST_CAUSE_NORMAL        AST_CAUSE_BUSY
05883         AST_CAUSE_FAILURE       AST_CAUSE_CONGESTION    AST_CAUSE_UNALLOCATED
05884 
05885    In addition to these, a lot of PRI codes is defined in causes.h 
05886    ...should we take care of them too ?
05887    
05888    Quote RFC 3398
05889 
05890    ISUP Cause value                        SIP response
05891    ----------------                        ------------
05892    1  unallocated number                   404 Not Found
05893    2  no route to network                  404 Not found
05894    3  no route to destination              404 Not found
05895    16 normal call clearing                 --- (*)
05896    17 user busy                            486 Busy here
05897    18 no user responding                   408 Request Timeout
05898    19 no answer from the user              480 Temporarily unavailable
05899    20 subscriber absent                    480 Temporarily unavailable
05900    21 call rejected                        403 Forbidden (+)
05901    22 number changed (w/o diagnostic)      410 Gone
05902    22 number changed (w/ diagnostic)       301 Moved Permanently
05903    23 redirection to new destination       410 Gone
05904    26 non-selected user clearing           404 Not Found (=)
05905    27 destination out of order             502 Bad Gateway
05906    28 address incomplete                   484 Address incomplete
05907    29 facility rejected                    501 Not implemented
05908    31 normal unspecified                   480 Temporarily unavailable
05909 \endverbatim
05910 */
05911 static const char *hangup_cause2sip(int cause)
05912 {
05913    switch (cause) {
05914       case AST_CAUSE_UNALLOCATED:      /* 1 */
05915       case AST_CAUSE_NO_ROUTE_DESTINATION:   /* 3 IAX2: Can't find extension in context */
05916       case AST_CAUSE_NO_ROUTE_TRANSIT_NET:   /* 2 */
05917          return "404 Not Found";
05918       case AST_CAUSE_CONGESTION:    /* 34 */
05919       case AST_CAUSE_SWITCH_CONGESTION:   /* 42 */
05920          return "503 Service Unavailable";
05921       case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
05922          return "408 Request Timeout";
05923       case AST_CAUSE_NO_ANSWER:     /* 19 */
05924       case AST_CAUSE_UNREGISTERED:        /* 20 */
05925          return "480 Temporarily unavailable";
05926       case AST_CAUSE_CALL_REJECTED:    /* 21 */
05927          return "403 Forbidden";
05928       case AST_CAUSE_NUMBER_CHANGED:      /* 22 */
05929          return "410 Gone";
05930       case AST_CAUSE_NORMAL_UNSPECIFIED:  /* 31 */
05931          return "480 Temporarily unavailable";
05932       case AST_CAUSE_INVALID_NUMBER_FORMAT:
05933          return "484 Address incomplete";
05934       case AST_CAUSE_USER_BUSY:
05935          return "486 Busy here";
05936       case AST_CAUSE_FAILURE:
05937          return "500 Server internal failure";
05938       case AST_CAUSE_FACILITY_REJECTED:   /* 29 */
05939          return "501 Not Implemented";
05940       case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
05941          return "503 Service Unavailable";
05942       /* Used in chan_iax2 */
05943       case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
05944          return "502 Bad Gateway";
05945       case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
05946          return "488 Not Acceptable Here";
05947          
05948       case AST_CAUSE_NOTDEFINED:
05949       default:
05950          ast_debug(1, "AST hangup cause %d (no match found in SIP)\n", cause);
05951          return NULL;
05952    }
05953 
05954    /* Never reached */
05955    return 0;
05956 }
05957 
05958 
05959 /*! \brief  sip_hangup: Hangup SIP call
05960  * Part of PBX interface, called from ast_hangup */
05961 static int sip_hangup(struct ast_channel *ast)
05962 {
05963    struct sip_pvt *p = ast->tech_pvt;
05964    int needcancel = FALSE;
05965    int needdestroy = 0;
05966    struct ast_channel *oldowner = ast;
05967 
05968    if (!p) {
05969       ast_debug(1, "Asked to hangup channel that was not connected\n");
05970       return 0;
05971    }
05972    if (ast_test_flag(ast, AST_FLAG_ANSWERED_ELSEWHERE) || ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
05973       ast_debug(1, "This call was answered elsewhere");
05974       if (ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
05975          ast_debug(1, "####### It's the cause code, buddy. The cause code!!!\n");
05976       }
05977       append_history(p, "Cancel", "Call answered elsewhere");
05978       p->answered_elsewhere = TRUE;
05979    }
05980 
05981    /* Store hangupcause locally in PVT so we still have it before disconnect */
05982    if (p->owner)
05983       p->hangupcause = p->owner->hangupcause;
05984 
05985    if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
05986       if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05987          if (sipdebug)
05988             ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
05989          update_call_counter(p, DEC_CALL_LIMIT);
05990       }
05991       ast_debug(4, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
05992       if (p->autokillid > -1 && sip_cancel_destroy(p))
05993          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
05994       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05995       ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Really hang up next time */
05996       p->needdestroy = 0;
05997       p->owner->tech_pvt = dialog_unref(p->owner->tech_pvt, "unref p->owner->tech_pvt");
05998       sip_pvt_lock(p);
05999       p->owner = NULL;  /* Owner will be gone after we return, so take it away */
06000       sip_pvt_unlock(p);
06001       ast_module_unref(ast_module_info->self);
06002       return 0;
06003    }
06004 
06005    if (ast_test_flag(ast, AST_FLAG_ZOMBIE)) {
06006       if (p->refer)
06007          ast_debug(1, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast->name, p->callid);
06008       else
06009          ast_debug(1, "Hanging up zombie call. Be scared.\n");
06010    } else
06011       ast_debug(1, "Hangup call %s, SIP callid %s\n", ast->name, p->callid);
06012 
06013    sip_pvt_lock(p);
06014    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06015       if (sipdebug)
06016          ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
06017       update_call_counter(p, DEC_CALL_LIMIT);
06018    }
06019 
06020    /* Determine how to disconnect */
06021    if (p->owner != ast) {
06022       ast_log(LOG_WARNING, "Huh?  We aren't the owner? Can't hangup call.\n");
06023       sip_pvt_unlock(p);
06024       return 0;
06025    }
06026    /* If the call is not UP, we need to send CANCEL instead of BYE */
06027    /* In case of re-invites, the call might be UP even though we have an incomplete invite transaction */
06028    if (p->invitestate < INV_COMPLETED && p->owner->_state != AST_STATE_UP) {
06029       needcancel = TRUE;
06030       ast_debug(4, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
06031    }
06032 
06033    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
06034 
06035    append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", p->owner ? ast_cause2str(p->hangupcause) : "Unknown");
06036 
06037    /* Disconnect */
06038    if (p->dsp)
06039       ast_dsp_free(p->dsp);
06040 
06041    p->owner = NULL;
06042    ast->tech_pvt = dialog_unref(ast->tech_pvt, "unref ast->tech_pvt");
06043 
06044    ast_module_unref(ast_module_info->self);
06045    /* Do not destroy this pvt until we have timeout or
06046       get an answer to the BYE or INVITE/CANCEL 
06047       If we get no answer during retransmit period, drop the call anyway.
06048       (Sorry, mother-in-law, you can't deny a hangup by sending
06049       603 declined to BYE...)
06050    */
06051    if (p->alreadygone)
06052       needdestroy = 1;  /* Set destroy flag at end of this function */
06053    else if (p->invitestate != INV_CALLING)
06054       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06055 
06056    /* Start the process if it's not already started */
06057    if (!p->alreadygone && p->initreq.data && !ast_strlen_zero(p->initreq.data->str)) {
06058       if (needcancel) { /* Outgoing call, not up */
06059          if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06060             /* stop retransmitting an INVITE that has not received a response */
06061             /* if we can't send right now, mark it pending */
06062             if (p->invitestate == INV_CALLING) {
06063                /* We can't send anything in CALLING state */
06064                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
06065                __sip_pretend_ack(p);
06066                /* 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. */
06067                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06068                append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
06069             } else {
06070                struct sip_pkt *cur;
06071 
06072                for (cur = p->packets; cur; cur = cur->next) {
06073                   __sip_semi_ack(p, cur->seqno, cur->is_resp, cur->method ? cur->method : find_sip_method(cur->data->str));
06074                }
06075                p->invitestate = INV_CANCELLED;
06076                /* Send a new request: CANCEL */
06077                transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
06078                /* Actually don't destroy us yet, wait for the 487 on our original 
06079                   INVITE, but do set an autodestruct just in case we never get it. */
06080                needdestroy = 0;
06081                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06082             }
06083          } else { /* Incoming call, not up */
06084             const char *res;
06085             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"));
06086             if (p->hangupcause && (res = hangup_cause2sip(p->hangupcause)))
06087                transmit_response_reliable(p, res, &p->initreq);
06088             else 
06089                transmit_response_reliable(p, "603 Declined", &p->initreq);
06090             p->invitestate = INV_TERMINATED;
06091          }
06092       } else { /* Call is in UP state, send BYE */
06093          if (p->stimer->st_active == TRUE) {
06094             stop_session_timer(p);
06095          }
06096 
06097          if (!p->pendinginvite) {
06098             struct ast_channel *bridge = ast_bridged_channel(oldowner);
06099             char *audioqos = "";
06100             char *videoqos = "";
06101             char *textqos = "";
06102 
06103             /* We need to get the lock on bridge because ast_rtp_set_vars will attempt
06104              * to lock the bridge. This may get hairy...
06105              */
06106             while (bridge && ast_channel_trylock(bridge)) {
06107                sip_pvt_unlock(p);
06108                do {
06109                   /* Use oldowner since p->owner is already NULL */
06110                   CHANNEL_DEADLOCK_AVOIDANCE(oldowner);
06111                } while (sip_pvt_trylock(p));
06112                bridge = ast_bridged_channel(oldowner);
06113             }
06114 
06115             if (p->rtp)
06116                ast_rtp_set_vars(oldowner, p->rtp);
06117 
06118             if (bridge) {
06119                struct sip_pvt *q = bridge->tech_pvt;
06120 
06121                if (IS_SIP_TECH(bridge->tech) && q && q->rtp)
06122                   ast_rtp_set_vars(bridge, q->rtp);
06123                ast_channel_unlock(bridge);
06124             }
06125 
06126             if (p->vrtp)
06127                videoqos = ast_rtp_get_quality(p->vrtp, NULL, RTPQOS_SUMMARY);
06128             if (p->trtp)
06129                textqos = ast_rtp_get_quality(p->trtp, NULL, RTPQOS_SUMMARY);
06130             /* Send a hangup */
06131             if (oldowner->_state == AST_STATE_UP) {
06132                transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
06133             }
06134 
06135             /* Get RTCP quality before end of call */
06136             if (p->do_history) {
06137                if (p->rtp)
06138                   append_history(p, "RTCPaudio", "Quality:%s", audioqos);
06139                if (p->vrtp)
06140                   append_history(p, "RTCPvideo", "Quality:%s", videoqos);
06141                if (p->trtp)
06142                   append_history(p, "RTCPtext", "Quality:%s", textqos);
06143             }
06144             if (p->rtp && oldowner)
06145                pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", audioqos);
06146             if (p->vrtp && oldowner)
06147                pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", videoqos);
06148             if (p->trtp && oldowner)
06149                pbx_builtin_setvar_helper(oldowner, "RTPTEXTQOS", textqos);
06150          } else {
06151             /* Note we will need a BYE when this all settles out
06152                but we can't send one while we have "INVITE" outstanding. */
06153             ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
06154             ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE); 
06155             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"));
06156             if (sip_cancel_destroy(p))
06157                ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
06158          }
06159       }
06160    }
06161    if (needdestroy) {
06162       pvt_set_needdestroy(p, "hangup");
06163    }
06164    sip_pvt_unlock(p);
06165    return 0;
06166 }
06167 
06168 /*! \brief Try setting codec suggested by the SIP_CODEC channel variable */
06169 static void try_suggested_sip_codec(struct sip_pvt *p)
06170 {
06171    int fmt;
06172    const char *codec;
06173 
06174    codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
06175    if (!codec) 
06176       return;
06177 
06178    fmt = ast_getformatbyname(codec);
06179    if (fmt) {
06180       ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
06181       if (p->jointcapability & fmt) {
06182          p->jointcapability &= fmt;
06183          p->capability &= fmt;
06184       } else
06185          ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
06186    } else
06187       ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
06188    return;  
06189 }
06190 
06191 /*! \brief  sip_answer: Answer SIP call , send 200 OK on Invite 
06192  * Part of PBX interface */
06193 static int sip_answer(struct ast_channel *ast)
06194 {
06195    int res = 0;
06196    struct sip_pvt *p = ast->tech_pvt;
06197 
06198    sip_pvt_lock(p);
06199    if (ast->_state != AST_STATE_UP) {
06200       try_suggested_sip_codec(p);   
06201 
06202       ast_setstate(ast, AST_STATE_UP);
06203       ast_debug(1, "SIP answering channel: %s\n", ast->name);
06204       ast_rtp_new_source(p->rtp);
06205       res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL, FALSE);
06206       ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
06207    }
06208    sip_pvt_unlock(p);
06209    return res;
06210 }
06211 
06212 /*! \brief Send frame to media channel (rtp) */
06213 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
06214 {
06215    struct sip_pvt *p = ast->tech_pvt;
06216    int res = 0;
06217 
06218    switch (frame->frametype) {
06219    case AST_FRAME_VOICE:
06220       if (!(frame->subclass & ast->nativeformats)) {
06221          char s1[512], s2[512], s3[512];
06222          ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %s(%d) read/write = %s(%d)/%s(%d)\n",
06223             frame->subclass, 
06224             ast_getformatname_multiple(s1, sizeof(s1) - 1, ast->nativeformats & AST_FORMAT_AUDIO_MASK),
06225             ast->nativeformats & AST_FORMAT_AUDIO_MASK,
06226             ast_getformatname_multiple(s2, sizeof(s2) - 1, ast->readformat),
06227             ast->readformat,
06228             ast_getformatname_multiple(s3, sizeof(s3) - 1, ast->writeformat),
06229             ast->writeformat);
06230          return 0;
06231       }
06232       if (p) {
06233          sip_pvt_lock(p);
06234          if (p->rtp) {
06235             /* If channel is not up, activate early media session */
06236             if ((ast->_state != AST_STATE_UP) &&
06237                 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06238                 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06239                ast_rtp_new_source(p->rtp);
06240                if (!global_prematuremediafilter) {
06241                   p->invitestate = INV_EARLY_MEDIA;
06242                   transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06243                   ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06244                }
06245             } else if (p->t38.state == T38_ENABLED) {
06246                /* drop frame, can't sent VOICE frames while in T.38 mode */
06247             } else {
06248                p->lastrtptx = time(NULL);
06249                res = ast_rtp_write(p->rtp, frame);
06250             }
06251          }
06252          sip_pvt_unlock(p);
06253       }
06254       break;
06255    case AST_FRAME_VIDEO:
06256       if (p) {
06257          sip_pvt_lock(p);
06258          if (p->vrtp) {
06259             /* Activate video early media */
06260             if ((ast->_state != AST_STATE_UP) &&
06261                 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06262                 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06263                p->invitestate = INV_EARLY_MEDIA;
06264                transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06265                ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06266             }
06267             p->lastrtptx = time(NULL);
06268             res = ast_rtp_write(p->vrtp, frame);
06269          }
06270          sip_pvt_unlock(p);
06271       }
06272       break;
06273    case AST_FRAME_TEXT:
06274       if (p) {
06275          sip_pvt_lock(p);
06276          if (p->red) {
06277             red_buffer_t140(p->trtp, frame);
06278          } else {
06279             if (p->trtp) {
06280                /* Activate text early media */
06281                if ((ast->_state != AST_STATE_UP) &&
06282                    !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06283                    !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06284                   p->invitestate = INV_EARLY_MEDIA;
06285                   transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06286                   ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06287                }
06288                p->lastrtptx = time(NULL);
06289                res = ast_rtp_write(p->trtp, frame);
06290             }
06291          }
06292          sip_pvt_unlock(p);
06293       }
06294       break;
06295    case AST_FRAME_IMAGE:
06296       return 0;
06297       break;
06298    case AST_FRAME_MODEM:
06299       if (p) {
06300          sip_pvt_lock(p);
06301          /* UDPTL requires two-way communication, so early media is not needed here.
06302             we simply forget the frames if we get modem frames before the bridge is up.
06303             Fax will re-transmit.
06304          */
06305          if ((ast->_state == AST_STATE_UP) &&
06306              p->udptl &&
06307              (p->t38.state == T38_ENABLED)) {
06308             res = ast_udptl_write(p->udptl, frame);
06309          }
06310          sip_pvt_unlock(p);
06311       }
06312       break;
06313    default: 
06314       ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
06315       return 0;
06316    }
06317 
06318    return res;
06319 }
06320 
06321 /*! \brief  sip_fixup: Fix up a channel:  If a channel is consumed, this is called.
06322         Basically update any ->owner links */
06323 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
06324 {
06325    int ret = -1;
06326    struct sip_pvt *p;
06327 
06328    if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE))
06329       ast_debug(1, "New channel is zombie\n");
06330    if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE))
06331       ast_debug(1, "Old channel is zombie\n");
06332 
06333    if (!newchan || !newchan->tech_pvt) {
06334       if (!newchan)
06335          ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
06336       else
06337          ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
06338       return -1;
06339    }
06340    p = newchan->tech_pvt;
06341 
06342    sip_pvt_lock(p);
06343    append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
06344    append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
06345    if (p->owner != oldchan)
06346       ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
06347    else {
06348       p->owner = newchan;
06349       /* Re-invite RTP back to Asterisk. Needed if channel is masqueraded out of a native
06350          RTP bridge (i.e., RTP not going through Asterisk): RTP bridge code might not be
06351          able to do this if the masquerade happens before the bridge breaks (e.g., AMI
06352          redirect of both channels). Note that a channel can not be masqueraded *into*
06353          a native bridge. So there is no danger that this breaks a native bridge that
06354          should stay up. */
06355       sip_set_rtp_peer(newchan, NULL, NULL, 0, 0, 0);
06356       ret = 0;
06357    }
06358    ast_debug(3, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);
06359 
06360    sip_pvt_unlock(p);
06361    return ret;
06362 }
06363 
06364 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
06365 {
06366    struct sip_pvt *p = ast->tech_pvt;
06367    int res = 0;
06368 
06369    sip_pvt_lock(p);
06370    switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06371    case SIP_DTMF_INBAND:
06372       res = -1; /* Tell Asterisk to generate inband indications */
06373       break;
06374    case SIP_DTMF_RFC2833:
06375       if (p->rtp)
06376          ast_rtp_senddigit_begin(p->rtp, digit);
06377       break;
06378    default:
06379       break;
06380    }
06381    sip_pvt_unlock(p);
06382 
06383    return res;
06384 }
06385 
06386 /*! \brief Send DTMF character on SIP channel
06387    within one call, we're able to transmit in many methods simultaneously */
06388 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
06389 {
06390    struct sip_pvt *p = ast->tech_pvt;
06391    int res = 0;
06392 
06393    sip_pvt_lock(p);
06394    switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06395    case SIP_DTMF_INFO:
06396    case SIP_DTMF_SHORTINFO:
06397       transmit_info_with_digit(p, digit, duration);
06398       break;
06399    case SIP_DTMF_RFC2833:
06400       if (p->rtp)
06401          ast_rtp_senddigit_end(p->rtp, digit);
06402       break;
06403    case SIP_DTMF_INBAND:
06404       res = -1; /* Tell Asterisk to stop inband indications */
06405       break;
06406    }
06407    sip_pvt_unlock(p);
06408 
06409    return res;
06410 }
06411 
06412 /*! \brief Transfer SIP call */
06413 static int sip_transfer(struct ast_channel *ast, const char *dest)
06414 {
06415    struct sip_pvt *p = ast->tech_pvt;
06416    int res;
06417 
06418    if (dest == NULL) /* functions below do not take a NULL */
06419       dest = "";
06420    sip_pvt_lock(p);
06421    if (ast->_state == AST_STATE_RING)
06422       res = sip_sipredirect(p, dest);
06423    else
06424       res = transmit_refer(p, dest);
06425    sip_pvt_unlock(p);
06426    return res;
06427 }
06428 
06429 /*! \brief Helper function which updates T.38 capability information and triggers a reinvite */
06430 static int interpret_t38_parameters(struct sip_pvt *p, const struct ast_control_t38_parameters *parameters)
06431 {
06432    int res = 0;
06433 
06434    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) || !p->udptl) {
06435       return -1;
06436    }
06437    switch (parameters->request_response) {
06438    case AST_T38_NEGOTIATED:
06439    case AST_T38_REQUEST_NEGOTIATE:         /* Request T38 */
06440       /* Negotiation can not take place without a valid max_ifp value. */
06441       if (!parameters->max_ifp) {
06442          change_t38_state(p, T38_DISABLED);
06443          if (p->t38.state == T38_PEER_REINVITE) {
06444             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"));
06445             transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06446          }
06447          break;
06448       } else if (p->t38.state == T38_PEER_REINVITE) {
06449          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"));
06450          p->t38.our_parms = *parameters;
06451          /* modify our parameters to conform to the peer's parameters,
06452           * based on the rules in the ITU T.38 recommendation
06453           */
06454          if (!p->t38.their_parms.fill_bit_removal) {
06455             p->t38.our_parms.fill_bit_removal = FALSE;
06456          }
06457          if (!p->t38.their_parms.transcoding_mmr) {
06458             p->t38.our_parms.transcoding_mmr = FALSE;
06459          }
06460          if (!p->t38.their_parms.transcoding_jbig) {
06461             p->t38.our_parms.transcoding_jbig = FALSE;
06462          }
06463          p->t38.our_parms.version = MIN(p->t38.our_parms.version, p->t38.their_parms.version);
06464          p->t38.our_parms.rate_management = p->t38.their_parms.rate_management;
06465          ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06466          change_t38_state(p, T38_ENABLED);
06467          transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
06468       } else if (p->t38.state != T38_ENABLED) {
06469          p->t38.our_parms = *parameters;
06470          ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06471          change_t38_state(p, T38_LOCAL_REINVITE);
06472          if (!p->pendinginvite) {
06473             transmit_reinvite_with_sdp(p, TRUE, FALSE);
06474          } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
06475             ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
06476          }
06477       }
06478       break;
06479    case AST_T38_TERMINATED:
06480    case AST_T38_REFUSED:
06481    case AST_T38_REQUEST_TERMINATE:         /* Shutdown T38 */
06482       if (p->t38.state == T38_PEER_REINVITE) {
06483          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"));
06484          change_t38_state(p, T38_DISABLED);
06485          transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06486       } else if (p->t38.state == T38_ENABLED)
06487          transmit_reinvite_with_sdp(p, FALSE, FALSE);
06488       break;
06489    case AST_T38_REQUEST_PARMS: {    /* Application wants remote's parameters re-sent */
06490       struct ast_control_t38_parameters parameters = p->t38.their_parms;
06491 
06492       if (p->t38.state == T38_PEER_REINVITE) {
06493          AST_SCHED_DEL(sched, p->t38id);
06494          parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
06495          parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
06496          ast_queue_control_data(p->owner, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
06497          /* we need to return a positive value here, so that applications that
06498           * send this request can determine conclusively whether it was accepted or not...
06499           * older versions of chan_sip would just silently accept it and return zero.
06500           */
06501          res = AST_T38_REQUEST_PARMS;
06502       }
06503       break;
06504    }
06505    default:
06506       res = -1;
06507       break;
06508    }
06509 
06510    return res;
06511 }
06512 
06513 /*! \brief Play indication to user 
06514  * With SIP a lot of indications is sent as messages, letting the device play
06515    the indication - busy signal, congestion etc 
06516    \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
06517 */
06518 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
06519 {
06520    struct sip_pvt *p = ast->tech_pvt;
06521    int res = 0;
06522 
06523    sip_pvt_lock(p);
06524    switch(condition) {
06525    case AST_CONTROL_RINGING:
06526       if (ast->_state == AST_STATE_RING) {
06527          p->invitestate = INV_EARLY_MEDIA;
06528          if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
06529              (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {            
06530             /* Send 180 ringing if out-of-band seems reasonable */
06531             transmit_provisional_response(p, "180 Ringing", &p->initreq, 0);
06532             ast_set_flag(&p->flags[0], SIP_RINGING);
06533             if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
06534                break;
06535          } else {
06536             /* Well, if it's not reasonable, just send in-band */
06537          }
06538       }
06539       res = -1;
06540       break;
06541    case AST_CONTROL_BUSY:
06542       if (ast->_state != AST_STATE_UP) {
06543          transmit_response_reliable(p, "486 Busy Here", &p->initreq);
06544          p->invitestate = INV_COMPLETED;
06545          sip_alreadygone(p);
06546          ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06547          break;
06548       }
06549       res = -1;
06550       break;
06551    case AST_CONTROL_CONGESTION:
06552       if (ast->_state != AST_STATE_UP) {
06553          transmit_response_reliable(p, "503 Service Unavailable", &p->initreq);
06554          p->invitestate = INV_COMPLETED;
06555          sip_alreadygone(p);
06556          ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06557          break;
06558       }
06559       res = -1;
06560       break;
06561    case AST_CONTROL_PROCEEDING:
06562       if ((ast->_state != AST_STATE_UP) &&
06563           !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06564           !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06565          transmit_response(p, "100 Trying", &p->initreq);
06566          p->invitestate = INV_PROCEEDING;  
06567          break;
06568       }
06569       res = -1;
06570       break;
06571    case AST_CONTROL_PROGRESS:
06572       if ((ast->_state != AST_STATE_UP) &&
06573           !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06574           !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06575          p->invitestate = INV_EARLY_MEDIA;
06576          transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06577          ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06578          break;
06579       }
06580       res = -1;
06581       break;
06582    case AST_CONTROL_HOLD:
06583       ast_rtp_new_source(p->rtp);
06584       ast_moh_start(ast, data, p->mohinterpret);
06585       break;
06586    case AST_CONTROL_UNHOLD:
06587       ast_rtp_new_source(p->rtp);
06588       ast_moh_stop(ast);
06589       break;
06590    case AST_CONTROL_VIDUPDATE:   /* Request a video frame update */
06591       if (p->vrtp && !p->novideo) {
06592          transmit_info_with_vidupdate(p);
06593          /* ast_rtcp_send_h261fur(p->vrtp); */
06594       } else
06595          res = -1;
06596       break;
06597    case AST_CONTROL_T38_PARAMETERS:
06598       if (datalen != sizeof(struct ast_control_t38_parameters)) {
06599          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);
06600          res = -1;
06601       } else {
06602          const struct ast_control_t38_parameters *parameters = data;
06603          res = interpret_t38_parameters(p, parameters);
06604       }
06605       break;
06606    case AST_CONTROL_SRCUPDATE:
06607       ast_rtp_new_source(p->rtp);
06608       break;
06609    case AST_CONTROL_SRCCHANGE:
06610       ast_rtp_change_source(p->rtp);
06611       break;
06612    case -1:
06613       res = -1;
06614       break;
06615    default:
06616       ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
06617       res = -1;
06618       break;
06619    }
06620    sip_pvt_unlock(p);
06621    return res;
06622 }
06623 
06624 
06625 /*! \brief Initiate a call in the SIP channel
06626    called from sip_request_call (calls from the pbx ) for outbound channels
06627    and from handle_request_invite for inbound channels
06628    
06629 */
06630 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title)
06631 {
06632    struct ast_channel *tmp;
06633    struct ast_variable *v = NULL;
06634    int fmt;
06635    int what;
06636    int video;
06637    int text;
06638    int needvideo = 0;
06639    int needtext = 0;
06640    char buf[SIPBUFSIZE];
06641    char *decoded_exten;
06642 
06643    {
06644       const char *my_name; /* pick a good name */
06645    
06646       if (title) {
06647          my_name = title;
06648       } else {
06649          char *port = NULL;
06650          my_name = ast_strdupa(i->fromdomain);
06651          if ((port = strchr(i->fromdomain, ':'))) {
06652             *port = '\0';
06653          }
06654       }
06655 
06656       sip_pvt_unlock(i);
06657       /* Don't hold a sip pvt lock while we allocate a channel */
06658       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));
06659 
06660    }
06661    if (!tmp) {
06662       ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
06663       sip_pvt_lock(i);
06664       return NULL;
06665    }
06666    sip_pvt_lock(i);
06667 
06668    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;
06669 
06670    /* Select our native format based on codec preference until we receive
06671       something from another device to the contrary. */
06672    if (i->jointcapability) {  /* The joint capabilities of us and peer */
06673       what = i->jointcapability;
06674       video = i->jointcapability & AST_FORMAT_VIDEO_MASK;
06675       text = i->jointcapability & AST_FORMAT_TEXT_MASK;
06676    } else if (i->capability) {      /* Our configured capability for this peer */
06677       what = i->capability;
06678       video = i->capability & AST_FORMAT_VIDEO_MASK;
06679       text = i->capability & AST_FORMAT_TEXT_MASK;
06680    } else {
06681       what = global_capability;  /* Global codec support */
06682       video = global_capability & AST_FORMAT_VIDEO_MASK;
06683       text = global_capability & AST_FORMAT_TEXT_MASK;
06684    }
06685 
06686    /* Set the native formats for audio  and merge in video */
06687    tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | video | text;
06688    ast_debug(3, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmp->nativeformats));
06689    ast_debug(3, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcapability));
06690    ast_debug(3, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->capability));
06691    ast_debug(3, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, ast_codec_choose(&i->prefs, what, 1)));
06692    if (i->prefcodec)
06693       ast_debug(3, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcodec));
06694 
06695    /* XXX Why are we choosing a codec from the native formats?? */
06696    fmt = ast_best_codec(tmp->nativeformats);
06697 
06698    /* If we have a prefcodec setting, we have an inbound channel that set a 
06699       preferred format for this call. Otherwise, we check the jointcapability
06700       We also check for vrtp. If it's not there, we are not allowed do any video anyway.
06701     */
06702    if (i->vrtp) {
06703       if (ast_test_flag(&i->flags[1], SIP_PAGE2_VIDEOSUPPORT))
06704          needvideo = AST_FORMAT_VIDEO_MASK;
06705       else if (i->prefcodec)
06706          needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK;  /* Outbound call */
06707       else
06708          needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK;  /* Inbound call */
06709    }
06710 
06711    if (i->trtp) {
06712       if (i->prefcodec)
06713          needtext = i->prefcodec & AST_FORMAT_TEXT_MASK; /* Outbound call */
06714       else
06715          needtext = i->jointcapability & AST_FORMAT_TEXT_MASK; /* Inbound call */
06716    }
06717 
06718    if (needvideo) 
06719       ast_debug(3, "This channel can handle video! HOLLYWOOD next!\n");
06720    else
06721       ast_debug(3, "This channel will not be able to handle video.\n");
06722 
06723    if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) || (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) ||
06724        (ast_test_flag(&i->flags[1], SIP_PAGE2_FAX_DETECT))) {
06725       int features = 0;
06726 
06727       if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) || (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
06728          features |= DSP_FEATURE_DIGIT_DETECT;
06729       }
06730 
06731       if (ast_test_flag(&i->flags[1], SIP_PAGE2_FAX_DETECT)) {
06732          features |= DSP_FEATURE_FAX_DETECT;
06733       }
06734 
06735       i->dsp = ast_dsp_new();
06736       ast_dsp_set_features(i->dsp, features);
06737       if (global_relaxdtmf)
06738          ast_dsp_set_digitmode(i->dsp, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
06739          }
06740 
06741    /* Set file descriptors for audio, video, realtime text and UDPTL as needed */
06742    if (i->rtp) {
06743       ast_channel_set_fd(tmp, 0, ast_rtp_fd(i->rtp));
06744       ast_channel_set_fd(tmp, 1, ast_rtcp_fd(i->rtp));
06745    }
06746    if (needvideo && i->vrtp) {
06747       ast_channel_set_fd(tmp, 2, ast_rtp_fd(i->vrtp));
06748       ast_channel_set_fd(tmp, 3, ast_rtcp_fd(i->vrtp));
06749    }
06750    if (needtext && i->trtp) 
06751       ast_channel_set_fd(tmp, 4, ast_rtp_fd(i->trtp));
06752    if (i->udptl)
06753       ast_channel_set_fd(tmp, 5, ast_udptl_fd(i->udptl));
06754 
06755    if (state == AST_STATE_RING)
06756       tmp->rings = 1;
06757    tmp->adsicpe = AST_ADSI_UNAVAILABLE;
06758    tmp->writeformat = fmt;
06759    tmp->rawwriteformat = fmt;
06760    tmp->readformat = fmt;
06761    tmp->rawreadformat = fmt;
06762    tmp->tech_pvt = dialog_ref(i, "sip_new: set chan->tech_pvt to i");
06763 
06764    tmp->callgroup = i->callgroup;
06765    tmp->pickupgroup = i->pickupgroup;
06766    tmp->cid.cid_pres = i->callingpres;
06767    if (!ast_strlen_zero(i->parkinglot))
06768       ast_string_field_set(tmp, parkinglot, i->parkinglot);
06769    if (!ast_strlen_zero(i->accountcode))
06770       ast_string_field_set(tmp, accountcode, i->accountcode);
06771    if (i->amaflags)
06772       tmp->amaflags = i->amaflags;
06773    if (!ast_strlen_zero(i->language))
06774       ast_string_field_set(tmp, language, i->language);
06775    i->owner = tmp;
06776    ast_module_ref(ast_module_info->self);
06777    ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
06778    /*Since it is valid to have extensions in the dialplan that have unescaped characters in them
06779     * we should decode the uri before storing it in the channel, but leave it encoded in the sip_pvt
06780     * structure so that there aren't issues when forming URI's
06781     */
06782    decoded_exten = ast_strdupa(i->exten);
06783    ast_uri_decode(decoded_exten);
06784    ast_copy_string(tmp->exten, decoded_exten, sizeof(tmp->exten));
06785 
06786    /* Don't use ast_set_callerid() here because it will
06787     * generate an unnecessary NewCallerID event  */
06788    tmp->cid.cid_ani = ast_strdup(i->cid_num);
06789    if (!ast_strlen_zero(i->rdnis))
06790       tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
06791    
06792    if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
06793       tmp->cid.cid_dnid = ast_strdup(i->exten);
06794 
06795    tmp->priority = 1;
06796    if (!ast_strlen_zero(i->uri))
06797       pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
06798    if (!ast_strlen_zero(i->domain))
06799       pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
06800    if (!ast_strlen_zero(i->callid))
06801       pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
06802    if (i->rtp)
06803       ast_jb_configure(tmp, &global_jbconf);
06804 
06805    /* Set channel variables for this call from configuration */
06806    for (v = i->chanvars ; v ; v = v->next) {
06807       char valuebuf[1024];
06808       pbx_builtin_setvar_helper(tmp, v->name, ast_get_encoded_str(v->value, valuebuf, sizeof(valuebuf)));
06809    }
06810 
06811    if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
06812       ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
06813       tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
06814       ast_hangup(tmp);
06815       tmp = NULL;
06816    }
06817 
06818    if (i->do_history)
06819       append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);
06820 
06821    /* Inform manager user about new channel and their SIP call ID */
06822    if (sip_cfg.callevents)
06823       manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
06824          "Channel: %s\r\nUniqueid: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\n",
06825          tmp->name, tmp->uniqueid, "SIP", i->callid, i->fullcontact);
06826 
06827    return tmp;
06828 }
06829 
06830 /*! \brief Reads one line of SIP message body */
06831 static char *get_body_by_line(const char *line, const char *name, int nameLen, char delimiter)
06832 {
06833    if (!strncasecmp(line, name, nameLen) && line[nameLen] == delimiter)
06834       return ast_skip_blanks(line + nameLen + 1);
06835 
06836    return "";
06837 }
06838 
06839 /*! \brief Lookup 'name' in the SDP starting
06840  * at the 'start' line. Returns the matching line, and 'start'
06841  * is updated with the next line number.
06842  */
06843 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
06844 {
06845    int len = strlen(name);
06846 
06847    while (*start < (req->sdp_start + req->sdp_count)) {
06848       const char *r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[(*start)++]), name, len, '=');
06849       if (r[0] != '\0')
06850          return r;
06851    }
06852 
06853    /* if the line was not found, ensure that *start points past the SDP */
06854    (*start)++;
06855 
06856    return "";
06857 }
06858 
06859 /*! \brief Fetches the next valid SDP line between the 'start' line
06860  * (inclusive) and the 'stop' line (exclusive). Returns the type
06861  * ('a', 'c', ...) and matching line in reference 'start' is updated
06862  * with the next line number.
06863  */
06864 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value)
06865 {
06866    char type = '\0';
06867    const char *line = NULL;
06868 
06869    if (stop > (req->sdp_start + req->sdp_count)) {
06870       stop = req->sdp_start + req->sdp_count;
06871    }
06872 
06873    while (*start < stop) {
06874       line = REQ_OFFSET_TO_STR(req, line[(*start)++]);
06875       if (line[1] == '=') {
06876          type = line[0];
06877          *value = ast_skip_blanks(line + 2);
06878          break;
06879       }
06880    }
06881 
06882    return type;
06883 }
06884 
06885 /*! \brief Get a specific line from the message body */
06886 static char *get_body(struct sip_request *req, char *name, char delimiter) 
06887 {
06888    int x;
06889    int len = strlen(name);
06890    char *r;
06891 
06892    for (x = 0; x < req->lines; x++) {
06893       r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[x]), name, len, delimiter);
06894       if (r[0] != '\0')
06895          return r;
06896    }
06897 
06898    return "";
06899 }
06900 
06901 /*! \brief Find compressed SIP alias */
06902 static const char *find_alias(const char *name, const char *_default)
06903 {
06904    /*! \brief Structure for conversion between compressed SIP and "normal" SIP */
06905    static const struct cfalias {
06906       char * const fullname;
06907       char * const shortname;
06908    } aliases[] = {
06909       { "Content-Type",  "c" },
06910       { "Content-Encoding",    "e" },
06911       { "From",       "f" },
06912       { "Call-ID",       "i" },
06913       { "Contact",       "m" },
06914       { "Content-Length",   "l" },
06915       { "Subject",       "s" },
06916       { "To",         "t" },
06917       { "Supported",     "k" },
06918       { "Refer-To",      "r" },
06919       { "Referred-By",   "b" },
06920       { "Allow-Events",  "u" },
06921       { "Event",      "o" },
06922       { "Via",     "v" },
06923       { "Accept-Contact",      "a" },
06924       { "Reject-Contact",      "j" },
06925       { "Request-Disposition", "d" },
06926       { "Session-Expires",     "x" },
06927       { "Identity",            "y" },
06928       { "Identity-Info",       "n" },
06929    };
06930    int x;
06931 
06932    for (x = 0; x < ARRAY_LEN(aliases); x++) {
06933       if (!strcasecmp(aliases[x].fullname, name))
06934          return aliases[x].shortname;
06935    }
06936 
06937    return _default;
06938 }
06939 
06940 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
06941 {
06942    int pass;
06943 
06944    /*
06945     * Technically you can place arbitrary whitespace both before and after the ':' in
06946     * a header, although RFC3261 clearly says you shouldn't before, and place just
06947     * one afterwards.  If you shouldn't do it, what absolute idiot decided it was 
06948     * a good idea to say you can do it, and if you can do it, why in the hell would.
06949     * you say you shouldn't.
06950     * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
06951     * and we always allow spaces after that for compatibility.
06952     */
06953    for (pass = 0; name && pass < 2;pass++) {
06954       int x, len = strlen(name);
06955       for (x = *start; x < req->headers; x++) {
06956          char *header = REQ_OFFSET_TO_STR(req, header[x]);
06957          if (!strncasecmp(header, name, len)) {
06958             char *r = header + len; /* skip name */
06959             if (sip_cfg.pedanticsipchecking)
06960                r = ast_skip_blanks(r);
06961 
06962             if (*r == ':') {
06963                *start = x+1;
06964                return ast_skip_blanks(r+1);
06965             }
06966          }
06967       }
06968       if (pass == 0) /* Try aliases */
06969          name = find_alias(name, NULL);
06970    }
06971 
06972    /* Don't return NULL, so get_header is always a valid pointer */
06973    return "";
06974 }
06975 
06976 /*! \brief Get header from SIP request 
06977    \return Always return something, so don't check for NULL because it won't happen :-)
06978 */
06979 static const char *get_header(const struct sip_request *req, const char *name)
06980 {
06981    int start = 0;
06982    return __get_header(req, name, &start);
06983 }
06984 
06985 /*! \brief Read RTP from network */
06986 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
06987 {
06988    /* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
06989    struct ast_frame *f;
06990    
06991    if (!p->rtp) {
06992       /* We have no RTP allocated for this channel */
06993       return &ast_null_frame;
06994    }
06995 
06996    switch(ast->fdno) {
06997    case 0:
06998       f = ast_rtp_read(p->rtp);  /* RTP Audio */
06999       break;
07000    case 1:
07001       f = ast_rtcp_read(p->rtp); /* RTCP Control Channel */
07002       break;
07003    case 2:
07004       f = ast_rtp_read(p->vrtp); /* RTP Video */
07005       break;
07006    case 3:
07007       f = ast_rtcp_read(p->vrtp);   /* RTCP Control Channel for video */
07008       break;
07009    case 4:
07010       f = ast_rtp_read(p->trtp); /* RTP Text */
07011       if (sipdebug_text) {
07012          int i;
07013          unsigned char* arr = f->data.ptr;
07014          for (i=0; i < f->datalen; i++)
07015             ast_verbose("%c", (arr[i] > ' ' && arr[i] < '}') ? arr[i] : '.');
07016          ast_verbose(" -> ");
07017          for (i=0; i < f->datalen; i++)
07018             ast_verbose("%02X ", arr[i]);
07019          ast_verbose("\n");
07020       }
07021       break;
07022    case 5:
07023       f = ast_udptl_read(p->udptl); /* UDPTL for T.38 */
07024       break;
07025    default:
07026       f = &ast_null_frame;
07027    }
07028    /* Don't forward RFC2833 if we're not supposed to */
07029    if (f && (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) &&
07030        (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833)) {
07031       ast_debug(1, "Ignoring DTMF (%c) RTP frame because dtmfmode is not RFC2833\n", f->subclass);
07032       return &ast_null_frame;
07033    }
07034 
07035    /* We already hold the channel lock */
07036    if (!p->owner || (f && f->frametype != AST_FRAME_VOICE))
07037       return f;
07038 
07039    if (f && f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
07040       if (!(f->subclass & p->jointcapability)) {
07041          ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
07042             ast_getformatname(f->subclass), p->owner->name);
07043          return &ast_null_frame;
07044       }
07045       ast_debug(1, "Oooh, format changed to %d %s\n",
07046          f->subclass, ast_getformatname(f->subclass));
07047       p->owner->nativeformats = (p->owner->nativeformats & (AST_FORMAT_VIDEO_MASK | AST_FORMAT_TEXT_MASK)) | f->subclass;
07048       ast_set_read_format(p->owner, p->owner->readformat);
07049       ast_set_write_format(p->owner, p->owner->writeformat);
07050    }
07051 
07052    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) {
07053       f = ast_dsp_process(p->owner, p->dsp, f);
07054                 if (f && f->frametype == AST_FRAME_DTMF) {
07055          if (f->subclass == 'f') {
07056                                 if (option_debug)
07057                                         ast_log(LOG_DEBUG, "Fax CNG detected on %s\n", ast->name);
07058                                 *faxdetect = 1;
07059             /* If we only needed this DSP for fax detection purposes we can just drop it now */
07060             if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
07061                ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
07062             } else {
07063                ast_dsp_free(p->dsp);
07064                p->dsp = NULL;
07065             }
07066          } else {
07067             ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass);
07068          }
07069       }
07070    }
07071    
07072    return f;
07073 }
07074 
07075 /*! \brief Read SIP RTP from channel */
07076 static struct ast_frame *sip_read(struct ast_channel *ast)
07077 {
07078    struct ast_frame *fr;
07079    struct sip_pvt *p = ast->tech_pvt;
07080    int faxdetected = FALSE;
07081 
07082    sip_pvt_lock(p);
07083    fr = sip_rtp_read(ast, p, &faxdetected);
07084    p->lastrtprx = time(NULL);
07085 
07086    /* If we detect a CNG tone and fax detection is enabled then send us off to the fax extension */
07087    if (faxdetected && ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
07088       ast_channel_lock(ast);
07089       if (strcmp(ast->exten, "fax")) {
07090          const char *target_context = S_OR(ast->macrocontext, ast->context);
07091          ast_channel_unlock(ast);
07092          if (ast_exists_extension(ast, target_context, "fax", 1, ast->cid.cid_num)) {
07093             ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to CNG detection\n", ast->name);
07094             pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
07095             if (ast_async_goto(ast, target_context, "fax", 1)) {
07096                ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast->name, target_context);
07097             }
07098             fr = &ast_null_frame;
07099          } else {
07100             ast_log(LOG_NOTICE, "FAX CNG detected but no fax extension\n");
07101                         }
07102       } else {
07103          ast_channel_unlock(ast);
07104                 }
07105         }
07106 
07107    /* Only allow audio through if they sent progress with SDP, or if the channel is actually answered */
07108    if (fr && fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast->_state != AST_STATE_UP) {
07109       fr = &ast_null_frame;
07110    }
07111 
07112    sip_pvt_unlock(p);
07113 
07114    return fr;
07115 }
07116 
07117 
07118 /*! \brief Generate 32 byte random string for callid's etc */
07119 static char *generate_random_string(char *buf, size_t size)
07120 {
07121    long val[4];
07122    int x;
07123 
07124    for (x=0; x<4; x++)
07125       val[x] = ast_random();
07126    snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
07127 
07128    return buf;
07129 }
07130 
07131 /*! \brief Build SIP Call-ID value for a non-REGISTER transaction */
07132 static void build_callid_pvt(struct sip_pvt *pvt)
07133 {
07134    char buf[33];
07135 
07136    const char *host = S_OR(pvt->fromdomain, ast_inet_ntoa(pvt->ourip.sin_addr));
07137    
07138    ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07139 
07140 }
07141 
07142 /*! \brief Build SIP Call-ID value for a REGISTER transaction */
07143 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain)
07144 {
07145    char buf[33];
07146 
07147    const char *host = S_OR(fromdomain, ast_inet_ntoa(ourip));
07148 
07149    ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07150 }
07151 
07152 /*! \brief Make our SIP dialog tag */
07153 static void make_our_tag(char *tagbuf, size_t len)
07154 {
07155    snprintf(tagbuf, len, "as%08lx", ast_random());
07156 }
07157 
07158 /*! \brief Allocate Session-Timers struct w/in dialog */
07159 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
07160 {
07161    struct sip_st_dlg *stp;
07162 
07163    if (p->stimer) {
07164       ast_log(LOG_ERROR, "Session-Timer struct already allocated\n");
07165       return p->stimer;
07166    }
07167 
07168    if (!(stp = ast_calloc(1, sizeof(struct sip_st_dlg))))
07169       return NULL;
07170 
07171    p->stimer = stp;
07172 
07173    stp->st_schedid = -1;           /* Session-Timers ast_sched scheduler id */
07174 
07175    return p->stimer;
07176 }
07177 
07178 /*! \brief Allocate sip_pvt structure, set defaults and link in the container.
07179  * Returns a reference to the object so whoever uses it later must
07180  * remember to release the reference.
07181  */
07182 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
07183              int useglobal_nat, const int intended_method, struct sip_request *req)
07184 {
07185    struct sip_pvt *p;
07186 
07187    if (!(p = ao2_t_alloc(sizeof(*p), sip_destroy_fn, "allocate a dialog(pvt) struct")))
07188       return NULL;
07189 
07190    if (ast_string_field_init(p, 512)) {
07191       ao2_t_ref(p, -1, "failed to string_field_init, drop p");
07192       return NULL;
07193    }
07194 
07195    if (req) {
07196       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 */
07197    } else {
07198       set_socket_transport(&p->socket, SIP_TRANSPORT_UDP);
07199    }
07200 
07201    p->socket.fd = -1;
07202    p->method = intended_method;
07203    p->initid = -1;
07204    p->waitid = -1;
07205    p->autokillid = -1;
07206    p->request_queue_sched_id = -1;
07207    p->provisional_keepalive_sched_id = -1;
07208    p->t38id = -1;
07209    p->subscribed = NONE;
07210    p->stateid = -1;
07211    p->sessionversion_remote = -1;
07212    p->session_modify = TRUE;
07213    p->stimer = NULL;
07214    p->prefs = default_prefs;     /* Set default codecs for this call */
07215 
07216    if (intended_method != SIP_OPTIONS) {  /* Peerpoke has it's own system */
07217       p->timer_t1 = global_t1;   /* Default SIP retransmission timer T1 (RFC 3261) */
07218       p->timer_b = global_timer_b;  /* Default SIP transaction timer B (RFC 3261) */
07219    }
07220 
07221    if (!sin)
07222       p->ourip = internip;
07223    else {
07224       p->sa = *sin;
07225       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
07226    }
07227 
07228    /* Copy global flags to this PVT at setup. */
07229    ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
07230    ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
07231 
07232    p->do_history = recordhistory;
07233 
07234    p->branch = ast_random();  
07235    make_our_tag(p->tag, sizeof(p->tag));
07236    p->ocseq = INITIAL_CSEQ;
07237 
07238    if (sip_methods[intended_method].need_rtp) {
07239       p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
07240       /* If the global videosupport flag is on, we always create a RTP interface for video */
07241       if (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
07242             ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS))
07243          p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
07244       if (ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT))
07245          p->trtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
07246       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
07247          if (!(p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr))) {
07248             /* udptl creation failed, T38 can not be supported on this dialog */
07249             ast_log(LOG_ERROR, "UDPTL creation failed\n");
07250             ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
07251          }
07252       }
07253       if (!p->rtp|| (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) && !p->vrtp) 
07254             || (ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) && !p->trtp)) {
07255          ast_log(LOG_WARNING, "Unable to create RTP audio %s%ssession: %s\n",
07256             ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "and video " : "",
07257             ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "and text " : "", strerror(errno));
07258          if (p->chanvars) {
07259             ast_variables_destroy(p->chanvars);
07260             p->chanvars = NULL;
07261          }
07262          ao2_t_ref(p, -1, "failed to create RTP audio session, drop p");
07263          return NULL;
07264          p->t38_maxdatagram = global_t38_maxdatagram;
07265       }
07266       ast_rtp_setqos(p->rtp, global_tos_audio, global_cos_audio, "SIP RTP");
07267       ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
07268       ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
07269       ast_rtp_set_rtptimeout(p->rtp, global_rtptimeout);
07270       ast_rtp_set_rtpholdtimeout(p->rtp, global_rtpholdtimeout);
07271       ast_rtp_set_rtpkeepalive(p->rtp, global_rtpkeepalive);
07272       if (p->vrtp) {
07273          ast_rtp_setqos(p->vrtp, global_tos_video, global_cos_video, "SIP VRTP");
07274          ast_rtp_setdtmf(p->vrtp, 0);
07275          ast_rtp_setdtmfcompensate(p->vrtp, 0);
07276          ast_rtp_set_rtptimeout(p->vrtp, global_rtptimeout);
07277          ast_rtp_set_rtpholdtimeout(p->vrtp, global_rtpholdtimeout);
07278          ast_rtp_set_rtpkeepalive(p->vrtp, global_rtpkeepalive);
07279       }
07280       if (p->trtp) {
07281          ast_rtp_setqos(p->trtp, global_tos_text, global_cos_text, "SIP TRTP");
07282          ast_rtp_setdtmf(p->trtp, 0);
07283          ast_rtp_setdtmfcompensate(p->trtp, 0);
07284       }
07285       if (p->udptl)
07286          ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
07287       p->maxcallbitrate = default_maxcallbitrate;
07288       p->autoframing = global_autoframing;
07289       ast_rtp_codec_setpref(p->rtp, &p->prefs);
07290    }
07291 
07292    if (useglobal_nat && sin) {
07293       /* Setup NAT structure according to global settings if we have an address */
07294       ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
07295       p->recv = *sin;
07296       do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
07297    }
07298 
07299    if (p->method != SIP_REGISTER)
07300       ast_string_field_set(p, fromdomain, default_fromdomain);
07301    build_via(p);
07302    if (!callid)
07303       build_callid_pvt(p);
07304    else
07305       ast_string_field_set(p, callid, callid);
07306    /* Assign default music on hold class */
07307    ast_string_field_set(p, mohinterpret, default_mohinterpret);
07308    ast_string_field_set(p, mohsuggest, default_mohsuggest);
07309    p->capability = global_capability;
07310    p->allowtransfer = sip_cfg.allowtransfer;
07311    if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
07312        (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
07313       p->noncodeccapability |= AST_RTP_DTMF;
07314    if (p->udptl) {
07315       p->t38_maxdatagram = global_t38_maxdatagram;
07316       set_t38_capabilities(p);
07317    }
07318    ast_string_field_set(p, context, sip_cfg.default_context);
07319    ast_string_field_set(p, parkinglot, default_parkinglot);
07320 
07321    AST_LIST_HEAD_INIT_NOLOCK(&p->request_queue);
07322 
07323    /* Add to active dialog list */
07324 
07325    ao2_t_link(dialogs, p, "link pvt into dialogs table");
07326    
07327    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");
07328    return p;
07329 }
07330 
07331 /*! \brief argument to the helper function to identify a call */
07332 struct find_call_cb_arg {
07333    enum sipmethod method;
07334    const char *callid;
07335    const char *fromtag;
07336    const char *totag;
07337    const char *tag;
07338 };
07339 
07340 /*!
07341  * code to determine whether this is the pvt that we are looking for.
07342  * Return FALSE if not found, true otherwise. p is unlocked.
07343  */
07344 static int find_call_cb(void *__pvt, void *__arg, int flags)
07345 {
07346    struct sip_pvt *p = __pvt;
07347    struct find_call_cb_arg *arg = __arg;
07348    /* In pedantic, we do not want packets with bad syntax to be connected to a PVT */
07349    int found = FALSE;
07350    
07351    if (!ast_strlen_zero(p->callid)) { /* XXX double check, do we allow match on empty p->callid ? */
07352       if (arg->method == SIP_REGISTER)
07353          found = (!strcmp(p->callid, arg->callid));
07354       else {
07355          found = !strcmp(p->callid, arg->callid);
07356          if (sip_cfg.pedanticsipchecking && found) {
07357             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);
07358          } 
07359       }
07360       
07361       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);
07362       
07363       /* If we get a new request within an existing to-tag - check the to tag as well */
07364       if (sip_cfg.pedanticsipchecking && found && arg->method != SIP_RESPONSE) { /* SIP Request */
07365          if (p->tag[0] == '\0' && arg->totag[0]) {
07366             /* We have no to tag, but they have. Wrong dialog */
07367             found = FALSE;
07368          } else if (arg->totag[0]) { /* Both have tags, compare them */
07369             if (strcmp(arg->totag, p->tag)) {
07370                found = FALSE; /* This is not our packet */
07371             }
07372          }
07373          if (!found)
07374             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);
07375       }
07376    }
07377    return found;
07378 }
07379 
07380 /*! \brief find or create a dialog structure for an incoming SIP message.
07381  * Connect incoming SIP message to current dialog or create new dialog structure
07382  * Returns a reference to the sip_pvt object, remember to give it back once done.
07383  *     Called by handle_incoming(), sipsock_read
07384  */
07385 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
07386 {
07387    struct sip_pvt *p = NULL;
07388    char *tag = "";   /* note, tag is never NULL */
07389    char totag[128];
07390    char fromtag[128];
07391    struct find_call_cb_arg arg;
07392    const char *callid = get_header(req, "Call-ID");
07393    const char *from = get_header(req, "From");
07394    const char *to = get_header(req, "To");
07395    const char *cseq = get_header(req, "Cseq");
07396    struct sip_pvt *sip_pvt_ptr;
07397 
07398    /* Call-ID, to, from and Cseq are required by RFC 3261. (Max-forwards and via too - ignored now) */
07399    /* get_header always returns non-NULL so we must use ast_strlen_zero() */
07400    if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
07401          ast_strlen_zero(from) || ast_strlen_zero(cseq))
07402       return NULL;   /* Invalid packet */
07403 
07404    arg.method = req->method;
07405    arg.callid = callid;
07406    arg.fromtag = fromtag;
07407    arg.totag = totag;
07408    arg.tag = ""; /* make sure tag is never NULL */
07409 
07410    if (sip_cfg.pedanticsipchecking) {
07411       /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
07412          we need more to identify a branch - so we have to check branch, from
07413          and to tags to identify a call leg.
07414          For Asterisk to behave correctly, you need to turn on pedanticsipchecking
07415          in sip.conf
07416          */
07417       if (gettag(req, "To", totag, sizeof(totag)))
07418          req->has_to_tag = 1; /* Used in handle_request/response */
07419       gettag(req, "From", fromtag, sizeof(fromtag));
07420 
07421       tag = (req->method == SIP_RESPONSE) ? totag : fromtag;
07422 
07423       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);
07424 
07425       /* All messages must always have From: tag */
07426       if (ast_strlen_zero(fromtag)) {
07427          ast_debug(5, "%s request has no from tag, dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
07428          return NULL;
07429       }
07430       /* reject requests that must always have a To: tag */
07431       if (ast_strlen_zero(totag) && (req->method == SIP_ACK || req->method == SIP_BYE || req->method == SIP_INFO )) {
07432          ast_debug(5, "%s must have a to tag. dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
07433          return NULL;
07434       }
07435    }
07436 
07437 restartsearch:
07438    if (!sip_cfg.pedanticsipchecking) {
07439       struct sip_pvt tmp_dialog = {
07440          .callid = callid,
07441       };       
07442       sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find in dialogs");
07443       if (sip_pvt_ptr) {  /* well, if we don't find it-- what IS in there? */
07444          /* Found the call */
07445          sip_pvt_lock(sip_pvt_ptr);
07446          return sip_pvt_ptr;
07447       }
07448    } else { /* in pedantic mode! -- do the fancy linear search */
07449       ao2_lock(dialogs);
07450       p = ao2_t_callback(dialogs, 0 /* single, data */, find_call_cb, &arg, "pedantic linear search for dialog");
07451       if (p) {
07452          if (sip_pvt_trylock(p)) {
07453             ao2_unlock(dialogs);
07454             usleep(1);
07455             goto restartsearch;
07456          }
07457          ao2_unlock(dialogs);
07458          return p;
07459       }
07460       ao2_unlock(dialogs);
07461    }
07462  
07463    /* See if the method is capable of creating a dialog */
07464    if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
07465       if (intended_method == SIP_REFER) {
07466          /* We do support REFER, but not outside of a dialog yet */
07467          transmit_response_using_temp(callid, sin, 1, intended_method, req, "603 Declined (no dialog)");
07468       } else if (intended_method == SIP_NOTIFY) {
07469          /* We do not support out-of-dialog NOTIFY either,
07470             like voicemail notification, so cancel that early */
07471          transmit_response_using_temp(callid, sin, 1, intended_method, req, "489 Bad event");
07472       } else {
07473          /* Ok, time to create a new SIP dialog object, a pvt */
07474          if ((p = sip_alloc(callid, sin, 1, intended_method, req)))  {
07475             /* Ok, we've created a dialog, let's go and process it */
07476             sip_pvt_lock(p);
07477          } else {
07478             /* We have a memory or file/socket error (can't allocate RTP sockets or something) so we're not
07479                getting a dialog from sip_alloc. 
07480    
07481                Without a dialog we can't retransmit and handle ACKs and all that, but at least
07482                send an error message.
07483    
07484                Sorry, we apologize for the inconvienience
07485             */
07486             transmit_response_using_temp(callid, sin, 1, intended_method, req, "500 Server internal error");
07487             ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
07488          }
07489       }
07490       return p; /* can be NULL */
07491    } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
07492       /* A method we do not support, let's take it on the volley */
07493       transmit_response_using_temp(callid, sin, 1, intended_method, req, "501 Method Not Implemented");
07494       ast_debug(2, "Got a request with unsupported SIP method.\n");
07495    } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
07496       /* This is a request outside of a dialog that we don't know about */
07497       transmit_response_using_temp(callid, sin, 1, intended_method, req, "481 Call leg/transaction does not exist");
07498       ast_debug(2, "That's odd...  Got a request in unknown dialog. Callid %s\n", callid ? callid : "<unknown>");
07499    }
07500    /* We do not respond to responses for dialogs that we don't know about, we just drop
07501       the session quickly */
07502    if (intended_method == SIP_RESPONSE)
07503       ast_debug(2, "That's odd...  Got a response on a call we don't know about. Callid %s\n", callid ? callid : "<unknown>");
07504 
07505    return NULL;
07506 }
07507 
07508 /*! \brief Parse register=> line in sip.conf and add to registry */
07509 static int sip_register(const char *value, int lineno)
07510 {
07511    struct sip_registry *reg;
07512    int portnum = 0;
07513    enum sip_transport transport = SIP_TRANSPORT_UDP;
07514    char buf[256] = "";
07515    char *userpart = NULL, *hostpart = NULL;
07516    /* register => [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] */
07517    AST_DECLARE_APP_ARGS(pre1,
07518       AST_APP_ARG(peer);
07519       AST_APP_ARG(userpart);
07520    );
07521    AST_DECLARE_APP_ARGS(pre2,
07522       AST_APP_ARG(transport);
07523       AST_APP_ARG(blank);
07524       AST_APP_ARG(userpart);
07525    );
07526    AST_DECLARE_APP_ARGS(user1,
07527       AST_APP_ARG(userpart);
07528       AST_APP_ARG(secret);
07529       AST_APP_ARG(authuser);
07530    );
07531    AST_DECLARE_APP_ARGS(host1,
07532       AST_APP_ARG(hostpart);
07533       AST_APP_ARG(expiry);
07534    );
07535    AST_DECLARE_APP_ARGS(host2,
07536       AST_APP_ARG(hostpart);
07537       AST_APP_ARG(extension);
07538    );
07539    AST_DECLARE_APP_ARGS(host3,
07540       AST_APP_ARG(host);
07541       AST_APP_ARG(port);
07542    );
07543 
07544    if (!value)
07545       return -1;
07546    ast_copy_string(buf, value, sizeof(buf));
07547 
07548    /*! register => [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry]
07549     * becomes
07550     *   userpart => [peer?][transport://]user[@domain][:secret[:authuser]]
07551     *   hostpart => host[:port][/extension][~expiry]
07552     */
07553    if ((hostpart = strrchr(buf, '@'))) {
07554       *hostpart++ = '\0';
07555       userpart = buf;
07556    }
07557 
07558    if (ast_strlen_zero(userpart) || ast_strlen_zero(hostpart)) {
07559       ast_log(LOG_WARNING, "Format for registration is [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] at line %d\n", lineno);
07560       return -1;
07561    }
07562 
07563    /*!
07564     * pre1.peer => peer
07565     * pre1.userpart => [transport://]user[@domain][:secret[:authuser]]
07566     * hostpart => host[:port][/extension][~expiry]
07567     */
07568    AST_NONSTANDARD_RAW_ARGS(pre1, userpart, '?');
07569    if (ast_strlen_zero(pre1.userpart)) {
07570       pre1.userpart = pre1.peer;
07571       pre1.peer = NULL;
07572    }
07573 
07574    /*!
07575     * pre1.peer => peer
07576     * pre2.transport = transport
07577     * pre2.userpart => user[@domain][:secret[:authuser]]
07578     * hostpart => host[:port][/extension][~expiry]
07579     */
07580    AST_NONSTANDARD_RAW_ARGS(pre2, pre1.userpart, '/');
07581    if (ast_strlen_zero(pre2.userpart)) {
07582       pre2.userpart = pre2.transport;
07583       pre2.transport = NULL;
07584    } else {
07585       pre2.transport[strlen(pre2.transport) - 1] = '\0'; /* Remove trailing : */
07586    }
07587 
07588    if (!ast_strlen_zero(pre2.blank)) {
07589       ast_log(LOG_WARNING, "Format for registration is [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] at line %d\n", lineno);
07590       return -1;
07591    }
07592 
07593    /*!
07594     * pre1.peer => peer
07595     * pre2.transport = transport
07596     * user1.userpart => user[@domain]
07597     * user1.secret => secret
07598     * user1.authuser => authuser
07599     * hostpart => host[:port][/extension][~expiry]
07600     */
07601    AST_NONSTANDARD_RAW_ARGS(user1, pre2.userpart, ':');
07602 
07603    /*!
07604     * pre1.peer => peer
07605     * pre2.transport = transport
07606     * user1.userpart => user[@domain]
07607     * user1.secret => secret
07608     * user1.authuser => authuser
07609     * host1.hostpart => host[:port][/extension]
07610     * host1.expiry => [expiry]
07611     */
07612    AST_NONSTANDARD_RAW_ARGS(host1, hostpart, '~');
07613 
07614    /*!
07615     * pre1.peer => peer
07616     * pre2.transport = transport
07617     * user1.userpart => user[@domain]
07618     * user1.secret => secret
07619     * user1.authuser => authuser
07620     * host2.hostpart => host[:port]
07621     * host2.extension => [extension]
07622     * host1.expiry => [expiry]
07623     */
07624    AST_NONSTANDARD_RAW_ARGS(host2, host1.hostpart, '/');
07625 
07626    /*!
07627     * pre1.peer => peer
07628     * pre2.transport = transport
07629     * user1.userpart => user[@domain]
07630     * user1.secret => secret
07631     * user1.authuser => authuser
07632     * host3.host => host
07633     * host3.port => port
07634     * host2.extension => extension
07635     * host1.expiry => expiry
07636     */
07637    AST_NONSTANDARD_RAW_ARGS(host3, host2.hostpart, ':');
07638 
07639    if (host3.port) {
07640       if (!(portnum = port_str2int(host3.port, 0))) {
07641          ast_log(LOG_NOTICE, "'%s' is not a valid port number on line %d of sip.conf. using default.\n", host3.port, lineno);
07642       }
07643    }
07644 
07645    /* set transport type */
07646    if (!pre2.transport) {
07647       transport = SIP_TRANSPORT_UDP;
07648    } else if (!strncasecmp(pre2.transport, "tcp", 3)) {
07649       transport = SIP_TRANSPORT_TCP;
07650    } else if (!strncasecmp(pre2.transport, "tls", 3)) {
07651       transport = SIP_TRANSPORT_TLS;
07652    } else if (!strncasecmp(pre2.transport, "udp", 3)) {
07653       transport = SIP_TRANSPORT_UDP;
07654    } else {
07655       transport = SIP_TRANSPORT_UDP;
07656       ast_log(LOG_NOTICE, "'%.3s' is not a valid transport type on line %d of sip.conf. defaulting to udp.\n", pre2.transport, lineno);
07657    }
07658 
07659    /* if no portnum specified, set default for transport */
07660    if (!portnum) {
07661       if (transport == SIP_TRANSPORT_TLS) {
07662          portnum = STANDARD_TLS_PORT;
07663       } else {
07664          portnum = STANDARD_SIP_PORT;
07665       }
07666    }
07667 
07668    if (!(reg = ast_calloc(1, sizeof(*reg)))) {
07669       ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
07670       return -1;
07671    }
07672 
07673    if (ast_string_field_init(reg, 256)) {
07674       ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry strings\n");
07675       ast_free(reg);
07676       return -1;
07677    }
07678 
07679    ast_atomic_fetchadd_int(&regobjs, 1);
07680    ASTOBJ_INIT(reg);
07681    ast_string_field_set(reg, callback, ast_strip_quoted(S_OR(host2.extension, "s"), "\"", "\""));
07682    ast_string_field_set(reg, username, ast_strip_quoted(S_OR(user1.userpart, ""), "\"", "\""));
07683    ast_string_field_set(reg, hostname, ast_strip_quoted(S_OR(host3.host, ""), "\"", "\""));
07684    ast_string_field_set(reg, authuser, ast_strip_quoted(S_OR(user1.authuser, ""), "\"", "\""));
07685    ast_string_field_set(reg, secret, ast_strip_quoted(S_OR(user1.secret, ""), "\"", "\""));
07686    ast_string_field_set(reg, peername, ast_strip_quoted(S_OR(pre1.peer, ""), "\"", "\""));
07687 
07688    reg->transport = transport;
07689    reg->timeout = reg->expire = -1;
07690    reg->refresh = reg->expiry = reg->configured_expiry = (host1.expiry ? atoi(ast_strip_quoted(host1.expiry, "\"", "\"")) : default_expiry);
07691    reg->portno = portnum;
07692    reg->callid_valid = FALSE;
07693    reg->ocseq = INITIAL_CSEQ;
07694    ASTOBJ_CONTAINER_LINK(&regl, reg); /* Add the new registry entry to the list */
07695    registry_unref(reg, "unref the reg pointer");   /* release the reference given by ASTOBJ_INIT. The container has another reference */
07696    return 0;
07697 }
07698 
07699 /*! \brief Parse mwi=> line in sip.conf and add to list */
07700 static int sip_subscribe_mwi(const char *value, int lineno)
07701 {
07702    struct sip_subscription_mwi *mwi;
07703    int portnum = 0;
07704    enum sip_transport transport = SIP_TRANSPORT_UDP;
07705    char buf[256] = "";
07706    char *username = NULL, *hostname = NULL, *secret = NULL, *authuser = NULL, *porta = NULL, *mailbox = NULL;
07707    
07708    if (!value) {
07709       return -1;
07710    }
07711    
07712    ast_copy_string(buf, value, sizeof(buf));
07713 
07714    sip_parse_host(buf, lineno, &username, &portnum, &transport);
07715    
07716    if ((hostname = strrchr(username, '@'))) {
07717       *hostname++ = '\0';
07718    }
07719    
07720    if ((secret = strchr(username, ':'))) {
07721       *secret++ = '\0';
07722       if ((authuser = strchr(secret, ':'))) {
07723          *authuser++ = '\0';
07724       }
07725    }
07726    
07727    if ((mailbox = strchr(hostname, '/'))) {
07728       *mailbox++ = '\0';
07729    }
07730 
07731    if (ast_strlen_zero(username) || ast_strlen_zero(hostname) || ast_strlen_zero(mailbox)) {
07732       ast_log(LOG_WARNING, "Format for MWI subscription is user[:secret[:authuser]]@host[:port][/mailbox] at line %d\n", lineno);
07733       return -1;
07734    }
07735    
07736    if ((porta = strchr(hostname, ':'))) {
07737       *porta++ = '\0';
07738       if (!(portnum = atoi(porta))) {
07739          ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
07740          return -1;
07741       }
07742    }
07743    
07744    if (!(mwi = ast_calloc(1, sizeof(*mwi)))) {
07745       return -1;
07746    }
07747    
07748    if (ast_string_field_init(mwi, 256)) {
07749       ast_free(mwi);
07750       return -1;
07751    }
07752    
07753    ASTOBJ_INIT(mwi);
07754    ast_string_field_set(mwi, username, username);
07755    if (secret) {
07756       ast_string_field_set(mwi, secret, secret);
07757    }
07758    if (authuser) {
07759       ast_string_field_set(mwi, authuser, authuser);
07760    }
07761    ast_string_field_set(mwi, hostname, hostname);
07762    ast_string_field_set(mwi, mailbox, mailbox);
07763    mwi->resub = -1;
07764    mwi->portno = portnum;
07765    mwi->transport = transport;
07766    
07767    ASTOBJ_CONTAINER_LINK(&submwil, mwi);
07768    ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
07769    
07770    return 0;
07771 }
07772 
07773 /*! \brief  Parse multiline SIP headers into one header
07774    This is enabled if pedanticsipchecking is enabled */
07775 static int lws2sws(char *msgbuf, int len) 
07776 {
07777    int h = 0, t = 0; 
07778    int lws = 0; 
07779 
07780    for (; h < len;) { 
07781       /* Eliminate all CRs */ 
07782       if (msgbuf[h] == '\r') { 
07783          h++; 
07784          continue; 
07785       } 
07786       /* Check for end-of-line */ 
07787       if (msgbuf[h] == '\n') { 
07788          /* Check for end-of-message */ 
07789          if (h + 1 == len) 
07790             break; 
07791          /* Check for a continuation line */ 
07792          if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') { 
07793             /* Merge continuation line */ 
07794             h++; 
07795             continue; 
07796          } 
07797          /* Propagate LF and start new line */ 
07798          msgbuf[t++] = msgbuf[h++]; 
07799          lws = 0;
07800          continue; 
07801       } 
07802       if (msgbuf[h] == ' ' || msgbuf[h] == '\t') { 
07803          if (lws) { 
07804             h++; 
07805             continue; 
07806          } 
07807          msgbuf[t++] = msgbuf[h++]; 
07808          lws = 1; 
07809          continue; 
07810       } 
07811       msgbuf[t++] = msgbuf[h++]; 
07812       if (lws) 
07813          lws = 0; 
07814    } 
07815    msgbuf[t] = '\0'; 
07816    return t; 
07817 }
07818 
07819 /*! \brief Parse a SIP message 
07820    \note this function is used both on incoming and outgoing packets
07821 */
07822 static int parse_request(struct sip_request *req)
07823 {
07824    char *c = req->data->str;
07825    ptrdiff_t *dst = req->header;
07826    int i = 0, lim = SIP_MAX_HEADERS - 1;
07827    unsigned int skipping_headers = 0;
07828    ptrdiff_t current_header_offset = 0;
07829    char *previous_header = "";
07830 
07831    req->header[0] = 0;
07832    req->headers = -1;   /* mark that we are working on the header */
07833    for (; *c; c++) {
07834       if (*c == '\r') {    /* remove \r */
07835          *c = '\0';
07836       } else if (*c == '\n') {   /* end of this line */
07837          *c = '\0';
07838          current_header_offset = (c + 1) - req->data->str;
07839          previous_header = req->data->str + dst[i];
07840          if (skipping_headers) {
07841             /* check to see if this line is blank; if so, turn off
07842                the skipping flag, so the next line will be processed
07843                as a body line */
07844             if (ast_strlen_zero(previous_header)) {
07845                skipping_headers = 0;
07846             }
07847             dst[i] = current_header_offset; /* record start of next line */
07848             continue;
07849          }
07850          if (sipdebug) {
07851             ast_debug(4, "%7s %2d [%3d]: %s\n",
07852                  req->headers < 0 ? "Header" : "Body",
07853                  i, (int) strlen(previous_header), previous_header);
07854          }
07855          if (ast_strlen_zero(previous_header) && req->headers < 0) {
07856             req->headers = i; /* record number of header lines */
07857             dst = req->line;  /* start working on the body */
07858             i = 0;
07859             lim = SIP_MAX_LINES - 1;
07860          } else { /* move to next line, check for overflows */
07861             if (i++ == lim) {
07862                /* if we're processing headers, then skip any remaining
07863                   headers and move on to processing the body, otherwise
07864                   we're done */
07865                if (req->headers != -1) {
07866                   break;
07867                } else {
07868                   req->headers = i;
07869                   dst = req->line;
07870                   i = 0;
07871                   lim = SIP_MAX_LINES - 1;
07872                   skipping_headers = 1;
07873                }
07874             }
07875          }
07876          dst[i] = current_header_offset; /* record start of next line */
07877       }
07878    }
07879 
07880    /* Check for last header or body line without CRLF. The RFC for SDP requires CRLF,
07881       but since some devices send without, we'll be generous in what we accept. However,
07882       if we've already reached the maximum number of lines for portion of the message
07883       we were parsing, we can't accept any more, so just ignore it.
07884    */
07885    previous_header = req->data->str + dst[i];
07886    if ((i < lim) && !ast_strlen_zero(previous_header)) {
07887       if (sipdebug) {
07888          ast_debug(4, "%7s %2d [%3d]: %s\n",
07889               req->headers < 0 ? "Header" : "Body",
07890               i, (int) strlen(previous_header), previous_header );
07891       }
07892       i++;
07893    }
07894 
07895    /* update count of header or body lines */
07896    if (req->headers >= 0) {   /* we are in the body */
07897       req->lines = i;
07898    } else {       /* no body */
07899       req->headers = i;
07900       req->lines = 0;
07901       /* req->data->used will be a NULL byte */
07902       req->line[0] = ast_str_strlen(req->data);
07903    }
07904 
07905    if (*c) {
07906       ast_log(LOG_WARNING, "Too many lines, skipping <%s>\n", c);
07907    }
07908 
07909    /* Split up the first line parts */
07910    return determine_firstline_parts(req);
07911 }
07912 
07913 /*!
07914   \brief Determine whether a SIP message contains an SDP in its body
07915   \param req the SIP request to process
07916   \return 1 if SDP found, 0 if not found
07917 
07918   Also updates req->sdp_start and req->sdp_count to indicate where the SDP
07919   lives in the message body.
07920 */
07921 static int find_sdp(struct sip_request *req)
07922 {
07923    const char *content_type;
07924    const char *content_length;
07925    const char *search;
07926    char *boundary;
07927    unsigned int x;
07928    int boundaryisquoted = FALSE;
07929    int found_application_sdp = FALSE;
07930    int found_end_of_headers = FALSE;
07931 
07932    content_length = get_header(req, "Content-Length");
07933 
07934    if (!ast_strlen_zero(content_length)) {
07935       if (sscanf(content_length, "%30u", &x) != 1) {
07936          ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
07937          return 0;
07938       }
07939 
07940       /* Content-Length of zero means there can't possibly be an
07941          SDP here, even if the Content-Type says there is */
07942       if (x == 0)
07943          return 0;
07944    }
07945 
07946    content_type = get_header(req, "Content-Type");
07947 
07948    /* if the body contains only SDP, this is easy */
07949    if (!strncasecmp(content_type, "application/sdp", 15)) {
07950       req->sdp_start = 0;
07951       req->sdp_count = req->lines;
07952       return req->lines ? 1 : 0;
07953    }
07954 
07955    /* if it's not multipart/mixed, there cannot be an SDP */
07956    if (strncasecmp(content_type, "multipart/mixed", 15))
07957       return 0;
07958 
07959    /* if there is no boundary marker, it's invalid */
07960    if ((search = strcasestr(content_type, ";boundary=")))
07961       search += 10;
07962    else if ((search = strcasestr(content_type, "; boundary=")))
07963       search += 11;
07964    else
07965       return 0;
07966 
07967    if (ast_strlen_zero(search))
07968       return 0;
07969 
07970    /* If the boundary is quoted with ", remove quote */
07971    if (*search == '\"')  {
07972       search++;
07973       boundaryisquoted = TRUE;
07974    }
07975 
07976    /* make a duplicate of the string, with two extra characters
07977       at the beginning */
07978    boundary = ast_strdupa(search - 2);
07979    boundary[0] = boundary[1] = '-';
07980    /* Remove final quote */
07981    if (boundaryisquoted)
07982       boundary[strlen(boundary) - 1] = '\0';
07983 
07984    /* search for the boundary marker, the empty line delimiting headers from
07985       sdp part and the end boundry if it exists */
07986 
07987    for (x = 0; x < (req->lines); x++) {
07988       char *line = REQ_OFFSET_TO_STR(req, line[x]);
07989       if (!strncasecmp(line, boundary, strlen(boundary))){
07990          if (found_application_sdp && found_end_of_headers) {
07991             req->sdp_count = (x - 1) - req->sdp_start;
07992             return 1;
07993          }
07994          found_application_sdp = FALSE;
07995       }
07996       if (!strcasecmp(line, "Content-Type: application/sdp"))
07997          found_application_sdp = TRUE;
07998       
07999       if (ast_strlen_zero(line)) {
08000          if (found_application_sdp && !found_end_of_headers){
08001             req->sdp_start = x;
08002             found_end_of_headers = TRUE;
08003          }
08004       }
08005    }
08006    if (found_application_sdp && found_end_of_headers) {
08007       req->sdp_count = x - req->sdp_start;
08008       return TRUE;
08009    }
08010    return FALSE;
08011 }
08012 
08013 enum media_type {
08014    SDP_AUDIO,
08015    SDP_VIDEO,
08016    SDP_IMAGE,
08017    SDP_TEXT,
08018 };
08019 
08020 static int get_ip_and_port_from_sdp(struct sip_request *req, const enum media_type media, struct sockaddr_in *sin)
08021 {
08022    const char *m;
08023    const char *c;
08024    int miterator = req->sdp_start;
08025    int citerator = req->sdp_start;
08026    int x = 0;
08027    int numberofports;
08028    int len;
08029    char host[258] = ""; /*Initialize to empty so we will know if we have any input */
08030    struct ast_hostent audiohp;
08031    struct hostent *hp;
08032 
08033    c = get_sdp_iterate(&citerator, req, "c");
08034    if (sscanf(c, "IN IP4 %256s", host) != 1) {
08035       ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
08036       /* Continue since there may be a valid host in a c= line specific to the audio stream */
08037    }
08038    /* We only want the m and c lines for audio */
08039    for (m = get_sdp_iterate(&miterator, req, "m"); !ast_strlen_zero(m); m = get_sdp_iterate(&miterator, req, "m")) {
08040       if ((media == SDP_AUDIO && ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08041           (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0))) ||
08042          (media == SDP_VIDEO && ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08043           (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len > 0)))) {
08044          /* See if there's a c= line for this media stream.
08045           * XXX There is no guarantee that we'll be grabbing the c= line for this
08046           * particular media stream here. However, this is the same logic used in process_sdp.
08047           */
08048          c = get_sdp_iterate(&citerator, req, "c");
08049          if (!ast_strlen_zero(c)) {
08050             sscanf(c, "IN IP4 %256s", host);
08051          }
08052          break;
08053       }
08054    }
08055 
08056    if (ast_strlen_zero(host) || x == 0) {
08057       ast_log(LOG_WARNING, "Failed to read an alternate host or port in SDP. Expect %s problems\n", media == SDP_AUDIO ? "audio" : "video");
08058       return -1;
08059    }
08060 
08061    hp = ast_gethostbyname(host, &audiohp);
08062    if (!hp) {
08063       ast_log(LOG_WARNING, "Could not look up IP address of alternate hostname. Expect %s problems\n", media == SDP_AUDIO? "audio" : "video");
08064       return -1;
08065    }
08066 
08067    memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
08068    sin->sin_port = htons(x);
08069    return 0;
08070 }
08071 
08072 /*! \brief Process SIP SDP offer, select formats and activate RTP channels
08073    If offer is rejected, we will not change any properties of the call
08074    Return 0 on success, a negative value on errors.
08075    Must be called after find_sdp().
08076 */
08077 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
08078 {
08079    /* Iterators for SDP parsing */
08080    int start = req->sdp_start;
08081    int next = start;
08082    int iterator = start;
08083 
08084    /* Temporary vars for SDP parsing */
08085    char type = '\0';
08086    const char *value = NULL;
08087    const char *m = NULL;           /* SDP media offer */
08088    const char *nextm = NULL;
08089    int len = -1;
08090 
08091    /* Host information */
08092    struct ast_hostent sessionhp;
08093    struct ast_hostent audiohp;
08094    struct ast_hostent videohp;
08095    struct ast_hostent texthp;
08096    struct ast_hostent imagehp;
08097    struct hostent *hp = NULL; /*!< RTP Audio host IP */
08098    struct hostent *vhp = NULL;   /*!< RTP video host IP */
08099    struct hostent *thp = NULL;   /*!< RTP text host IP */
08100    struct hostent *ihp = NULL;     /*!< UDPTL host ip */
08101    int portno = -1;     /*!< RTP Audio port number */
08102    int vportno = -1;    /*!< RTP Video port number */
08103    int tportno = -1;    /*!< RTP Text port number */
08104    int udptlportno = -1;      /*!< UDPTL Image port number */
08105    struct sockaddr_in sin;    /*!< media socket address */
08106    struct sockaddr_in vsin;   /*!< video socket address */
08107    struct sockaddr_in isin;   /*!< image socket address */
08108    struct sockaddr_in tsin;   /*!< text socket address */
08109 
08110    /* Peer capability is the capability in the SDP, non codec is RFC2833 DTMF (101) */ 
08111    int peercapability = 0, peernoncodeccapability = 0;
08112    int vpeercapability = 0, vpeernoncodeccapability = 0;
08113    int tpeercapability = 0, tpeernoncodeccapability = 0;
08114 
08115    struct ast_rtp *newaudiortp, *newvideortp, *newtextrtp;
08116    int newjointcapability;          /* Negotiated capability */
08117    int newpeercapability;
08118    int newnoncodeccapability;
08119 
08120    const char *codecs;
08121    int codec;
08122 
08123    /* Others */
08124    int sendonly = -1;
08125    int vsendonly = -1;
08126    int numberofports;
08127    int numberofmediastreams = 0;
08128    int last_rtpmap_codec = 0;
08129    int red_data_pt[10];    /* For T.140 red */
08130    int red_num_gen = 0;    /* For T.140 red */
08131    char red_fmtp[100] = "empty"; /* For T.140 red */
08132    int debug = sip_debug_test_pvt(p);
08133 
08134    /* START UNKNOWN */
08135    char buf[SIPBUFSIZE];
08136    /* END UNKNOWN */
08137 
08138    /* Initial check */
08139    if (!p->rtp) {
08140       ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
08141       return -1;
08142    }
08143 
08144    /* Initialize the temporary RTP structures we use to evaluate the offer from the peer */
08145 #ifdef LOW_MEMORY
08146    newaudiortp = ast_threadstorage_get(&ts_audio_rtp, ast_rtp_alloc_size());
08147 #else
08148    newaudiortp = alloca(ast_rtp_alloc_size());
08149 #endif
08150    memset(newaudiortp, 0, ast_rtp_alloc_size());
08151    ast_rtp_new_init(newaudiortp);
08152    ast_rtp_pt_clear(newaudiortp);
08153 
08154 #ifdef LOW_MEMORY
08155    newvideortp = ast_threadstorage_get(&ts_video_rtp, ast_rtp_alloc_size());
08156 #else
08157    newvideortp = alloca(ast_rtp_alloc_size());
08158 #endif
08159    memset(newvideortp, 0, ast_rtp_alloc_size());
08160    ast_rtp_new_init(newvideortp);
08161    ast_rtp_pt_clear(newvideortp);
08162 
08163 #ifdef LOW_MEMORY
08164    newtextrtp = ast_threadstorage_get(&ts_text_rtp, ast_rtp_alloc_size());
08165 #else
08166    newtextrtp = alloca(ast_rtp_alloc_size());
08167 #endif
08168    memset(newtextrtp, 0, ast_rtp_alloc_size());
08169    ast_rtp_new_init(newtextrtp);
08170    ast_rtp_pt_clear(newtextrtp);
08171 
08172    /* Update our last rtprx when we receive an SDP, too */
08173    p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
08174 
08175    memset(p->offered_media, 0, sizeof(p->offered_media));
08176 
08177 
08178    /* default: novideo and notext set */
08179    p->novideo = TRUE;
08180    p->notext = TRUE;
08181 
08182    if (p->vrtp)
08183       ast_rtp_pt_clear(newvideortp);  /* Must be cleared in case no m=video line exists */
08184  
08185    if (p->trtp)
08186       ast_rtp_pt_clear(newtextrtp);  /* Must be cleared in case no m=text line exists */
08187    
08188    /* Scan for the first media stream (m=) line to limit scanning of globals */
08189    nextm = get_sdp_iterate(&next, req, "m");
08190    if (ast_strlen_zero(nextm)) {
08191       ast_log(LOG_WARNING, "Insufficient information for SDP (m= not found)\n");
08192       return -1;
08193    }
08194 
08195    /* Scan session level SDP parameters (lines before first media stream) */
08196    while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
08197       int processed = FALSE;
08198       switch (type) {
08199       case 'o':
08200          /* If we end up receiving SDP that doesn't actually modify the session we don't want to treat this as a fatal
08201           * error. We just want to ignore the SDP and let the rest of the packet be handled as normal.
08202           */
08203          if (!process_sdp_o(value, p))
08204             return (p->session_modify == FALSE) ? 0 : -1;
08205          break;
08206       case 'c':
08207          if (process_sdp_c(value, &sessionhp)) {
08208             processed = TRUE;
08209             hp = &sessionhp.hp;
08210             vhp = hp;
08211             thp = hp;
08212             ihp = hp;
08213          }
08214          break;
08215       case 'a':
08216          if (process_sdp_a_sendonly(value, &sendonly)) {
08217             processed = TRUE;
08218             vsendonly = sendonly;
08219          }
08220          else if (process_sdp_a_audio(value, p, newaudiortp, &last_rtpmap_codec))
08221             processed = TRUE;
08222          else if (process_sdp_a_video(value, p, newvideortp, &last_rtpmap_codec))
08223             processed = TRUE;
08224          else if (process_sdp_a_text(value, p, newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
08225             processed = TRUE;
08226          else if (process_sdp_a_image(value, p))
08227             processed = TRUE;
08228          break;
08229       }
08230 
08231       if (option_debug > 2)
08232          ast_log(LOG_DEBUG, "Processing session-level SDP %c=%s... %s\n", type, value, (processed == TRUE)? "OK." : "UNSUPPORTED.");
08233    }
08234 
08235 
08236 
08237    /* Scan media stream (m=) specific parameters loop */
08238    while (!ast_strlen_zero(nextm)) {
08239       int audio = FALSE;
08240       int video = FALSE;
08241       int image = FALSE;
08242       int text = FALSE;
08243       int x;
08244 
08245       numberofports = 1;
08246       len = -1;
08247       start = next;
08248       m = nextm;
08249       iterator = next;
08250       nextm = get_sdp_iterate(&next, req, "m");
08251 
08252       /* Search for audio media definition */
08253       if ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08254           (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
08255          audio = TRUE;
08256          p->offered_media[SDP_AUDIO].offered = TRUE;
08257          numberofmediastreams++;
08258          portno = x;
08259 
08260          /* Scan through the RTP payload types specified in a "m=" line: */
08261          codecs = m + len;
08262          ast_copy_string(p->offered_media[SDP_AUDIO].text, codecs, sizeof(p->offered_media[SDP_AUDIO].text));
08263          for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08264             if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08265                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08266                return -1;
08267             }
08268             if (debug)
08269                ast_verbose("Found RTP audio format %d\n", codec);
08270 
08271             ast_rtp_set_m_type(newaudiortp, codec);
08272          }
08273       /* Search for video media definition */
08274       } else if ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08275             (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len >= 0)) {
08276          video = TRUE;
08277          p->novideo = FALSE;
08278          p->offered_media[SDP_VIDEO].offered = TRUE;
08279          numberofmediastreams++;
08280          vportno = x;
08281 
08282          /* Scan through the RTP payload types specified in a "m=" line: */
08283          codecs = m + len;
08284          ast_copy_string(p->offered_media[SDP_VIDEO].text, codecs, sizeof(p->offered_media[SDP_VIDEO].text));
08285          for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08286             if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08287                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08288                return -1;
08289             }
08290             if (debug)
08291                ast_verbose("Found RTP video format %d\n", codec);
08292             ast_rtp_set_m_type(newvideortp, codec);
08293          }
08294       /* Search for text media definition */
08295       } else if ((sscanf(m, "text %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08296             (sscanf(m, "text %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
08297          text = TRUE;
08298          p->notext = FALSE;
08299          p->offered_media[SDP_TEXT].offered = TRUE;
08300          numberofmediastreams++;
08301          tportno = x;
08302 
08303          /* Scan through the RTP payload types specified in a "m=" line: */
08304          codecs = m + len;
08305          ast_copy_string(p->offered_media[SDP_TEXT].text, codecs, sizeof(p->offered_media[SDP_TEXT].text));
08306          for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08307             if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08308                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08309                return -1;
08310             }
08311             if (debug)
08312                ast_verbose("Found RTP text format %d\n", codec);
08313             ast_rtp_set_m_type(newtextrtp, codec);
08314          }
08315       /* Search for image media definition */
08316       } else if (p->udptl && ((sscanf(m, "image %30u udptl t38%n", &x, &len) == 1 && len > 0) ||
08317                (sscanf(m, "image %30u UDPTL t38%n", &x, &len) == 1 && len > 0) )) {
08318          image = TRUE;
08319          if (debug)
08320             ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
08321          p->offered_media[SDP_IMAGE].offered = TRUE;
08322          udptlportno = x;
08323          numberofmediastreams++;
08324 
08325          if (p->t38.state != T38_ENABLED) {
08326             memset(&p->t38.their_parms, 0, sizeof(p->t38.their_parms));
08327 
08328             /* default EC to none, the remote end should
08329              * respond with the EC they want to use */
08330             ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
08331          }
08332       } else {
08333          ast_log(LOG_WARNING, "Unsupported SDP media type in offer: %s\n", m);
08334          continue;
08335       }
08336 
08337       /* Check for number of ports */
08338       if (numberofports > 1)
08339          ast_log(LOG_WARNING, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports);
08340       
08341 
08342 
08343       /* Media stream specific parameters */
08344       while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
08345          int processed = FALSE;
08346 
08347          switch (type) {
08348          case 'c':
08349             if (audio) {
08350                if (process_sdp_c(value, &audiohp)) {
08351                   processed = TRUE;
08352                   hp = &audiohp.hp;
08353                }
08354             } else if (video) {
08355                if (process_sdp_c(value, &videohp)) {
08356                   processed = TRUE;
08357                   vhp = &videohp.hp;
08358                }
08359             } else if (text) {
08360                if (process_sdp_c(value, &texthp)) {
08361                   processed = TRUE;
08362                   thp = &texthp.hp;
08363                }
08364             } else if (image) {
08365                if (process_sdp_c(value, &imagehp)) {
08366                   processed = TRUE;
08367                   ihp = &imagehp.hp;
08368                }
08369             }
08370             break;
08371          case 'a':
08372             /* Audio specific scanning */
08373             if (audio) {
08374                if (process_sdp_a_sendonly(value, &sendonly))
08375                   processed = TRUE;
08376                else if (process_sdp_a_audio(value, p, newaudiortp, &last_rtpmap_codec))
08377                   processed = TRUE;
08378             }
08379             /* Video specific scanning */
08380             else if (video) {
08381                if (process_sdp_a_sendonly(value, &vsendonly))
08382                   processed = TRUE;
08383                else if (process_sdp_a_video(value, p, newvideortp, &last_rtpmap_codec))
08384                   processed = TRUE;
08385             }
08386             /* Text (T.140) specific scanning */
08387             else if (text) {
08388                if (process_sdp_a_text(value, p, newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
08389                   processed = TRUE;
08390             }
08391             /* Image (T.38 FAX) specific scanning */
08392             else if (image) {
08393                if (process_sdp_a_image(value, p))
08394                   processed = TRUE;
08395             }
08396             break;
08397          }
08398 
08399          if (option_debug > 2)
08400             ast_log(LOG_DEBUG, "Processing media-level (%s) SDP %c=%s... %s\n",
08401                   (audio == TRUE)? "audio" : (video == TRUE)? "video" : "image",
08402                   type, value,
08403                   (processed == TRUE)? "OK." : "UNSUPPORTED.");
08404       }
08405    }
08406 
08407 
08408    /* Sanity checks */
08409    if (!hp && !vhp && !thp && !ihp) {
08410       ast_log(LOG_WARNING, "Insufficient information in SDP (c=)...\n");
08411       return -1;
08412    }
08413 
08414    if (portno == -1 && vportno == -1 && udptlportno == -1  && tportno == -1)
08415       /* No acceptable offer found in SDP  - we have no ports */
08416       /* Do not change RTP or VRTP if this is a re-invite */
08417       return -2;
08418 
08419    if (numberofmediastreams > 3)
08420       /* We have too many fax, audio and/or video and/or text media streams, fail this offer */
08421       return -3;
08422 
08423    if (udptlportno == -1) {
08424       change_t38_state(p, T38_DISABLED);
08425    }
08426 
08427 
08428    /* Now gather all of the codecs that we are asked for: */
08429    ast_rtp_get_current_formats(newaudiortp, &peercapability, &peernoncodeccapability);
08430    ast_rtp_get_current_formats(newvideortp, &vpeercapability, &vpeernoncodeccapability);
08431    ast_rtp_get_current_formats(newtextrtp, &tpeercapability, &tpeernoncodeccapability);
08432 
08433    newjointcapability = p->capability & (peercapability | vpeercapability | tpeercapability);
08434    newpeercapability = (peercapability | vpeercapability | tpeercapability);
08435    newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
08436 
08437    if (debug) {
08438       /* shame on whoever coded this.... */
08439       char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE], s5[SIPBUFSIZE];
08440 
08441       ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s/text=%s, combined - %s\n",
08442              ast_getformatname_multiple(s1, SIPBUFSIZE, p->capability),
08443              ast_getformatname_multiple(s2, SIPBUFSIZE, peercapability),
08444              ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
08445              ast_getformatname_multiple(s4, SIPBUFSIZE, tpeercapability),
08446              ast_getformatname_multiple(s5, SIPBUFSIZE, newjointcapability));
08447 
08448       ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
08449              ast_rtp_lookup_mime_multiple(s1, SIPBUFSIZE, p->noncodeccapability, 0, 0),
08450              ast_rtp_lookup_mime_multiple(s2, SIPBUFSIZE, peernoncodeccapability, 0, 0),
08451              ast_rtp_lookup_mime_multiple(s3, SIPBUFSIZE, newnoncodeccapability, 0, 0));
08452    }
08453    if (!newjointcapability && (portno != -1)) {
08454       ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
08455       /* Do NOT Change current setting */
08456       return -1;
08457    }
08458 
08459    /* Setup audio address and port */
08460    if (p->rtp) {
08461       if (portno > 0) {
08462          sin.sin_family = AF_INET;
08463          sin.sin_port = htons(portno);
08464          memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
08465          ast_rtp_set_peer(p->rtp, &sin);
08466          if (debug)
08467             ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
08468          /* We are now ready to change the sip session and p->rtp and p->vrtp with the offered codecs, since                                                                                                    
08469             they are acceptable */
08470          p->jointcapability = newjointcapability;                /* Our joint codec profile for this call */
08471          p->peercapability = newpeercapability;                  /* The other sides capability in latest offer */
08472          p->jointnoncodeccapability = newnoncodeccapability;     /* DTMF capabilities */
08473 
08474          ast_rtp_pt_copy(p->rtp, newaudiortp);
08475 
08476          if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
08477             ast_clear_flag(&p->flags[0], SIP_DTMF);
08478             if (newnoncodeccapability & AST_RTP_DTMF) {
08479                /* XXX Would it be reasonable to drop the DSP at this point? XXX */
08480                ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
08481                /* Since RFC2833 is now negotiated we need to change some properties of the RTP stream */
08482                ast_rtp_setdtmf(p->rtp, 1);
08483                ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
08484             } else {
08485                ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
08486             }
08487          }
08488       } else if (udptlportno > 0) {
08489          if (debug)
08490             ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session.\n");
08491       } else {
08492          ast_rtp_stop(p->rtp);
08493          if (debug)
08494             ast_verbose("Peer doesn't provide audio\n");
08495       }
08496    }
08497 
08498    /* Setup video address and port */
08499    if (p->vrtp) {
08500       if (vportno > 0) {
08501          vsin.sin_family = AF_INET;
08502          vsin.sin_port = htons(vportno);
08503          memcpy(&vsin.sin_addr, vhp->h_addr, sizeof(vsin.sin_addr));
08504          ast_rtp_set_peer(p->vrtp, &vsin);
08505          if (debug) 
08506             ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(vsin.sin_addr), ntohs(vsin.sin_port));
08507          ast_rtp_pt_copy(p->vrtp, newvideortp);
08508       } else {
08509          ast_rtp_stop(p->vrtp);
08510          if (debug)
08511             ast_verbose("Peer doesn't provide video\n");
08512       }
08513    }
08514 
08515    /* Setup text address and port */
08516    if (p->trtp) {
08517       if (tportno > 0) {
08518          tsin.sin_family = AF_INET;
08519          tsin.sin_port = htons(tportno);
08520          memcpy(&tsin.sin_addr, thp->h_addr, sizeof(tsin.sin_addr));
08521          ast_rtp_set_peer(p->trtp, &tsin);
08522          if (debug) 
08523             ast_verbose("Peer T.140 RTP is at port %s:%d\n", ast_inet_ntoa(tsin.sin_addr), ntohs(tsin.sin_port));
08524          if ((p->jointcapability & AST_FORMAT_T140RED)) {
08525             p->red = 1;
08526             rtp_red_init(p->trtp, 300, red_data_pt, 2);
08527          } else {
08528             p->red = 0;
08529          }
08530          ast_rtp_pt_copy(p->trtp, newtextrtp);
08531       } else {
08532          ast_rtp_stop(p->trtp);
08533          if (debug)
08534             ast_verbose("Peer doesn't provide T.140\n");
08535       }
08536    }
08537    /* Setup image address and port */
08538    if (p->udptl) {
08539       if (udptlportno > 0) {
08540          isin.sin_family = AF_INET;
08541          isin.sin_port = htons(udptlportno);
08542          if (ast_test_flag(&p->flags[0], SIP_NAT) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
08543             struct sockaddr_in remote_address = { 0, };
08544             ast_rtp_get_peer(p->rtp, &remote_address);
08545             if (remote_address.sin_addr.s_addr) {
08546                memcpy(&isin, &remote_address, sizeof(isin));
08547                if (debug) {
08548                   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));
08549                }
08550             }
08551          } else {
08552             memcpy(&isin.sin_addr, ihp->h_addr, sizeof(isin.sin_addr));
08553          }
08554          ast_udptl_set_peer(p->udptl, &isin);
08555          if (debug)
08556             ast_debug(1,"Peer T.38 UDPTL is at port %s:%d\n", ast_inet_ntoa(isin.sin_addr), ntohs(isin.sin_port));
08557 
08558          /* verify the far max ifp can be calculated. this requires far max datagram to be set. */
08559          if (!ast_udptl_get_far_max_datagram(p->udptl)) {
08560             /* setting to zero will force a default if none was provided by the SDP */
08561             ast_udptl_set_far_max_datagram(p->udptl, 0);
08562          }
08563 
08564          /* Remote party offers T38, we need to update state */
08565          if ((t38action == SDP_T38_ACCEPT) &&
08566              (p->t38.state == T38_LOCAL_REINVITE)) {
08567             change_t38_state(p, T38_ENABLED);
08568          } else if ((t38action == SDP_T38_INITIATE) &&
08569                p->owner && p->lastinvite) {
08570             change_t38_state(p, T38_PEER_REINVITE); /* T38 Offered in re-invite from remote party */
08571             /* If fax detection is enabled then send us off to the fax extension */
08572             if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38)) {
08573                ast_channel_lock(p->owner);
08574                if (strcmp(p->owner->exten, "fax")) {
08575                   const char *target_context = S_OR(p->owner->macrocontext, p->owner->context);
08576                   ast_channel_unlock(p->owner);
08577                   if (ast_exists_extension(p->owner, target_context, "fax", 1, p->owner->cid.cid_num)) {
08578                      ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to peer T.38 re-INVITE\n", p->owner->name);
08579                      pbx_builtin_setvar_helper(p->owner, "FAXEXTEN", p->owner->exten);
08580                      if (ast_async_goto(p->owner, target_context, "fax", 1)) {
08581                         ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", p->owner->name, target_context);
08582                      }
08583                   } else {
08584                      ast_log(LOG_NOTICE, "T.38 re-INVITE detected but no fax extension\n");
08585                   }
08586                } else {
08587                   ast_channel_unlock(p->owner);
08588                }
08589             }
08590          }
08591       } else {
08592          ast_udptl_stop(p->udptl);
08593          if (debug)
08594             ast_debug(1, "Peer doesn't provide T.38 UDPTL\n");
08595       }
08596    }
08597 
08598    if ((portno == -1) && (p->t38.state != T38_DISABLED)) {
08599       ast_debug(3, "Have T.38 but no audio, accepting offer anyway\n");
08600                 return 0;
08601         }
08602 
08603    /* Ok, we're going with this offer */
08604    ast_debug(2, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcapability));
08605 
08606    if (!p->owner)    /* There's no open channel owning us so we can return here. For a re-invite or so, we proceed */
08607       return 0;
08608 
08609    ast_debug(4, "We have an owner, now see if we need to change this call\n");
08610 
08611    if (!(p->owner->nativeformats & p->jointcapability) && (p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
08612       if (debug) {
08613          char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
08614          ast_debug(1, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n", 
08615             ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcapability),
08616             ast_getformatname_multiple(s2, SIPBUFSIZE, p->owner->nativeformats));
08617       }
08618       p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability) | (p->capability & tpeercapability);
08619       ast_set_read_format(p->owner, p->owner->readformat);
08620       ast_set_write_format(p->owner, p->owner->writeformat);
08621    }
08622    
08623    if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) && sin.sin_addr.s_addr && (!sendonly || sendonly == -1)) {
08624       ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
08625       /* Activate a re-invite */
08626       ast_queue_frame(p->owner, &ast_null_frame);
08627       /* Queue Manager Unhold event */
08628       append_history(p, "Unhold", "%s", req->data->str);
08629       if (sip_cfg.callevents)
08630          manager_event(EVENT_FLAG_CALL, "Hold",
08631                   "Status: Off\r\n"
08632                   "Channel: %s\r\n"
08633                   "Uniqueid: %s\r\n",
08634                   p->owner->name,
08635                   p->owner->uniqueid);
08636       if (sip_cfg.notifyhold)
08637          sip_peer_hold(p, FALSE);
08638       ast_clear_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD); /* Clear both flags */
08639    } else if (!sin.sin_addr.s_addr || (sendonly && sendonly != -1)) {
08640       int already_on_hold = ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD);
08641       ast_queue_control_data(p->owner, AST_CONTROL_HOLD, 
08642                    S_OR(p->mohsuggest, NULL),
08643                    !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
08644       if (sendonly)
08645          ast_rtp_stop(p->rtp);
08646       /* RTCP needs to go ahead, even if we're on hold!!! */
08647       /* Activate a re-invite */
08648       ast_queue_frame(p->owner, &ast_null_frame);
08649       /* Queue Manager Hold event */
08650       append_history(p, "Hold", "%s", req->data->str);
08651       if (sip_cfg.callevents && !ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
08652          manager_event(EVENT_FLAG_CALL, "Hold",
08653                   "Status: On\r\n"
08654                   "Channel: %s\r\n"
08655                   "Uniqueid: %s\r\n",
08656                   p->owner->name, 
08657                   p->owner->uniqueid);
08658       }
08659       if (sendonly == 1)   /* One directional hold (sendonly/recvonly) */
08660          ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
08661       else if (sendonly == 2) /* Inactive stream */
08662          ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
08663       else
08664          ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
08665       if (sip_cfg.notifyhold && !already_on_hold)
08666          sip_peer_hold(p, TRUE);
08667    }
08668    
08669    return 0;
08670 }
08671 
08672 static int process_sdp_o(const char *o, struct sip_pvt *p)
08673 {
08674    char *o_copy;
08675    char *token;
08676    int64_t rua_version;
08677 
08678    /* Store the SDP version number of remote UA. This will allow us to
08679    distinguish between session modifications and session refreshes. If
08680    the remote UA does not send an incremented SDP version number in a
08681    subsequent RE-INVITE then that means its not changing media session.
08682    The RE-INVITE may have been sent to update connected party, remote
08683    target or to refresh the session (Session-Timers).  Asterisk must not
08684    change media session and increment its own version number in answer
08685    SDP in this case. */
08686 
08687    p->session_modify = TRUE;
08688 
08689    if (ast_strlen_zero(o)) {
08690       ast_log(LOG_WARNING, "SDP syntax error. SDP without an o= line\n");
08691       return FALSE;
08692    }
08693 
08694    o_copy = ast_strdupa(o);
08695    token = strsep(&o_copy, " ");  /* Skip username   */
08696    if (!o_copy) {
08697       ast_log(LOG_WARNING, "SDP syntax error in o= line username\n");
08698       return FALSE;
08699    }
08700    token = strsep(&o_copy, " ");  /* Skip session-id */
08701    if (!o_copy) {
08702       ast_log(LOG_WARNING, "SDP syntax error in o= line session-id\n");
08703       return FALSE;
08704    }
08705    token = strsep(&o_copy, " ");  /* Version         */
08706    if (!o_copy) {
08707       ast_log(LOG_WARNING, "SDP syntax error in o= line\n");
08708       return FALSE;
08709    }
08710    if (!sscanf(token, "%30" SCNd64, &rua_version)) {
08711       ast_log(LOG_WARNING, "SDP syntax error in o= line version\n");
08712       return FALSE;
08713    }
08714 
08715    /* we need to check the SDP version number the other end sent us;
08716     * our rules for deciding what to accept are a bit complex.
08717     *
08718     * 1) if 'ignoresdpversion' has been set for this dialog, then
08719     *    we will just accept whatever they sent and assume it is
08720     *    a modification of the session, even if it is not
08721     * 2) otherwise, if this is the first SDP we've seen from them
08722     *    we accept it
08723     * 3) otherwise, if the new SDP version number is higher than the
08724     *    old one, we accept it
08725     * 4) otherwise, if this SDP is in response to us requesting a switch
08726     *    to T.38, we accept the SDP, but also generate a warning message
08727     *    that this peer should have the 'ignoresdpversion' option set,
08728     *    because it is not following the SDP offer/answer RFC; if we did
08729     *    not request a switch to T.38, then we stop parsing the SDP, as it
08730     *    has not changed from the previous version
08731     */
08732 
08733    if (ast_test_flag(&p->flags[1], SIP_PAGE2_IGNORESDPVERSION) ||
08734        (p->sessionversion_remote < 0) ||
08735        (p->sessionversion_remote < rua_version)) {
08736       p->sessionversion_remote = rua_version;
08737    } else {
08738       if (p->t38.state == T38_LOCAL_REINVITE) {
08739          p->sessionversion_remote = rua_version;
08740          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);
08741       } else {
08742          p->session_modify = FALSE;
08743          ast_debug(2, "Call %s responded to our reinvite without changing SDP version; ignoring SDP.\n", p->callid);
08744          return FALSE;
08745       }
08746    }
08747 
08748    return TRUE;
08749 }
08750 
08751 static int process_sdp_c(const char *c, struct ast_hostent *ast_hp)
08752 {
08753    char host[258];
08754    struct hostent *hp;
08755 
08756    /* Check for Media-description-level-address */
08757    if (sscanf(c, "IN IP4 %255s", host) != 1) {
08758       ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
08759       return FALSE;
08760    } else {
08761       if (!(hp = ast_gethostbyname(host, ast_hp))) {
08762          ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in c= line, '%s'\n", c);
08763          return FALSE;
08764       }
08765       return TRUE;
08766    }
08767    return FALSE;
08768 }
08769 
08770 static int process_sdp_a_sendonly(const char *a, int *sendonly)
08771 {
08772    int found = FALSE;
08773 
08774    if (!strcasecmp(a, "sendonly")) {
08775       if (*sendonly == -1)
08776          *sendonly = 1;
08777       found = TRUE;
08778    } else if (!strcasecmp(a, "inactive")) {
08779       if (*sendonly == -1)
08780          *sendonly = 2;
08781       found = TRUE;
08782    }  else if (!strcasecmp(a, "sendrecv")) {
08783       if (*sendonly == -1)
08784          *sendonly = 0;
08785       found = TRUE;
08786    }
08787    return found;
08788 }
08789 
08790 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp *newaudiortp, int *last_rtpmap_codec)
08791 {
08792    int found = FALSE;
08793    int codec;
08794    char mimeSubtype[128];
08795    char fmtp_string[64];
08796    unsigned int sample_rate;
08797    int debug = sip_debug_test_pvt(p);
08798 
08799    if (!strncasecmp(a, "ptime", 5)) {
08800       char *tmp = strrchr(a, ':');
08801       long int framing = 0;
08802       if (tmp) {
08803          tmp++;
08804          framing = strtol(tmp, NULL, 10);
08805          if (framing == LONG_MIN || framing == LONG_MAX) {
08806             framing = 0;
08807             ast_debug(1, "Can't read framing from SDP: %s\n", a);
08808          }
08809       }
08810       if (framing && p->autoframing) {
08811          struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
08812          int codec_n;
08813          int format = 0;
08814          for (codec_n = 0; codec_n < MAX_RTP_PT; codec_n++) {
08815             format = ast_rtp_codec_getformat(codec_n);
08816             if (!format)   /* non-codec or not found */
08817                continue;
08818             if (option_debug)
08819                ast_log(LOG_DEBUG, "Setting framing for %d to %ld\n", format, framing);
08820             ast_codec_pref_setsize(pref, format, framing);
08821          }
08822          ast_rtp_codec_setpref(p->rtp, pref);
08823       }
08824       found = TRUE;
08825    } else if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
08826       /* We have a rtpmap to handle */
08827       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
08828          if (ast_rtp_set_rtpmap_type_rate(newaudiortp, codec, "audio", mimeSubtype,
08829              ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0, sample_rate) != -1) {
08830             if (debug)
08831                ast_verbose("Found audio description format %s for ID %d\n", mimeSubtype, codec);
08832             //found_rtpmap_codecs[last_rtpmap_codec] = codec;
08833             (*last_rtpmap_codec)++;
08834             found = TRUE;
08835          } else {
08836             ast_rtp_unset_m_type(newaudiortp, codec);
08837             if (debug)
08838                ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
08839          }
08840       } else {
08841          if (debug)
08842             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
08843       }
08844    } else if (sscanf(a, "fmtp: %30u %63s", &codec, fmtp_string) == 2) {
08845       struct rtpPayloadType payload;
08846 
08847       payload = ast_rtp_lookup_pt(newaudiortp, codec);
08848       if (payload.code && payload.isAstFormat) {
08849          unsigned int bit_rate;
08850 
08851          switch (payload.code) {
08852          case AST_FORMAT_SIREN7:
08853             if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
08854                if (bit_rate != 32000) {
08855                   ast_log(LOG_WARNING, "Got Siren7 offer at %d bps, but only 32000 bps supported; ignoring.\n", bit_rate);
08856                   ast_rtp_unset_m_type(newaudiortp, codec);
08857                } else {
08858                   found = TRUE;
08859                }
08860             }
08861             break;
08862          case AST_FORMAT_SIREN14:
08863             if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
08864                if (bit_rate != 48000) {
08865                   ast_log(LOG_WARNING, "Got Siren14 offer at %d bps, but only 48000 bps supported; ignoring.\n", bit_rate);
08866                   ast_rtp_unset_m_type(newaudiortp, codec);
08867                } else {
08868                   found = TRUE;
08869                }
08870             }
08871             break;
08872          }
08873       }
08874    }
08875 
08876    return found;
08877 }
08878 
08879 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp *newvideortp, int *last_rtpmap_codec)
08880 {
08881    int found = FALSE;
08882    int codec;
08883    char mimeSubtype[128];
08884    unsigned int sample_rate;
08885    int debug = sip_debug_test_pvt(p);
08886 
08887    if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
08888       /* We have a rtpmap to handle */
08889       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
08890          /* Note: should really look at the '#chans' params too */
08891          if (!strncasecmp(mimeSubtype, "H26", 3) || !strncasecmp(mimeSubtype, "MP4", 3)) {
08892             if (ast_rtp_set_rtpmap_type_rate(newvideortp, codec, "video", mimeSubtype, 0, sample_rate) != -1) {
08893                if (debug)
08894                   ast_verbose("Found video description format %s for ID %d\n", mimeSubtype, codec);
08895                //found_rtpmap_codecs[last_rtpmap_codec] = codec;
08896                (*last_rtpmap_codec)++;
08897                found = TRUE;
08898             } else {
08899                ast_rtp_unset_m_type(newvideortp, codec);
08900                if (debug) 
08901                   ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
08902             }
08903          }
08904       } else {
08905          if (debug)
08906             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
08907       }
08908    }
08909 
08910    return found;
08911 }
08912 
08913 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)
08914 {
08915    int found = FALSE;
08916    int codec;
08917    char mimeSubtype[128];
08918    unsigned int sample_rate;
08919    char *red_cp;
08920    int debug = sip_debug_test_pvt(p);
08921 
08922    if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
08923       /* We have a rtpmap to handle */
08924       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
08925          if (!strncasecmp(mimeSubtype, "T140", 4)) { /* Text */
08926             if (p->trtp) {
08927                /* ast_verbose("Adding t140 mimeSubtype to textrtp struct\n"); */
08928                ast_rtp_set_rtpmap_type(newtextrtp, codec, "text", mimeSubtype, 0);
08929                found = TRUE;
08930             }
08931          } else if (!strncasecmp(mimeSubtype, "RED", 3)) { /* Text with Redudancy */
08932             if (p->trtp) {
08933                ast_rtp_set_rtpmap_type(newtextrtp, codec, "text", mimeSubtype, 0);
08934                sprintf(red_fmtp, "fmtp:%d ", codec); 
08935                if (debug)
08936                   ast_verbose("RED submimetype has payload type: %d\n", codec);
08937                found = TRUE;
08938             }
08939          }
08940       } else {
08941          if (debug)
08942             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
08943       }
08944    } else if (!strncmp(a, red_fmtp, strlen(red_fmtp))) {
08945       /* count numbers of generations in fmtp */
08946       red_cp = &red_fmtp[strlen(red_fmtp)];
08947       strncpy(red_fmtp, a, 100);
08948 
08949       sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
08950       red_cp = strtok(red_cp, "/");
08951       while (red_cp && (*red_num_gen)++ < RED_MAX_GENERATION) {
08952          sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
08953          red_cp = strtok(NULL, "/");
08954       }
08955       red_cp = red_fmtp;
08956       found = TRUE;
08957    }
08958 
08959    return found;
08960 }
08961 
08962 static int process_sdp_a_image(const char *a, struct sip_pvt *p)
08963 {
08964    int found = FALSE;
08965    char s[256];
08966    unsigned int x;
08967 
08968    if ((sscanf(a, "T38FaxMaxBuffer:%30u", &x) == 1)) {
08969       ast_debug(3, "MaxBufferSize:%d\n", x);
08970       found = TRUE;
08971    } else if ((sscanf(a, "T38MaxBitRate:%30u", &x) == 1) || (sscanf(a, "T38FaxMaxRate:%30u", &x) == 1)) {
08972       ast_debug(3, "T38MaxBitRate: %d\n", x);
08973       switch (x) {
08974       case 14400:
08975          p->t38.their_parms.rate = AST_T38_RATE_14400;
08976          break;
08977       case 12000:
08978          p->t38.their_parms.rate = AST_T38_RATE_12000;
08979          break;
08980       case 9600:
08981          p->t38.their_parms.rate = AST_T38_RATE_9600;
08982          break;
08983       case 7200:
08984          p->t38.their_parms.rate = AST_T38_RATE_7200;
08985          break;
08986       case 4800:
08987          p->t38.their_parms.rate = AST_T38_RATE_4800;
08988          break;
08989       case 2400:
08990          p->t38.their_parms.rate = AST_T38_RATE_2400;
08991          break;
08992       }
08993       found = TRUE;
08994    } else if ((sscanf(a, "T38FaxVersion:%30u", &x) == 1)) {
08995       ast_debug(3, "FaxVersion: %u\n", x);
08996       p->t38.their_parms.version = x;
08997       found = TRUE;
08998    } else if ((sscanf(a, "T38FaxMaxDatagram:%30u", &x) == 1) || (sscanf(a, "T38MaxDatagram:%30u", &x) == 1)) {
08999       /* override the supplied value if the configuration requests it */
09000       if (((signed int) p->t38_maxdatagram >= 0) && ((unsigned int) p->t38_maxdatagram > x)) {
09001          ast_debug(1, "Overriding T38FaxMaxDatagram '%d' with '%d'\n", x, p->t38_maxdatagram);
09002          x = p->t38_maxdatagram;
09003       }
09004       ast_debug(3, "FaxMaxDatagram: %u\n", x);
09005       ast_udptl_set_far_max_datagram(p->udptl, x);
09006       found = TRUE;
09007    } else if ((strncmp(a, "T38FaxFillBitRemoval", 20) == 0)) {
09008       if (sscanf(a, "T38FaxFillBitRemoval:%30u", &x) == 1) {
09009          ast_debug(3, "FillBitRemoval: %d\n", x);
09010          if (x == 1) {
09011             p->t38.their_parms.fill_bit_removal = TRUE;
09012          }
09013       } else {
09014          ast_debug(3, "FillBitRemoval\n");
09015          p->t38.their_parms.fill_bit_removal = TRUE;
09016       }
09017       found = TRUE;
09018    } else if ((strncmp(a, "T38FaxTranscodingMMR", 20) == 0)) {
09019       if (sscanf(a, "T38FaxTranscodingMMR:%30u", &x) == 1) {
09020          ast_debug(3, "Transcoding MMR: %d\n", x);
09021          if (x == 1) {
09022             p->t38.their_parms.transcoding_mmr = TRUE;
09023          }
09024       } else {
09025          ast_debug(3, "Transcoding MMR\n");
09026          p->t38.their_parms.transcoding_mmr = TRUE;
09027       }
09028       found = TRUE;
09029    } else if ((strncmp(a, "T38FaxTranscodingJBIG", 21) == 0)) {
09030       if (sscanf(a, "T38FaxTranscodingJBIG:%30u", &x) == 1) {
09031          ast_debug(3, "Transcoding JBIG: %d\n", x);
09032          if (x == 1) {
09033             p->t38.their_parms.transcoding_jbig = TRUE;
09034          }
09035       } else {
09036          ast_debug(3, "Transcoding JBIG\n");
09037          p->t38.their_parms.transcoding_jbig = TRUE;
09038       }
09039       found = TRUE;
09040    } else if ((sscanf(a, "T38FaxRateManagement:%255s", s) == 1)) {
09041       ast_debug(3, "RateManagement: %s\n", s);
09042       if (!strcasecmp(s, "localTCF"))
09043          p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_LOCAL_TCF;
09044       else if (!strcasecmp(s, "transferredTCF"))
09045          p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF;
09046       found = TRUE;
09047    } else if ((sscanf(a, "T38FaxUdpEC:%255s", s) == 1)) {
09048       ast_debug(3, "UDP EC: %s\n", s);
09049       if (!strcasecmp(s, "t38UDPRedundancy")) {
09050          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
09051       } else if (!strcasecmp(s, "t38UDPFEC")) {
09052          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
09053       } else {
09054          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
09055       }
09056       found = TRUE;
09057    }
09058 
09059    return found;
09060 }
09061 
09062 
09063 #ifdef LOW_MEMORY
09064 static void ts_ast_rtp_destroy(void *data)
09065 {
09066     struct ast_rtp *tmp = data;
09067     ast_rtp_destroy(tmp);
09068 }
09069 #endif
09070 
09071 /*! \brief Add header to SIP message */
09072 static int add_header(struct sip_request *req, const char *var, const char *value)
09073 {
09074    if (req->headers == SIP_MAX_HEADERS) {
09075       ast_log(LOG_WARNING, "Out of SIP header space\n");
09076       return -1;
09077    }
09078 
09079    if (req->lines) {
09080       ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
09081       return -1;
09082    }
09083 
09084    if (sip_cfg.compactheaders) {
09085       var = find_alias(var, var);
09086    }
09087 
09088    ast_str_append(&req->data, 0, "%s: %s\r\n", var, value);
09089    req->header[req->headers] = req->len;
09090 
09091    req->len = ast_str_strlen(req->data);
09092    req->headers++;
09093 
09094    return 0;   
09095 }
09096 
09097 /*! \brief Add 'Content-Length' header and content to SIP message */
09098 static int finalize_content(struct sip_request *req)
09099 {
09100    char clen[10];
09101 
09102    if (req->lines) {
09103       ast_log(LOG_WARNING, "finalize_content() called on a message that has already been finalized\n");
09104       return -1;
09105    }
09106 
09107    snprintf(clen, sizeof(clen), "%zd", ast_str_strlen(req->content));
09108    add_header(req, "Content-Length", clen);
09109 
09110    if (ast_str_strlen(req->content)) {
09111       ast_str_append(&req->data, 0, "\r\n%s", ast_str_buffer(req->content));
09112       req->len = ast_str_strlen(req->data);
09113    }
09114    req->lines = ast_str_strlen(req->content) ? 1 : 0;
09115    return 0;
09116 }
09117 
09118 /*! \brief Add content (not header) to SIP message */
09119 static int add_content(struct sip_request *req, const char *line)
09120 {
09121    if (req->lines) {
09122       ast_log(LOG_WARNING, "Can't add more content when the content has been finalized\n");
09123       return -1;
09124    }
09125 
09126    ast_str_append(&req->content, 0, "%s", line);
09127    return 0;
09128 }
09129 
09130 /*! \brief Copy one header field from one request to another */
09131 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
09132 {
09133    const char *tmp = get_header(orig, field);
09134 
09135    if (!ast_strlen_zero(tmp)) /* Add what we're responding to */
09136       return add_header(req, field, tmp);
09137    ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
09138    return -1;
09139 }
09140 
09141 /*! \brief Copy all headers from one request to another */
09142 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
09143 {
09144    int start = 0;
09145    int copied = 0;
09146    for (;;) {
09147       const char *tmp = __get_header(orig, field, &start);
09148 
09149       if (ast_strlen_zero(tmp))
09150          break;
09151       /* Add what we're responding to */
09152       add_header(req, field, tmp);
09153       copied++;
09154    }
09155    return copied ? 0 : -1;
09156 }
09157 
09158 /*! \brief Copy SIP VIA Headers from the request to the response
09159 \note If the client indicates that it wishes to know the port we received from,
09160    it adds ;rport without an argument to the topmost via header. We need to
09161    add the port number (from our point of view) to that parameter.
09162 \verbatim
09163    We always add ;received=<ip address> to the topmost via header.
09164 \endverbatim
09165    Received: RFC 3261, rport RFC 3581 */
09166 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
09167 {
09168    int copied = 0;
09169    int start = 0;
09170 
09171    for (;;) {
09172       char new[512];
09173       const char *oh = __get_header(orig, field, &start);
09174 
09175       if (ast_strlen_zero(oh))
09176          break;
09177 
09178       if (!copied) { /* Only check for empty rport in topmost via header */
09179          char leftmost[512], *others, *rport;
09180 
09181          /* Only work on leftmost value */
09182          ast_copy_string(leftmost, oh, sizeof(leftmost));
09183          others = strchr(leftmost, ',');
09184          if (others)
09185              *others++ = '\0';
09186 
09187          /* Find ;rport;  (empty request) */
09188          rport = strstr(leftmost, ";rport");
09189          if (rport && *(rport+6) == '=') 
09190             rport = NULL;     /* We already have a parameter to rport */
09191 
09192          /* Check rport if NAT=yes or NAT=rfc3581 (which is the default setting)  */
09193          if (rport && ((ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_ALWAYS) || (ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_RFC3581))) {
09194             /* We need to add received port - rport */
09195             char *end;
09196 
09197             rport = strstr(leftmost, ";rport");
09198 
09199             if (rport) {
09200                end = strchr(rport + 1, ';');
09201                if (end)
09202                   memmove(rport, end, strlen(end) + 1);
09203                else
09204                   *rport = '\0';
09205             }
09206 
09207             /* Add rport to first VIA header if requested */
09208             snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
09209                leftmost, ast_inet_ntoa(p->recv.sin_addr),
09210                ntohs(p->recv.sin_port),
09211                others ? "," : "", others ? others : "");
09212          } else {
09213             /* We should *always* add a received to the topmost via */
09214             snprintf(new, sizeof(new), "%s;received=%s%s%s",
09215                leftmost, ast_inet_ntoa(p->recv.sin_addr),
09216                others ? "," : "", others ? others : "");
09217          }
09218          oh = new;   /* the header to copy */
09219       }  /* else add the following via headers untouched */
09220       add_header(req, field, oh);
09221       copied++;
09222    }
09223    if (!copied) {
09224       ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
09225       return -1;
09226    }
09227    return 0;
09228 }
09229 
09230 /*! \brief Add route header into request per learned route */
09231 static void add_route(struct sip_request *req, struct sip_route *route)
09232 {
09233    char r[SIPBUFSIZE*2], *p;
09234    int n, rem = sizeof(r);
09235 
09236    if (!route)
09237       return;
09238 
09239    p = r;
09240    for (;route ; route = route->next) {
09241       n = strlen(route->hop);
09242       if (rem < n+3) /* we need room for ",<route>" */
09243          break;
09244       if (p != r) {  /* add a separator after fist route */
09245          *p++ = ',';
09246          --rem;
09247       }
09248       *p++ = '<';
09249       ast_copy_string(p, route->hop, rem); /* cannot fail */
09250       p += n;
09251       *p++ = '>';
09252       rem -= (n+2);
09253    }
09254    *p = '\0';
09255    add_header(req, "Route", r);
09256 }
09257 
09258 /*! \brief Set destination from SIP URI 
09259  *
09260  * Parse uri to h (host) and port - uri is already just the part inside the <> 
09261  * general form we are expecting is sip[s]:username[:password][;parameter]@host[:port][;...] 
09262  * If there's a port given, turn NAPTR/SRV off. NAPTR might indicate SIPS preference even
09263  * for SIP: uri's
09264  *
09265  * If there's a sips: uri scheme, TLS will be required. 
09266  */
09267 static void set_destination(struct sip_pvt *p, char *uri)
09268 {
09269    char *h, *maddr, hostname[256];
09270    int port, hn;
09271    struct hostent *hp;
09272    struct ast_hostent ahp;
09273    int debug=sip_debug_test_pvt(p);
09274    int tls_on = FALSE;
09275    int use_dns = sip_cfg.srvlookup;
09276 
09277    if (debug)
09278       ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
09279 
09280    /* Find and parse hostname */
09281    h = strchr(uri, '@');
09282    if (h)
09283       ++h;
09284    else {
09285       h = uri;
09286       if (!strncasecmp(h, "sip:", 4)) {
09287          h += 4;
09288       } else if (!strncasecmp(h, "sips:", 5)) {
09289          h += 5;
09290          tls_on = TRUE;
09291       }
09292    }
09293    hn = strcspn(h, ":;>") + 1;
09294    if (hn > sizeof(hostname)) 
09295       hn = sizeof(hostname);
09296    ast_copy_string(hostname, h, hn);
09297    /* XXX bug here if string has been trimmed to sizeof(hostname) */
09298    h += hn - 1;
09299 
09300    /* Is "port" present? if not default to STANDARD_SIP_PORT */
09301    if (*h == ':') {
09302       /* Parse port */
09303       ++h;
09304       port = strtol(h, &h, 10);
09305       use_dns = FALSE;
09306    } else
09307       port = tls_on ? STANDARD_TLS_PORT : STANDARD_SIP_PORT;
09308 
09309    /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
09310    maddr = strstr(h, "maddr=");
09311    if (maddr) {
09312       maddr += 6;
09313       hn = strspn(maddr, "0123456789.") + 1;
09314       if (hn > sizeof(hostname))
09315          hn = sizeof(hostname);
09316       ast_copy_string(hostname, maddr, hn);
09317    }
09318 
09319    /*! \todo XXX If we have use_dns on, then look for NAPTR/SRV, otherwise, just look for A records */
09320    
09321    hp = ast_gethostbyname(hostname, &ahp);
09322    if (hp == NULL)  {
09323       ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
09324       return;
09325    }
09326    p->sa.sin_family = AF_INET;
09327    memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
09328    p->sa.sin_port = htons(port);
09329    if (debug)
09330       ast_verbose("set_destination: set destination to %s, port %d\n", ast_inet_ntoa(p->sa.sin_addr), port);
09331 }
09332 
09333 /*! \brief Initialize SIP response, based on SIP request */
09334 static int init_resp(struct sip_request *resp, const char *msg)
09335 {
09336    /* Initialize a response */
09337    memset(resp, 0, sizeof(*resp));
09338    resp->method = SIP_RESPONSE;
09339    if (!(resp->data = ast_str_create(SIP_MIN_PACKET)))
09340       goto e_return;
09341    if (!(resp->content = ast_str_create(SIP_MIN_PACKET)))
09342       goto e_free_data;
09343    resp->header[0] = 0;
09344    ast_str_set(&resp->data, 0, "SIP/2.0 %s\r\n", msg);
09345    resp->len = resp->data->used;
09346    resp->headers++;
09347    return 0;
09348 
09349 e_free_data:
09350    ast_free(resp->data);
09351    resp->data = NULL;
09352 e_return:
09353    return -1;
09354 }
09355 
09356 /*! \brief Initialize SIP request */
09357 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
09358 {
09359    /* Initialize a request */
09360    memset(req, 0, sizeof(*req));
09361    if (!(req->data = ast_str_create(SIP_MIN_PACKET)))
09362       goto e_return;
09363    if (!(req->content = ast_str_create(SIP_MIN_PACKET)))
09364       goto e_free_data;
09365    req->method = sipmethod;
09366    req->header[0] = 0;
09367    ast_str_set(&req->data, 0, "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
09368    req->len = ast_str_strlen(req->data);
09369    req->headers++;
09370    return 0;
09371 
09372 e_free_data:
09373    ast_free(req->data);
09374    req->data = NULL;
09375 e_return:
09376    return -1;
09377 }
09378 
09379 /*! \brief Deinitialize SIP response/request */
09380 static void deinit_req(struct sip_request *req)
09381 {
09382    if (req->data) {
09383       ast_free(req->data);
09384       req->data = NULL;
09385    }
09386    if (req->content) {
09387       ast_free(req->content);
09388       req->content = NULL;
09389    }
09390 }
09391 
09392 
09393 /*! \brief Test if this response needs a contact header */
09394 static inline int resp_needs_contact(const char *msg, enum sipmethod method) {
09395    /* Requirements for Contact header inclusion in responses generated
09396     * from the header tables found in the following RFCs.  Where the
09397     * Contact header was marked mandatory (m) or optional (o) this
09398     * function returns 1.
09399     *
09400     * - RFC 3261 (ACK, BYE, CANCEL, INVITE, OPTIONS, REGISTER)
09401     * - RFC 2976 (INFO)
09402     * - RFC 3262 (PRACK)
09403     * - RFC 3265 (SUBSCRIBE, NOTIFY)
09404     * - RFC 3311 (UPDATE)
09405     * - RFC 3428 (MESSAGE)
09406     * - RFC 3515 (REFER)
09407     * - RFC 3903 (PUBLISH)
09408     */
09409 
09410    switch (method) {
09411       /* 1xx, 2xx, 3xx, 485 */
09412       case SIP_INVITE:
09413       case SIP_UPDATE:
09414       case SIP_SUBSCRIBE:
09415       case SIP_NOTIFY:
09416          if ((msg[0] >= '1' && msg[0] <= '3') || !strncmp(msg, "485", 3))
09417             return 1;
09418          break;
09419 
09420       /* 2xx, 3xx, 485 */
09421       case SIP_REGISTER:
09422       case SIP_OPTIONS:
09423          if (msg[0] == '2' || msg[0] == '3' || !strncmp(msg, "485", 3))
09424             return 1;
09425          break;
09426 
09427       /* 3xx, 485 */
09428       case SIP_BYE:
09429       case SIP_PRACK:
09430       case SIP_MESSAGE:
09431       case SIP_PUBLISH:
09432          if (msg[0] == '3' || !strncmp(msg, "485", 3))
09433             return 1;
09434          break;
09435 
09436       /* 2xx, 3xx, 4xx, 5xx, 6xx */
09437       case SIP_REFER:
09438          if (msg[0] >= '2' && msg[0] <= '6')
09439             return 1;
09440          break;
09441 
09442       /* contact will not be included for everything else */
09443       case SIP_ACK:
09444       case SIP_CANCEL:
09445       case SIP_INFO:
09446       case SIP_PING:
09447       default:
09448          return 0;
09449    }
09450    return 0;
09451 }
09452 
09453 /*! \brief Prepare SIP response packet */
09454 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
09455 {
09456    char newto[256];
09457    const char *ot;
09458 
09459    init_resp(resp, msg);
09460    copy_via_headers(p, resp, req, "Via");
09461    if (msg[0] == '1' || msg[0] == '2')
09462       copy_all_header(resp, req, "Record-Route");
09463    copy_header(resp, req, "From");
09464    ot = get_header(req, "To");
09465    if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
09466       /* Add the proper tag if we don't have it already.  If they have specified
09467          their tag, use it.  Otherwise, use our own tag */
09468       if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
09469          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
09470       else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
09471          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
09472       else
09473          ast_copy_string(newto, ot, sizeof(newto));
09474       ot = newto;
09475    }
09476    add_header(resp, "To", ot);
09477    copy_header(resp, req, "Call-ID");
09478    copy_header(resp, req, "CSeq");
09479    if (!ast_strlen_zero(global_useragent))
09480       add_header(resp, "Server", global_useragent);
09481    add_header(resp, "Allow", ALLOWED_METHODS);
09482    add_header(resp, "Supported", SUPPORTED_EXTENSIONS);
09483 
09484    /* If this is an invite, add Session-Timers related headers if the feature is active for this session */
09485    if (p->method == SIP_INVITE && p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE) {
09486       char se_hdr[256];
09487       snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval, 
09488          strefresher2str(p->stimer->st_ref));
09489       add_header(resp, "Require", "timer");
09490       add_header(resp, "Session-Expires", se_hdr);
09491    }
09492 
09493    if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
09494       /* For registration responses, we also need expiry and
09495          contact info */
09496       char tmp[256];
09497 
09498       snprintf(tmp, sizeof(tmp), "%d", p->expiry);
09499       add_header(resp, "Expires", tmp);
09500       if (p->expiry) {  /* Only add contact if we have an expiry time */
09501          char contact[SIPBUFSIZE];
09502          const char *contact_uri = p->method == SIP_SUBSCRIBE ? p->our_contact : p->fullcontact;
09503          char *brackets = strchr(contact_uri, '<');
09504          snprintf(contact, sizeof(contact), "%s%s%s;expires=%d", brackets ? "" : "<", contact_uri, brackets ? "" : ">", p->expiry);
09505          add_header(resp, "Contact", contact);  /* Not when we unregister */
09506       }
09507    } else if (!ast_strlen_zero(p->our_contact) && resp_needs_contact(msg, p->method)) {
09508       add_header(resp, "Contact", p->our_contact);
09509    }
09510 
09511    if (!ast_strlen_zero(p->url)) {
09512       add_header(resp, "Access-URL", p->url);
09513       ast_string_field_set(p, url, NULL);
09514    }
09515 
09516    return 0;
09517 }
09518 
09519 /*! \brief Initialize a SIP request message (not the initial one in a dialog) */
09520 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch)
09521 {
09522    struct sip_request *orig = &p->initreq;
09523    char stripped[80];
09524    char tmp[80];
09525    char newto[256];
09526    const char *c;
09527    const char *ot, *of;
09528    int is_strict = FALSE;     /*!< Strict routing flag */
09529    int is_outbound = ast_test_flag(&p->flags[0], SIP_OUTGOING);   /* Session direction */
09530 
09531    memset(req, 0, sizeof(struct sip_request));
09532    
09533    snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
09534    
09535    if (!seqno) {
09536       p->ocseq++;
09537       seqno = p->ocseq;
09538    }
09539    
09540    /* A CANCEL must have the same branch as the INVITE that it is canceling. */
09541    if (sipmethod == SIP_CANCEL) {
09542       p->branch = p->invite_branch;
09543       build_via(p);
09544    } else if (newbranch && (sipmethod == SIP_INVITE)) {
09545       p->branch ^= ast_random();
09546       p->invite_branch = p->branch;
09547       build_via(p);
09548    } else if (newbranch) {
09549       p->branch ^= ast_random();
09550       build_via(p);
09551    }
09552 
09553    /* Check for strict or loose router */
09554    if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop, ";lr") == NULL) {
09555       is_strict = TRUE;
09556       if (sipdebug)
09557          ast_debug(1, "Strict routing enforced for session %s\n", p->callid);
09558    }
09559    
09560    if (sipmethod == SIP_CANCEL)
09561       c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2); /* Use original URI */
09562    else if (sipmethod == SIP_ACK) {
09563       /* Use URI from Contact: in 200 OK (if INVITE) 
09564       (we only have the contacturi on INVITEs) */
09565       if (!ast_strlen_zero(p->okcontacturi))
09566          c = is_strict ? p->route->hop : p->okcontacturi;
09567       else
09568          c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
09569    } else if (!ast_strlen_zero(p->okcontacturi)) 
09570       c = is_strict ? p->route->hop : p->okcontacturi; /* Use for BYE or REINVITE */
09571    else if (!ast_strlen_zero(p->uri)) 
09572       c = p->uri;
09573    else {
09574       char *n;
09575       /* We have no URI, use To: or From:  header as URI (depending on direction) */
09576       ast_copy_string(stripped, get_header(orig, is_outbound ? "To" : "From"),
09577             sizeof(stripped));
09578       n = get_in_brackets(stripped);
09579       c = remove_uri_parameters(n);
09580    }  
09581    init_req(req, sipmethod, c);
09582 
09583    snprintf(tmp, sizeof(tmp), "%d %s", seqno, sip_methods[sipmethod].text);
09584 
09585    add_header(req, "Via", p->via);
09586    if (p->route) {
09587       set_destination(p, p->route->hop);
09588       add_route(req, is_strict ? p->route->next : p->route);
09589    }
09590    add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
09591 
09592    ot = get_header(orig, "To");
09593    of = get_header(orig, "From");
09594 
09595    /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
09596       as our original request, including tag (or presumably lack thereof) */
09597    if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
09598       /* Add the proper tag if we don't have it already.  If they have specified
09599          their tag, use it.  Otherwise, use our own tag */
09600       if (is_outbound && !ast_strlen_zero(p->theirtag))
09601          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
09602       else if (!is_outbound)
09603          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
09604       else
09605          snprintf(newto, sizeof(newto), "%s", ot);
09606       ot = newto;
09607    }
09608 
09609    if (is_outbound) {
09610       add_header(req, "From", of);
09611       add_header(req, "To", ot);
09612    } else {
09613       add_header(req, "From", ot);
09614       add_header(req, "To", of);
09615    }
09616    /* Do not add Contact for MESSAGE, BYE and Cancel requests */
09617    if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
09618       add_header(req, "Contact", p->our_contact);
09619 
09620    copy_header(req, orig, "Call-ID");
09621    add_header(req, "CSeq", tmp);
09622 
09623    if (!ast_strlen_zero(global_useragent))
09624       add_header(req, "User-Agent", global_useragent);
09625 
09626    if (!ast_strlen_zero(p->rpid))
09627       add_header(req, "Remote-Party-ID", p->rpid);
09628 
09629    if (!ast_strlen_zero(p->url)) {
09630       add_header(req, "Access-URL", p->url);
09631       ast_string_field_set(p, url, NULL);
09632    }
09633 
09634    /* Add Session-Timers related headers if the feature is active for this session.
09635       An exception to this behavior is the ACK request. Since Asterisk never requires 
09636       session-timers support from a remote end-point (UAS) in an INVITE, it must 
09637       not send 'Require: timer' header in the ACK request. 
09638       This should only be added in the INVITE transactions, not MESSAGE or REFER or other
09639       in-dialog messages.
09640    */
09641    if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE 
09642        && sipmethod == SIP_INVITE) {
09643       char se_hdr[256];
09644       snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval, 
09645          strefresher2str(p->stimer->st_ref));
09646       add_header(req, "Require", "timer");
09647       add_header(req, "Session-Expires", se_hdr);
09648       snprintf(se_hdr, sizeof(se_hdr), "%d", st_get_se(p, FALSE));
09649       add_header(req, "Min-SE", se_hdr);
09650    }
09651 
09652    return 0;
09653 }
09654 
09655 /*! \brief Base transmit response function */
09656 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
09657 {
09658    struct sip_request resp;
09659    int seqno = 0;
09660 
09661    if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
09662       ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
09663       return -1;
09664    }
09665    respprep(&resp, p, msg, req);
09666    /* If we are cancelling an incoming invite for some reason, add information
09667       about the reason why we are doing this in clear text */
09668    if (p->method == SIP_INVITE && msg[0] != '1' && p->owner && p->owner->hangupcause) {
09669       char buf[10];
09670 
09671       add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
09672       snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
09673       add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
09674    }
09675    return send_response(p, &resp, reliable, seqno);
09676 }
09677 
09678 static int temp_pvt_init(void *data)
09679 {
09680    struct sip_pvt *p = data;
09681 
09682    p->do_history = 0;   /* XXX do we need it ? isn't already all 0 ? */
09683    return ast_string_field_init(p, 512);
09684 }
09685 
09686 static void temp_pvt_cleanup(void *data)
09687 {
09688    struct sip_pvt *p = data;
09689 
09690    ast_string_field_free_memory(p);
09691 
09692    ast_free(data);
09693 }
09694 
09695 /*! \brief Transmit response, no retransmits, using a temporary pvt structure */
09696 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)
09697 {
09698    struct sip_pvt *p = NULL;
09699 
09700    if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
09701       ast_log(LOG_ERROR, "Failed to get temporary pvt\n");
09702       return -1;
09703    }
09704 
09705    /* XXX the structure may be dirty from previous usage.
09706     * Here we should state clearly how we should reinitialize it
09707     * before using it.
09708     * E.g. certainly the threadstorage should be left alone,
09709     * but other thihngs such as flags etc. maybe need cleanup ?
09710     */
09711     
09712    /* Initialize the bare minimum */
09713    p->method = intended_method;
09714 
09715    if (!sin)
09716       p->ourip = internip;
09717    else {
09718       p->sa = *sin;
09719       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
09720    }
09721 
09722    p->branch = ast_random();
09723    make_our_tag(p->tag, sizeof(p->tag));
09724    p->ocseq = INITIAL_CSEQ;
09725 
09726    if (useglobal_nat && sin) {
09727       ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
09728       p->recv = *sin;
09729       do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
09730    }
09731 
09732    ast_string_field_set(p, fromdomain, default_fromdomain);
09733    build_via(p);
09734    ast_string_field_set(p, callid, callid);
09735 
09736    copy_socket_data(&p->socket, &req->socket);
09737 
09738    /* Use this temporary pvt structure to send the message */
09739    __transmit_response(p, msg, req, XMIT_UNRELIABLE);
09740 
09741    /* Free the string fields, but not the pool space */
09742    ast_string_field_init(p, 0);
09743 
09744    return 0;
09745 }
09746 
09747 /*! \brief Transmit response, no retransmits */
09748 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req) 
09749 {
09750    return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
09751 }
09752 
09753 /*! \brief Transmit response, no retransmits */
09754 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported) 
09755 {
09756    struct sip_request resp;
09757    respprep(&resp, p, msg, req);
09758    append_date(&resp);
09759    add_header(&resp, "Unsupported", unsupported);
09760    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
09761 }
09762 
09763 /*! \brief Transmit 422 response with Min-SE header (Session-Timers)  */
09764 static int transmit_response_with_minse(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minse_int)
09765 {
09766    struct sip_request resp;
09767    char minse_str[20];
09768 
09769    respprep(&resp, p, msg, req);
09770    append_date(&resp);
09771 
09772    snprintf(minse_str, sizeof(minse_str), "%d", minse_int);
09773    add_header(&resp, "Min-SE", minse_str);
09774    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
09775 }
09776 
09777 
09778 /*! \brief Transmit response, Make sure you get an ACK
09779    This is only used for responses to INVITEs, where we need to make sure we get an ACK
09780 */
09781 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
09782 {
09783    return __transmit_response(p, msg, req, req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL);
09784 }
09785 
09786 /*! \brief Append date to SIP message */
09787 static void append_date(struct sip_request *req)
09788 {
09789    char tmpdat[256];
09790    struct tm tm;
09791    time_t t = time(NULL);
09792 
09793    gmtime_r(&t, &tm);
09794    strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
09795    add_header(req, "Date", tmpdat);
09796 }
09797 
09798 /*! \brief Append date and content length before transmitting response */
09799 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
09800 {
09801    struct sip_request resp;
09802    respprep(&resp, p, msg, req);
09803    append_date(&resp);
09804    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
09805 }
09806 
09807 /*! \brief Append Accept header, content length before transmitting response */
09808 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
09809 {
09810    struct sip_request resp;
09811    respprep(&resp, p, msg, req);
09812    add_header(&resp, "Accept", "application/sdp");
09813    return send_response(p, &resp, reliable, 0);
09814 }
09815 
09816 /*! \brief Respond with authorization request */
09817 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)
09818 {
09819    struct sip_request resp;
09820    char tmp[512];
09821    int seqno = 0;
09822 
09823    if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
09824       ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
09825       return -1;
09826    }
09827    /* Stale means that they sent us correct authentication, but 
09828       based it on an old challenge (nonce) */
09829    snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", sip_cfg.realm, randdata, stale ? ", stale=true" : "");
09830    respprep(&resp, p, msg, req);
09831    add_header(&resp, header, tmp);
09832    append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
09833    return send_response(p, &resp, reliable, seqno);
09834 }
09835 
09836 /* Only use a static string for the msg, here! */
09837 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp)
09838 {
09839    int res;
09840 
09841    if (!(res = with_sdp ? transmit_response_with_sdp(p, msg, req, XMIT_UNRELIABLE, FALSE) : transmit_response(p, msg, req))) {
09842       p->last_provisional = msg;
09843       update_provisional_keepalive(p, with_sdp);
09844    }
09845 
09846    return res;
09847 }
09848 
09849 /*! \brief Add text body to SIP message */
09850 static int add_text(struct sip_request *req, const char *text)
09851 {
09852    /* XXX Convert \n's to \r\n's XXX */
09853    add_header(req, "Content-Type", "text/plain;charset=UTF-8");
09854    add_content(req, text);
09855    return 0;
09856 }
09857 
09858 /*! \brief Add DTMF INFO tone to sip message 
09859    Mode =   0 for application/dtmf-relay (Cisco)
09860       1 for application/dtmf
09861 */
09862 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode)
09863 {
09864    char tmp[256];
09865    int event;
09866    if (mode) {
09867       /* Application/dtmf short version used by some implementations */
09868       if (digit == '*')
09869          event = 10;
09870       else if (digit == '#')
09871          event = 11;
09872       else if ((digit >= 'A') && (digit <= 'D'))
09873          event = 12 + digit - 'A';
09874       else
09875          event = atoi(&digit);
09876       snprintf(tmp, sizeof(tmp), "%d\r\n", event);
09877       add_header(req, "Content-Type", "application/dtmf");
09878       add_content(req, tmp);
09879    } else {
09880       /* Application/dtmf-relay as documented by Cisco */
09881       snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
09882       add_header(req, "Content-Type", "application/dtmf-relay");
09883       add_content(req, tmp);
09884    }
09885    return 0;
09886 }
09887 
09888 /*! \brief add XML encoded media control with update 
09889    \note XML: The only way to turn 0 bits of information into a few hundred. (markster) */
09890 static int add_vidupdate(struct sip_request *req)
09891 {
09892    const char *xml_is_a_huge_waste_of_space =
09893       "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
09894       " <media_control>\r\n"
09895       "  <vc_primitive>\r\n"
09896       "   <to_encoder>\r\n"
09897       "    <picture_fast_update>\r\n"
09898       "    </picture_fast_update>\r\n"
09899       "   </to_encoder>\r\n"
09900       "  </vc_primitive>\r\n"
09901       " </media_control>\r\n";
09902    add_header(req, "Content-Type", "application/media_control+xml");
09903    add_content(req, xml_is_a_huge_waste_of_space);
09904    return 0;
09905 }
09906 
09907 /*! \brief Add codec offer to SDP offer/answer body in INVITE or 200 OK */
09908 static void add_codec_to_sdp(const struct sip_pvt *p, int codec,
09909               struct ast_str **m_buf, struct ast_str **a_buf,
09910               int debug, int *min_packet_size)
09911 {
09912    int rtp_code;
09913    struct ast_format_list fmt;
09914 
09915 
09916    if (debug)
09917       ast_verbose("Adding codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
09918    if ((rtp_code = ast_rtp_lookup_code(p->rtp, 1, codec)) == -1)
09919       return;
09920 
09921    if (p->rtp) {
09922       struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
09923       fmt = ast_codec_pref_getsize(pref, codec);
09924    } 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 */
09925       return;
09926    ast_str_append(m_buf, 0, " %d", rtp_code);
09927    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
09928              ast_rtp_lookup_mime_subtype(1, codec,
09929                      ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
09930              ast_rtp_lookup_sample_rate(1, codec));
09931 
09932    switch (codec) {
09933    case AST_FORMAT_G729A:
09934       /* Indicate that we don't support VAD (G.729 annex B) */
09935       ast_str_append(a_buf, 0, "a=fmtp:%d annexb=no\r\n", rtp_code);
09936       break;
09937    case AST_FORMAT_G723_1:
09938       /* Indicate that we don't support VAD (G.723.1 annex A) */
09939       ast_str_append(a_buf, 0, "a=fmtp:%d annexa=no\r\n", rtp_code);
09940       break;
09941    case AST_FORMAT_ILBC:
09942       /* Add information about us using only 20/30 ms packetization */
09943       ast_str_append(a_buf, 0, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
09944       break;
09945    case AST_FORMAT_SIREN7:
09946       /* Indicate that we only expect 32Kbps */
09947       ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=32000\r\n", rtp_code);
09948       break;
09949    case AST_FORMAT_SIREN14:
09950       /* Indicate that we only expect 48Kbps */
09951       ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=48000\r\n", rtp_code);
09952       break;
09953    }
09954 
09955    if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
09956       *min_packet_size = fmt.cur_ms;
09957 
09958    /* Our first codec packetization processed cannot be zero */
09959    if ((*min_packet_size)==0 && fmt.cur_ms)
09960       *min_packet_size = fmt.cur_ms;
09961 }
09962 
09963 /*! \brief Add video codec offer to SDP offer/answer body in INVITE or 200 OK */
09964 /* This is different to the audio one now so we can add more caps later */
09965 static void add_vcodec_to_sdp(const struct sip_pvt *p, int codec,
09966               struct ast_str **m_buf, struct ast_str **a_buf,
09967               int debug, int *min_packet_size)
09968 {
09969    int rtp_code;
09970 
09971    if (!p->vrtp)
09972       return;
09973 
09974    if (debug)
09975       ast_verbose("Adding video codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
09976 
09977    if ((rtp_code = ast_rtp_lookup_code(p->vrtp, 1, codec)) == -1)
09978       return;
09979 
09980    ast_str_append(m_buf, 0, " %d", rtp_code);
09981    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
09982              ast_rtp_lookup_mime_subtype(1, codec, 0),
09983              ast_rtp_lookup_sample_rate(1, codec));
09984    /* Add fmtp code here */
09985 }
09986 
09987 /*! \brief Add text codec offer to SDP offer/answer body in INVITE or 200 OK */
09988 static void add_tcodec_to_sdp(const struct sip_pvt *p, int codec,
09989               struct ast_str **m_buf, struct ast_str **a_buf,
09990               int debug, int *min_packet_size)
09991 {
09992    int rtp_code;
09993 
09994    if (!p->trtp)
09995       return;
09996 
09997    if (debug)
09998       ast_verbose("Adding text codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
09999 
10000    if ((rtp_code = ast_rtp_lookup_code(p->trtp, 1, codec)) == -1)
10001       return;
10002 
10003    ast_str_append(m_buf, 0, " %d", rtp_code);
10004    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10005              ast_rtp_lookup_mime_subtype(1, codec, 0),
10006              ast_rtp_lookup_sample_rate(1, codec));
10007    /* Add fmtp code here */
10008 
10009    if (codec == AST_FORMAT_T140RED) {
10010       ast_str_append(a_buf, 0, "a=fmtp:%d %d/%d/%d\r\n", rtp_code,
10011           ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140),
10012           ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140),
10013           ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140));
10014 
10015    }
10016 }
10017 
10018 
10019 /*! \brief Get Max T.38 Transmission rate from T38 capabilities */
10020 static unsigned int t38_get_rate(enum ast_control_t38_rate rate)
10021 {
10022    switch (rate) {
10023    case AST_T38_RATE_2400:
10024       return 2400;
10025    case AST_T38_RATE_4800:
10026       return 4800;
10027    case AST_T38_RATE_7200:
10028       return 7200;
10029    case AST_T38_RATE_9600:
10030       return 9600;
10031    case AST_T38_RATE_12000:
10032       return 12000;
10033    case AST_T38_RATE_14400:
10034       return 14400;
10035    default:
10036       return 0;
10037    }
10038 }
10039 
10040 /*! \brief Add RFC 2833 DTMF offer to SDP */
10041 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
10042             struct ast_str **m_buf, struct ast_str **a_buf,
10043             int debug)
10044 {
10045    int rtp_code;
10046 
10047    if (debug)
10048       ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype(0, format, 0));
10049    if ((rtp_code = ast_rtp_lookup_code(p->rtp, 0, format)) == -1)
10050       return;
10051 
10052    ast_str_append(m_buf, 0, " %d", rtp_code);
10053    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10054              ast_rtp_lookup_mime_subtype(0, format, 0),
10055              ast_rtp_lookup_sample_rate(0, format));
10056    if (format == AST_RTP_DTMF)   /* Indicate we support DTMF and FLASH... */
10057       ast_str_append(a_buf, 0, "a=fmtp:%d 0-16\r\n", rtp_code);
10058 }
10059 
10060 /*! \brief Set all IP media addresses for this call 
10061    \note called from add_sdp()
10062 */
10063 static void get_our_media_address(struct sip_pvt *p, int needvideo,
10064    struct sockaddr_in *sin, struct sockaddr_in *vsin, struct sockaddr_in *tsin,
10065    struct sockaddr_in *dest, struct sockaddr_in *vdest)
10066 {
10067    /* First, get our address */
10068    ast_rtp_get_us(p->rtp, sin);
10069    if (p->vrtp)
10070       ast_rtp_get_us(p->vrtp, vsin);
10071    if (p->trtp)
10072       ast_rtp_get_us(p->trtp, tsin);
10073 
10074    /* Now, try to figure out where we want them to send data */
10075    /* Is this a re-invite to move the media out, then use the original offer from caller  */
10076    if (p->redirip.sin_addr.s_addr) {   /* If we have a redirection IP, use it */
10077       dest->sin_port = p->redirip.sin_port;
10078       dest->sin_addr = p->redirip.sin_addr;
10079    } else {
10080       dest->sin_addr = p->ourip.sin_addr;
10081       dest->sin_port = sin->sin_port;
10082    }
10083    if (needvideo) {
10084       /* Determine video destination */
10085       if (p->vredirip.sin_addr.s_addr) {
10086          vdest->sin_addr = p->vredirip.sin_addr;
10087          vdest->sin_port = p->vredirip.sin_port;
10088       } else {
10089          vdest->sin_addr = p->ourip.sin_addr;
10090          vdest->sin_port = vsin->sin_port;
10091       }
10092    }
10093 
10094 }
10095 
10096 /*! \brief Add Session Description Protocol message 
10097 
10098     If oldsdp is TRUE, then the SDP version number is not incremented. This mechanism
10099     is used in Session-Timers where RE-INVITEs are used for refreshing SIP sessions 
10100     without modifying the media session in any way. 
10101 */
10102 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38)
10103 {
10104    int alreadysent = 0;
10105 
10106    struct sockaddr_in sin;
10107    struct sockaddr_in vsin;
10108    struct sockaddr_in tsin;
10109    struct sockaddr_in dest;
10110    struct sockaddr_in udptlsin;
10111    struct sockaddr_in vdest = { 0, };
10112    struct sockaddr_in tdest = { 0, };
10113    struct sockaddr_in udptldest = { 0, };
10114 
10115    /* SDP fields */
10116    char *version =   "v=0\r\n";     /* Protocol version */
10117    char subject[256];            /* Subject of the session */
10118    char owner[256];           /* Session owner/creator */
10119    char connection[256];            /* Connection data */
10120    char *session_time = "t=0 0\r\n";         /* Time the session is active */
10121    char bandwidth[256] = "";        /* Max bitrate */
10122    char *hold = "";
10123    struct ast_str *m_audio = ast_str_alloca(256);  /* Media declaration line for audio */
10124    struct ast_str *m_video = ast_str_alloca(256);  /* Media declaration line for video */
10125    struct ast_str *m_text = ast_str_alloca(256);   /* Media declaration line for text */
10126    struct ast_str *m_modem = ast_str_alloca(256);  /* Media declaration line for modem */
10127    struct ast_str *a_audio = ast_str_alloca(1024); /* Attributes for audio */
10128    struct ast_str *a_video = ast_str_alloca(1024); /* Attributes for video */
10129    struct ast_str *a_text = ast_str_alloca(1024);  /* Attributes for text */
10130    struct ast_str *a_modem = ast_str_alloca(1024); /* Attributes for modem */
10131 
10132    int x;
10133    int capability = 0;
10134    int needaudio = FALSE;
10135    int needvideo = FALSE;
10136    int needtext = FALSE;
10137    int debug = sip_debug_test_pvt(p);
10138    int min_audio_packet_size = 0;
10139    int min_video_packet_size = 0;
10140    int min_text_packet_size = 0;
10141 
10142    char codecbuf[SIPBUFSIZE];
10143    char buf[SIPBUFSIZE];
10144    char dummy_answer[256];
10145 
10146    /* Set the SDP session name */
10147    snprintf(subject, sizeof(subject), "s=%s\r\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
10148 
10149    if (!p->rtp) {
10150       ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
10151       return AST_FAILURE;
10152    }
10153    /* XXX We should not change properties in the SIP dialog until 
10154       we have acceptance of the offer if this is a re-invite */
10155 
10156    /* Set RTP Session ID and version */
10157    if (!p->sessionid) {
10158       p->sessionid = (int)ast_random();
10159       p->sessionversion = p->sessionid;
10160    } else {
10161       if (oldsdp == FALSE)
10162          p->sessionversion++;
10163    }
10164 
10165    if (add_audio) {
10166       /* Check if we need video in this call */
10167       if ((p->jointcapability & AST_FORMAT_VIDEO_MASK) && !p->novideo) {
10168          if (p->vrtp) {
10169             needvideo = TRUE;
10170             ast_debug(2, "This call needs video offers!\n");
10171          } else
10172             ast_debug(2, "This call needs video offers, but there's no video support enabled!\n");
10173       }
10174       /* Check if we need text in this call */
10175       if ((p->jointcapability & AST_FORMAT_TEXT_MASK) && !p->notext) {
10176          if (sipdebug_text)
10177             ast_verbose("We think we can do text\n");
10178          if (p->trtp) {
10179             if (sipdebug_text) {
10180                ast_verbose("And we have a text rtp object\n");
10181             }
10182             needtext = TRUE;
10183             ast_debug(2, "This call needs text offers! \n");
10184          } else {
10185             ast_debug(2, "This call needs text offers, but there's no text support enabled ! \n");
10186          }
10187       }
10188    }
10189 
10190    get_our_media_address(p, needvideo, &sin, &vsin, &tsin, &dest, &vdest);
10191 
10192    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));
10193    snprintf(connection, sizeof(connection), "c=IN IP4 %s\r\n", ast_inet_ntoa(dest.sin_addr));
10194 
10195    if (add_audio) {
10196       capability = p->jointcapability;
10197 
10198       /* XXX note, Video and Text are negated - 'true' means 'no' */
10199       ast_debug(1, "** Our capability: %s Video flag: %s Text flag: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability), 
10200            p->novideo ? "True" : "False", p->notext ? "True" : "False");
10201       ast_debug(1, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));
10202 
10203       /* Check if we need audio */
10204       if (capability & AST_FORMAT_AUDIO_MASK)
10205          needaudio = TRUE;
10206 
10207       if (debug) 
10208          ast_verbose("Audio is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(sin.sin_port)); 
10209 
10210       /* Ok, we need video. Let's add what we need for video and set codecs.
10211          Video is handled differently than audio since we can not transcode. */
10212       if (needvideo) {
10213          ast_str_append(&m_video, 0, "m=video %d RTP/AVP", ntohs(vdest.sin_port));
10214 
10215          /* Build max bitrate string */
10216          if (p->maxcallbitrate)
10217             snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
10218          if (debug) 
10219             ast_verbose("Video is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(vdest.sin_port));  
10220       }
10221 
10222       /* Ok, we need text. Let's add what we need for text and set codecs.
10223          Text is handled differently than audio since we can not transcode. */
10224       if (needtext) {
10225          if (sipdebug_text)
10226             ast_verbose("Lets set up the text sdp\n");
10227          /* Determine text destination */
10228          if (p->tredirip.sin_addr.s_addr) {
10229             tdest.sin_addr = p->tredirip.sin_addr;
10230             tdest.sin_port = p->tredirip.sin_port;
10231          } else {
10232             tdest.sin_addr = p->ourip.sin_addr;
10233             tdest.sin_port = tsin.sin_port;
10234          }
10235          ast_str_append(&m_text, 0, "m=text %d RTP/AVP", ntohs(tdest.sin_port));
10236          if (debug) /* XXX should I use tdest below ? */
10237             ast_verbose("Text is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(tsin.sin_port)); 
10238 
10239       }
10240 
10241       /* Start building generic SDP headers */
10242 
10243       /* We break with the "recommendation" and send our IP, in order that our
10244          peer doesn't have to ast_gethostbyname() us */
10245 
10246       ast_str_append(&m_audio, 0, "m=audio %d RTP/AVP", ntohs(dest.sin_port));
10247 
10248       if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR)
10249          hold = "a=recvonly\r\n";
10250       else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE)
10251          hold = "a=inactive\r\n";
10252       else
10253          hold = "a=sendrecv\r\n";
10254 
10255       /* Now, start adding audio codecs. These are added in this order:
10256          - First what was requested by the calling channel
10257          - Then preferences in order from sip.conf device config for this peer/user
10258          - Then other codecs in capabilities, including video
10259       */
10260 
10261       /* Prefer the audio codec we were requested to use, first, no matter what 
10262          Note that p->prefcodec can include video codecs, so mask them out
10263       */
10264       if (capability & p->prefcodec) {
10265          int codec = p->prefcodec & AST_FORMAT_AUDIO_MASK;
10266 
10267          add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
10268          alreadysent |= codec;
10269       }
10270 
10271       /* Start by sending our preferred audio/video codecs */
10272       for (x = 0; x < 32; x++) {
10273          int codec;
10274 
10275          if (!(codec = ast_codec_pref_index(&p->prefs, x)))
10276             break; 
10277 
10278          if (!(capability & codec))
10279             continue;
10280 
10281          if (alreadysent & codec)
10282             continue;
10283 
10284          add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
10285          alreadysent |= codec;
10286       }
10287 
10288       /* Now send any other common audio and video codecs, and non-codec formats: */
10289       for (x = 1; x <= (needtext ? AST_FORMAT_TEXT_MASK : (needvideo ? AST_FORMAT_VIDEO_MASK : AST_FORMAT_AUDIO_MASK)); x <<= 1) {
10290          if (!(capability & x))  /* Codec not requested */
10291             continue;
10292 
10293          if (alreadysent & x) /* Already added to SDP */
10294             continue;
10295 
10296          if (x & AST_FORMAT_AUDIO_MASK)
10297             add_codec_to_sdp(p, x, &m_audio, &a_audio, debug, &min_audio_packet_size);
10298          else if (x & AST_FORMAT_VIDEO_MASK)
10299             add_vcodec_to_sdp(p, x, &m_video, &a_video, debug, &min_video_packet_size);
10300          else if (x & AST_FORMAT_TEXT_MASK)
10301             add_tcodec_to_sdp(p, x, &m_text, &a_text, debug, &min_text_packet_size);
10302       }
10303 
10304       /* Now add DTMF RFC2833 telephony-event as a codec */
10305       for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
10306          if (!(p->jointnoncodeccapability & x))
10307             continue;
10308 
10309          add_noncodec_to_sdp(p, x, &m_audio, &a_audio, debug);
10310       }
10311 
10312       ast_debug(3, "-- Done with adding codecs to SDP\n");
10313 
10314       if (!p->owner || !ast_internal_timing_enabled(p->owner))
10315          ast_str_append(&a_audio, 0, "a=silenceSupp:off - - - -\r\n");
10316 
10317       if (min_audio_packet_size)
10318          ast_str_append(&a_audio, 0, "a=ptime:%d\r\n", min_audio_packet_size);
10319 
10320       /* XXX don't think you can have ptime for video */
10321       if (min_video_packet_size)
10322          ast_str_append(&a_video, 0, "a=ptime:%d\r\n", min_video_packet_size);
10323 
10324       /* XXX don't think you can have ptime for text */
10325       if (min_text_packet_size)
10326          ast_str_append(&a_text, 0, "a=ptime:%d\r\n", min_text_packet_size);
10327  
10328       if (m_audio->len - m_audio->used < 2 || m_video->len - m_video->used < 2 ||
10329           m_text->len - m_text->used < 2 || a_text->len - a_text->used < 2 ||
10330           a_audio->len - a_audio->used < 2 || a_video->len - a_video->used < 2)
10331          ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
10332    }
10333 
10334    if (add_t38) {
10335       /* Our T.38 end is */
10336       ast_udptl_get_us(p->udptl, &udptlsin);
10337 
10338       /* Determine T.38 UDPTL destination */
10339       if (p->udptlredirip.sin_addr.s_addr) {
10340          udptldest.sin_port = p->udptlredirip.sin_port;
10341          udptldest.sin_addr = p->udptlredirip.sin_addr;
10342       } else {
10343          udptldest.sin_addr = p->ourip.sin_addr;
10344          udptldest.sin_port = udptlsin.sin_port;
10345       }
10346 
10347       if (debug)
10348          ast_debug(1, "T.38 UDPTL is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(udptlsin.sin_port));
10349 
10350       /* We break with the "recommendation" and send our IP, in order that our
10351          peer doesn't have to ast_gethostbyname() us */
10352 
10353       ast_str_append(&m_modem, 0, "m=image %d udptl t38\r\n", ntohs(udptldest.sin_port));
10354 
10355       ast_str_append(&a_modem, 0, "a=T38FaxVersion:%d\r\n", p->t38.our_parms.version);
10356       ast_str_append(&a_modem, 0, "a=T38MaxBitRate:%d\r\n", t38_get_rate(p->t38.our_parms.rate));
10357       if (p->t38.our_parms.fill_bit_removal) {
10358          ast_str_append(&a_modem, 0, "a=T38FaxFillBitRemoval\r\n");
10359       }
10360       if (p->t38.our_parms.transcoding_mmr) {
10361          ast_str_append(&a_modem, 0, "a=T38FaxTranscodingMMR\r\n");
10362       }
10363       if (p->t38.our_parms.transcoding_jbig) {
10364          ast_str_append(&a_modem, 0, "a=T38FaxTranscodingJBIG\r\n");
10365       }
10366       switch (p->t38.our_parms.rate_management) {
10367       case AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF:
10368          ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:transferredTCF\r\n");
10369          break;
10370       case AST_T38_RATE_MANAGEMENT_LOCAL_TCF:
10371          ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:localTCF\r\n");
10372          break;
10373       }
10374       ast_str_append(&a_modem, 0, "a=T38FaxMaxDatagram:%u\r\n", ast_udptl_get_local_max_datagram(p->udptl));
10375       switch (ast_udptl_get_error_correction_scheme(p->udptl)) {
10376       case UDPTL_ERROR_CORRECTION_NONE:
10377          break;
10378       case UDPTL_ERROR_CORRECTION_FEC:
10379          ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPFEC\r\n");
10380          break;
10381       case UDPTL_ERROR_CORRECTION_REDUNDANCY:
10382          ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPRedundancy\r\n");
10383          break;
10384       }
10385    }
10386 
10387    if (needaudio)
10388       ast_str_append(&m_audio, 0, "\r\n");
10389    if (needvideo)
10390       ast_str_append(&m_video, 0, "\r\n");
10391    if (needtext)
10392       ast_str_append(&m_text, 0, "\r\n");
10393 
10394    add_header(resp, "Content-Type", "application/sdp");
10395    add_content(resp, version);
10396    add_content(resp, owner);
10397    add_content(resp, subject);
10398    add_content(resp, connection);
10399    if (needvideo)    /* only if video response is appropriate */
10400       add_content(resp, bandwidth);
10401    add_content(resp, session_time);
10402    if (needaudio) {
10403       add_content(resp, m_audio->str);
10404       add_content(resp, a_audio->str);
10405       add_content(resp, hold);
10406    } else if (p->offered_media[SDP_AUDIO].offered) {
10407       snprintf(dummy_answer, sizeof(dummy_answer), "m=audio 0 RTP/AVP %s\r\n", p->offered_media[SDP_AUDIO].text);
10408       add_content(resp, dummy_answer);
10409    }
10410    if (needvideo) { /* only if video response is appropriate */
10411       add_content(resp, m_video->str);
10412       add_content(resp, a_video->str);
10413       add_content(resp, hold);   /* Repeat hold for the video stream */
10414    } else if (p->offered_media[SDP_VIDEO].offered) {
10415       snprintf(dummy_answer, sizeof(dummy_answer), "m=video 0 RTP/AVP %s\r\n", p->offered_media[SDP_VIDEO].text);
10416       add_content(resp, dummy_answer);
10417    }
10418    if (needtext) { /* only if text response is appropriate */
10419       add_content(resp, m_text->str);
10420       add_content(resp, a_text->str);
10421       add_content(resp, hold);   /* Repeat hold for the text stream */
10422    } else if (p->offered_media[SDP_TEXT].offered) {
10423       snprintf(dummy_answer, sizeof(dummy_answer), "m=text 0 RTP/AVP %s\r\n", p->offered_media[SDP_TEXT].text);
10424       add_content(resp, dummy_answer);
10425    }
10426    if (add_t38) {
10427       add_content(resp, m_modem->str);
10428       add_content(resp, a_modem->str);
10429    } else if (p->offered_media[SDP_IMAGE].offered) {
10430       add_content(resp, "m=image 0 udptl t38\r\n");
10431    }
10432 
10433    /* Update lastrtprx when we send our SDP */
10434    p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
10435 
10436    ast_debug(3, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, capability));
10437 
10438    return AST_SUCCESS;
10439 }
10440 
10441 /*! \brief Used for 200 OK and 183 early media */
10442 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
10443 {
10444    struct sip_request resp;
10445    int seqno;
10446    
10447    if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
10448       ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
10449       return -1;
10450    }
10451    respprep(&resp, p, msg, req);
10452    if (p->udptl) {
10453       add_sdp(&resp, p, 0, 0, 1);
10454    } else 
10455       ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
10456    if (retrans && !p->pendinginvite)
10457       p->pendinginvite = seqno;     /* Buggy clients sends ACK on RINGING too */
10458    return send_response(p, &resp, retrans, seqno);
10459 }
10460 
10461 /*! \brief copy SIP request (mostly used to save request for responses) */
10462 static void copy_request(struct sip_request *dst, const struct sip_request *src)
10463 {
10464    /* XXX this function can encounter memory allocation errors, perhaps it
10465     * should return a value */
10466 
10467    struct ast_str *duplicate = dst->data;
10468    struct ast_str *duplicate_content = dst->content;
10469 
10470    /* copy the entire request then restore the original data and content
10471     * members from the dst request */
10472    memcpy(dst, src, sizeof(*dst));
10473    dst->data = duplicate;
10474    dst->content = duplicate_content;
10475 
10476    /* copy the data into the dst request */
10477    if (!dst->data && !(dst->data = ast_str_create(ast_str_strlen(src->data) + 1)))
10478       return;
10479    ast_str_copy_string(&dst->data, src->data);
10480 
10481    /* copy the content into the dst request (if it exists) */
10482    if (src->content) {
10483       if (!dst->content && !(dst->content = ast_str_create(ast_str_strlen(src->content) + 1)))
10484          return;
10485       ast_str_copy_string(&dst->content, src->content);
10486    }
10487 }
10488 
10489 /*! \brief Used for 200 OK and 183 early media 
10490    \return Will return XMIT_ERROR for network errors.
10491 */
10492 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp)
10493 {
10494    struct sip_request resp;
10495    int seqno;
10496    if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
10497       ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
10498       return -1;
10499    }
10500    respprep(&resp, p, msg, req);
10501    if (p->rtp) {
10502       if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
10503          ast_debug(1, "Setting framing from config on incoming call\n");
10504          ast_rtp_codec_setpref(p->rtp, &p->prefs);
10505       }
10506       try_suggested_sip_codec(p);
10507       if (p->t38.state == T38_ENABLED) {
10508          add_sdp(&resp, p, oldsdp, TRUE, TRUE);
10509       } else {
10510          add_sdp(&resp, p, oldsdp, TRUE, FALSE);
10511       }
10512    } else 
10513       ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
10514    if (reliable && !p->pendinginvite)
10515       p->pendinginvite = seqno;     /* Buggy clients sends ACK on RINGING too */
10516    return send_response(p, &resp, reliable, seqno);
10517 }
10518 
10519 /*! \brief Parse first line of incoming SIP request */
10520 static int determine_firstline_parts(struct sip_request *req) 
10521 {
10522    char *e = ast_skip_blanks(req->data->str);   /* there shouldn't be any */
10523    char *local_rlPart1;
10524 
10525    if (!*e)
10526       return -1;
10527    req->rlPart1 = e - req->data->str;  /* method or protocol */
10528    local_rlPart1 = e;
10529    e = ast_skip_nonblanks(e);
10530    if (*e)
10531       *e++ = '\0';
10532    /* Get URI or status code */
10533    e = ast_skip_blanks(e);
10534    if ( !*e )
10535       return -1;
10536    ast_trim_blanks(e);
10537 
10538    if (!strcasecmp(local_rlPart1, "SIP/2.0") ) { /* We have a response */
10539       if (strlen(e) < 3)   /* status code is 3 digits */
10540          return -1;
10541       req->rlPart2 = e - req->data->str;
10542    } else { /* We have a request */
10543       if ( *e == '<' ) { /* XXX the spec says it must not be in <> ! */
10544          ast_debug(3, "Oops. Bogus uri in <> %s\n", e);
10545          e++;
10546          if (!*e)
10547             return -1; 
10548       }
10549       req->rlPart2 = e - req->data->str;  /* URI */
10550       e = ast_skip_nonblanks(e);
10551       if (*e)
10552          *e++ = '\0';
10553       e = ast_skip_blanks(e);
10554       if (strcasecmp(e, "SIP/2.0") ) {
10555          ast_debug(3, "Skipping packet - Bad request protocol %s\n", e);
10556          return -1;
10557       }
10558    }
10559    return 1;
10560 }
10561 
10562 /*! \brief Transmit reinvite with SDP
10563 \note    A re-invite is basically a new INVITE with the same CALL-ID and TAG as the
10564    INVITE that opened the SIP dialogue 
10565    We reinvite so that the audio stream (RTP) go directly between
10566    the SIP UAs. SIP Signalling stays with * in the path.
10567    
10568    If t38version is TRUE, we send T38 SDP for re-invite from audio/video to
10569    T38 UDPTL transmission on the channel
10570 
10571     If oldsdp is TRUE then the SDP version number is not incremented. This
10572     is needed for Session-Timers so we can send a re-invite to refresh the
10573     SIP session without modifying the media session. 
10574 */
10575 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp)
10576 {
10577    struct sip_request req;
10578    
10579    reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ?  SIP_UPDATE : SIP_INVITE, 0, 1);
10580 
10581    add_header(&req, "Allow", ALLOWED_METHODS);
10582    add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
10583    if (sipdebug) {
10584       if (oldsdp == TRUE)
10585          add_header(&req, "X-asterisk-Info", "SIP re-invite (Session-Timers)");
10586       else
10587          add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
10588    }
10589 
10590    if (p->do_history)
10591       append_history(p, "ReInv", "Re-invite sent");
10592    memset(p->offered_media, 0, sizeof(p->offered_media));
10593 
10594    if (t38version)
10595       add_sdp(&req, p, oldsdp, FALSE, TRUE);
10596    else
10597       add_sdp(&req, p, oldsdp, TRUE, FALSE);
10598 
10599    /* Use this as the basis */
10600    initialize_initreq(p, &req);
10601    p->lastinvite = p->ocseq;
10602    ast_set_flag(&p->flags[0], SIP_OUTGOING);       /* Change direction of this dialog */
10603 
10604    return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
10605 }
10606 
10607 /* \brief Remove URI parameters at end of URI, not in username part though */
10608 static char *remove_uri_parameters(char *uri)
10609 {
10610    char *atsign;
10611    atsign = strchr(uri, '@'); /* First, locate the at sign */
10612    if (!atsign)
10613       atsign = uri;  /* Ok hostname only, let's stick with the rest */
10614    atsign = strchr(atsign, ';'); /* Locate semi colon */
10615    if (atsign)
10616       *atsign = '\0';   /* Kill at the semi colon */
10617    return uri;
10618 }
10619 
10620 /*! \brief Check Contact: URI of SIP message */
10621 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
10622 {
10623    char stripped[SIPBUFSIZE];
10624    char *c;
10625 
10626    ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
10627    c = get_in_brackets(stripped);
10628    /* Cut the URI at the at sign after the @, not in the username part */
10629    c = remove_uri_parameters(c);
10630    if (!ast_strlen_zero(c))
10631       ast_string_field_set(p, uri, c);
10632 
10633 }
10634 
10635 /*! \brief Build contact header - the contact header we send out */
10636 static void build_contact(struct sip_pvt *p)
10637 {
10638 
10639    int ourport = ntohs(p->ourip.sin_port);
10640    /* only add port if it's non-standard for the transport type */
10641    if (!sip_standard_port(p->socket.type, ourport)) {
10642       if (p->socket.type == SIP_TRANSPORT_UDP)
10643          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);
10644       else
10645          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));
10646    } else {
10647       if (p->socket.type == SIP_TRANSPORT_UDP)
10648          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));
10649       else
10650          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));
10651    }
10652 }
10653 
10654 /*! \brief Build the Remote Party-ID & From using callingpres options */
10655 static void build_rpid(struct sip_pvt *p)
10656 {
10657    int send_pres_tags = TRUE;
10658    const char *privacy=NULL;
10659    const char *screen=NULL;
10660    char buf[256];
10661    const char *clid = default_callerid;
10662    const char *clin = NULL;
10663    const char *fromdomain;
10664 
10665    if (!ast_strlen_zero(p->rpid) || !ast_strlen_zero(p->rpid_from))  
10666       return;
10667 
10668    if (p->owner && !ast_strlen_zero(p->owner->cid.cid_num))
10669       clid = p->owner->cid.cid_num;
10670    if (p->owner && p->owner->cid.cid_name)
10671       clin = p->owner->cid.cid_name;
10672    if (ast_strlen_zero(clin))
10673       clin = clid;
10674 
10675    switch (p->callingpres) {
10676    case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
10677       privacy = "off";
10678       screen = "no";
10679       break;
10680    case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
10681       privacy = "off";
10682       screen = "yes";
10683       break;
10684    case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
10685       privacy = "off";
10686       screen = "no";
10687       break;
10688    case AST_PRES_ALLOWED_NETWORK_NUMBER:
10689       privacy = "off";
10690       screen = "yes";
10691       break;
10692    case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
10693       privacy = "full";
10694       screen = "no";
10695       break;
10696    case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
10697       privacy = "full";
10698       screen = "yes";
10699       break;
10700    case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
10701       privacy = "full";
10702       screen = "no";
10703       break;
10704    case AST_PRES_PROHIB_NETWORK_NUMBER:
10705       privacy = "full";
10706       screen = "yes";
10707       break;
10708    case AST_PRES_NUMBER_NOT_AVAILABLE:
10709       send_pres_tags = FALSE;
10710       break;
10711    default:
10712       ast_log(LOG_WARNING, "Unsupported callingpres (%d)\n", p->callingpres);
10713       if ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)
10714          privacy = "full";
10715       else
10716          privacy = "off";
10717       screen = "no";
10718       break;
10719    }
10720    
10721    fromdomain = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr));
10722 
10723    snprintf(buf, sizeof(buf), "\"%s\" <sip:%s@%s>", clin, clid, fromdomain);
10724    if (send_pres_tags)
10725       snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ";privacy=%s;screen=%s", privacy, screen);
10726    ast_string_field_set(p, rpid, buf);
10727 
10728    ast_string_field_build(p, rpid_from, "\"%s\" <sip:%s@%s>;tag=%s", clin,
10729                 S_OR(p->fromuser, clid),
10730                 fromdomain, p->tag);
10731 }
10732 
10733 /*! \brief Initiate new SIP request to peer/user */
10734 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod)
10735 {
10736    struct ast_str *invite = ast_str_alloca(256);
10737    char from[256];
10738    char to[256];
10739    char tmp_n[SIPBUFSIZE/2];  /* build a local copy of 'n' if needed */
10740    char tmp_l[SIPBUFSIZE/2];  /* build a local copy of 'l' if needed */
10741    const char *l = NULL;   /* XXX what is this, exactly ? */
10742    const char *n = NULL;   /* XXX what is this, exactly ? */
10743    const char *d = NULL;   /* domain in from header */
10744    const char *urioptions = "";
10745    int ourport;
10746 
10747    if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
10748       const char *s = p->username;  /* being a string field, cannot be NULL */
10749 
10750       /* Test p->username against allowed characters in AST_DIGIT_ANY
10751          If it matches the allowed characters list, then sipuser = ";user=phone"
10752          If not, then sipuser = ""
10753       */
10754       /* + is allowed in first position in a tel: uri */
10755       if (*s == '+')
10756          s++;
10757       for (; *s; s++) {
10758          if (!strchr(AST_DIGIT_ANYNUM, *s) )
10759             break;
10760       }
10761       /* If we have only digits, add ;user=phone to the uri */
10762       if (!*s)
10763          urioptions = ";user=phone";
10764    }
10765 
10766 
10767    snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
10768 
10769    d = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr));
10770    if (p->owner) {
10771       l = p->owner->cid.cid_num;
10772       n = p->owner->cid.cid_name;
10773    }
10774    /* if we are not sending RPID and user wants his callerid restricted */
10775    if (!ast_test_flag(&p->flags[0], SIP_SENDRPID) &&
10776        ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)) {
10777       l = CALLERID_UNKNOWN;
10778       n = l;
10779       d = FROMDOMAIN_INVALID;
10780    }
10781    if (ast_strlen_zero(l))
10782       l = default_callerid;
10783    if (ast_strlen_zero(n))
10784       n = l;
10785    /* Allow user to be overridden */
10786    if (!ast_strlen_zero(p->fromuser))
10787       l = p->fromuser;
10788    else /* Save for any further attempts */
10789       ast_string_field_set(p, fromuser, l);
10790 
10791    /* Allow user to be overridden */
10792    if (!ast_strlen_zero(p->fromname))
10793       n = p->fromname;
10794    else /* Save for any further attempts */
10795       ast_string_field_set(p, fromname, n);
10796 
10797    if (sip_cfg.pedanticsipchecking) {
10798       ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
10799       n = tmp_n;
10800       ast_uri_encode(l, tmp_l, sizeof(tmp_l), 0);
10801       l = tmp_l;
10802    }
10803 
10804    ourport = ntohs(p->ourip.sin_port);
10805    if (!sip_standard_port(p->socket.type, ourport) && ast_strlen_zero(p->fromdomain))
10806       snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=%s", n, l, d, ourport, p->tag);
10807    else
10808       snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, l, d, p->tag);
10809 
10810    /* If we're calling a registered SIP peer, use the fullcontact to dial to the peer */
10811    if (!ast_strlen_zero(p->fullcontact)) {
10812       /* If we have full contact, trust it */
10813       ast_str_append(&invite, 0, "%s", p->fullcontact);
10814    } else {
10815       /* Otherwise, use the username while waiting for registration */
10816       ast_str_append(&invite, 0, "sip:");
10817       if (!ast_strlen_zero(p->username)) {
10818          n = p->username;
10819          if (sip_cfg.pedanticsipchecking) {
10820             ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
10821             n = tmp_n;
10822          }
10823          ast_str_append(&invite, 0, "%s@", n);
10824       }
10825       ast_str_append(&invite, 0, "%s", p->tohost);
10826       if (p->portinuri)
10827          ast_str_append(&invite, 0, ":%d", ntohs(p->sa.sin_port));
10828       ast_str_append(&invite, 0, "%s", urioptions);
10829    }
10830 
10831    /* If custom URI options have been provided, append them */
10832    if (p->options && !ast_strlen_zero(p->options->uri_options))
10833       ast_str_append(&invite, 0, ";%s", p->options->uri_options);
10834    
10835    /* This is the request URI, which is the next hop of the call
10836       which may or may not be the destination of the call
10837    */
10838    ast_string_field_set(p, uri, invite->str);
10839   
10840    if (!ast_strlen_zero(p->todnid)) {
10841       /*! \todo Need to add back the VXML URL here at some point, possibly use build_string for all this junk */
10842       if (!strchr(p->todnid, '@')) {
10843          /* We have no domain in the dnid */
10844          snprintf(to, sizeof(to), "<sip:%s@%s>%s%s", p->todnid, p->tohost, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
10845       } else {
10846          snprintf(to, sizeof(to), "<sip:%s>%s%s", p->todnid, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
10847       }
10848    } else {
10849       if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) { 
10850          /* If this is a NOTIFY, use the From: tag in the subscribe (RFC 3265) */
10851          snprintf(to, sizeof(to), "<%s%s>;tag=%s", (strncasecmp(p->uri, "sip:", 4) ? "sip:" : ""), p->uri, p->theirtag);
10852       } else if (p->options && p->options->vxml_url) {
10853          /* If there is a VXML URL append it to the SIP URL */
10854          snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
10855       } else 
10856          snprintf(to, sizeof(to), "<%s>", p->uri);
10857    }
10858 
10859    init_req(req, sipmethod, p->uri);
10860    /* now tmp_n is available so reuse it to build the CSeq */
10861    snprintf(tmp_n, sizeof(tmp_n), "%d %s", ++p->ocseq, sip_methods[sipmethod].text);
10862 
10863    add_header(req, "Via", p->via);
10864    add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
10865    /* This will be a no-op most of the time. However, under certain circumstances,
10866     * NOTIFY messages will use this function for preparing the request and should
10867     * have Route headers present.
10868     */
10869    add_route(req, p->route);
10870 
10871    /* Build Remote Party-ID and From */
10872    if (ast_test_flag(&p->flags[0], SIP_SENDRPID) && (sipmethod == SIP_INVITE)) {
10873       build_rpid(p);
10874       add_header(req, "From", p->rpid_from);
10875    } else 
10876       add_header(req, "From", from);
10877    add_header(req, "To", to);
10878    ast_string_field_set(p, exten, l);
10879    build_contact(p);
10880    add_header(req, "Contact", p->our_contact);
10881    add_header(req, "Call-ID", p->callid);
10882    add_header(req, "CSeq", tmp_n);
10883    if (!ast_strlen_zero(global_useragent))
10884       add_header(req, "User-Agent", global_useragent);
10885    if (!ast_strlen_zero(p->rpid))
10886       add_header(req, "Remote-Party-ID", p->rpid);
10887 }
10888 
10889 /*! \brief Build REFER/INVITE/OPTIONS/SUBSCRIBE message and transmit it 
10890    \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
10891  \param p sip_pvt structure
10892  \param sdp unknown 
10893  \param sipmethod unknown 
10894  
10895 */
10896 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init)
10897 {
10898    struct sip_request req;
10899    struct ast_variable *var;
10900    
10901    req.method = sipmethod;
10902    if (init) {/* Bump branch even on initial requests */
10903       p->branch ^= ast_random();
10904       p->invite_branch = p->branch;
10905       build_via(p);
10906    }
10907    if (init > 1)
10908       initreqprep(&req, p, sipmethod);
10909    else
10910       /* If init=1, we should not generate a new branch. If it's 0, we need a new branch. */
10911       reqprep(&req, p, sipmethod, 0, init ? 0 : 1);
10912       
10913    if (p->options && p->options->auth)
10914       add_header(&req, p->options->authheader, p->options->auth);
10915    append_date(&req);
10916    if (sipmethod == SIP_REFER) { /* Call transfer */
10917       if (p->refer) {
10918          char buf[SIPBUFSIZE];
10919          if (!ast_strlen_zero(p->refer->refer_to))
10920             add_header(&req, "Refer-To", p->refer->refer_to);
10921          if (!ast_strlen_zero(p->refer->referred_by)) {
10922             snprintf(buf, sizeof(buf), "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
10923             add_header(&req, "Referred-By", buf);
10924          }
10925       }
10926    } else if (sipmethod == SIP_SUBSCRIBE) { /* We only support sending MWI subscriptions right now */
10927       char buf[SIPBUFSIZE];
10928 
10929       add_header(&req, "Event", "message-summary");
10930       add_header(&req, "Accept", "application/simple-message-summary");
10931       snprintf(buf, sizeof(buf), "%d", mwi_expiry);
10932       add_header(&req, "Expires", buf);
10933    }
10934 
10935    /* This new INVITE is part of an attended transfer. Make sure that the
10936    other end knows and replace the current call with this new call */
10937    if (p->options && !ast_strlen_zero(p->options->replaces)) {
10938       add_header(&req, "Replaces", p->options->replaces);
10939       add_header(&req, "Require", "replaces");
10940    }
10941 
10942    /* Add Session-Timers related headers */
10943    if (st_get_mode(p) == SESSION_TIMER_MODE_ORIGINATE) {
10944       char i2astr[10];
10945 
10946       if (!p->stimer->st_interval)
10947          p->stimer->st_interval = st_get_se(p, TRUE);
10948 
10949       p->stimer->st_active = TRUE;
10950       
10951       snprintf(i2astr, sizeof(i2astr), "%d", p->stimer->st_interval);
10952       add_header(&req, "Session-Expires", i2astr);
10953       snprintf(i2astr, sizeof(i2astr), "%d", st_get_se(p, FALSE));
10954       add_header(&req, "Min-SE", i2astr);
10955    }
10956 
10957    add_header(&req, "Allow", ALLOWED_METHODS);
10958    add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
10959 
10960    if(p->notify_headers) {
10961       char buf[512];
10962       for (var = p->notify_headers; var; var = var->next) {
10963          ast_copy_string(buf, var->value, sizeof(buf));
10964          add_header(&req, var->name, ast_unescape_semicolon(buf));
10965       }
10966    }
10967    if (p->options && p->options->addsipheaders && p->owner) {
10968       struct ast_channel *chan = p->owner; /* The owner channel */
10969       struct varshead *headp;
10970    
10971       ast_channel_lock(chan);
10972 
10973       headp = &chan->varshead;
10974 
10975       if (!headp)
10976          ast_log(LOG_WARNING, "No Headp for the channel...ooops!\n");
10977       else {
10978          const struct ast_var_t *current;
10979          AST_LIST_TRAVERSE(headp, current, entries) {  
10980             /* SIPADDHEADER: Add SIP header to outgoing call */
10981             if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
10982                char *content, *end;
10983                const char *header = ast_var_value(current);
10984                char *headdup = ast_strdupa(header);
10985 
10986                /* Strip of the starting " (if it's there) */
10987                if (*headdup == '"')
10988                   headdup++;
10989                if ((content = strchr(headdup, ':'))) {
10990                   *content++ = '\0';
10991                   content = ast_skip_blanks(content); /* Skip white space */
10992                   /* Strip the ending " (if it's there) */
10993                   end = content + strlen(content) -1; 
10994                   if (*end == '"')
10995                      *end = '\0';
10996                
10997                   add_header(&req, headdup, content);
10998                   if (sipdebug)
10999                      ast_debug(1, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
11000                }
11001             }
11002          }
11003       }
11004 
11005       ast_channel_unlock(chan);
11006    }
11007    if (sdp) {
11008       memset(p->offered_media, 0, sizeof(p->offered_media));
11009       if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
11010          ast_debug(1, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
11011          add_sdp(&req, p, FALSE, FALSE, TRUE);
11012       } else if (p->rtp) 
11013          add_sdp(&req, p, FALSE, TRUE, FALSE);
11014    }
11015 
11016    if (!p->initreq.headers || init > 2)
11017       initialize_initreq(p, &req);
11018    p->lastinvite = p->ocseq;
11019    return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
11020 }
11021 
11022 /*! \brief Send a subscription or resubscription for MWI */
11023 static int sip_subscribe_mwi_do(const void *data)
11024 {
11025    struct sip_subscription_mwi *mwi = (struct sip_subscription_mwi*)data;
11026    
11027    if (!mwi) {
11028       return -1;
11029    }
11030    
11031    mwi->resub = -1;
11032    __sip_subscribe_mwi_do(mwi);
11033    ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
11034    
11035    return 0;
11036 }
11037 
11038 /*! \brief Actually setup an MWI subscription or resubscribe */
11039 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi)
11040 {
11041    /* If we have no DNS manager let's do a lookup */
11042    if (!mwi->dnsmgr) {
11043       char transport[MAXHOSTNAMELEN];
11044       snprintf(transport, sizeof(transport), "_sip._%s", get_transport(mwi->transport));
11045       ast_dnsmgr_lookup(mwi->hostname, &mwi->us, &mwi->dnsmgr, sip_cfg.srvlookup ? transport : NULL);
11046    }
11047 
11048    /* If we already have a subscription up simply send a resubscription */
11049    if (mwi->call) {
11050       transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 0);
11051       return 0;
11052    }
11053    
11054    /* Create a dialog that we will use for the subscription */
11055    if (!(mwi->call = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
11056       return -1;
11057    }
11058 
11059    ref_proxy(mwi->call, obproxy_get(mwi->call, NULL));
11060 
11061    if (!mwi->us.sin_port && mwi->portno) {
11062       mwi->us.sin_port = htons(mwi->portno);
11063    }
11064    
11065    /* Setup the destination of our subscription */
11066    if (create_addr(mwi->call, mwi->hostname, &mwi->us, 0)) {
11067       dialog_unlink_all(mwi->call, TRUE, TRUE);
11068       mwi->call = dialog_unref(mwi->call, "unref dialog after unlink_all");
11069       return 0;
11070    }
11071    
11072    if (!mwi->dnsmgr && mwi->portno) {
11073       mwi->call->sa.sin_port = htons(mwi->portno);
11074       mwi->call->recv.sin_port = htons(mwi->portno);
11075    } else {
11076       mwi->portno = ntohs(mwi->call->sa.sin_port);
11077    }
11078    
11079    /* Set various other information */
11080    if (!ast_strlen_zero(mwi->authuser)) {
11081       ast_string_field_set(mwi->call, peername, mwi->authuser);
11082       ast_string_field_set(mwi->call, authname, mwi->authuser);
11083       ast_string_field_set(mwi->call, fromuser, mwi->authuser);
11084    } else {
11085       ast_string_field_set(mwi->call, peername, mwi->username);
11086       ast_string_field_set(mwi->call, authname, mwi->username);
11087       ast_string_field_set(mwi->call, fromuser, mwi->username);
11088    }
11089    ast_string_field_set(mwi->call, username, mwi->username);
11090    if (!ast_strlen_zero(mwi->secret)) {
11091       ast_string_field_set(mwi->call, peersecret, mwi->secret);
11092    }
11093    set_socket_transport(&mwi->call->socket, mwi->transport);
11094    mwi->call->socket.port = htons(mwi->portno);
11095    ast_sip_ouraddrfor(&mwi->call->sa.sin_addr, &mwi->call->ourip, mwi->call);
11096    build_contact(mwi->call);
11097    build_via(mwi->call);
11098    build_callid_pvt(mwi->call);
11099    ast_set_flag(&mwi->call->flags[0], SIP_OUTGOING);
11100    
11101    /* Associate the call with us */
11102    mwi->call->mwi = ASTOBJ_REF(mwi);
11103    
11104    /* Actually send the packet */
11105    transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 2);
11106 
11107    return 0;
11108 }
11109 
11110 static int find_calling_channel(struct ast_channel *c, void *data) {
11111    struct sip_pvt *p = data;
11112 
11113    return (c->pbx &&
11114          (!strcasecmp(c->macroexten, p->exten) || !strcasecmp(c->exten, p->exten)) &&
11115          (sip_cfg.notifycid == IGNORE_CONTEXT || !strcasecmp(c->context, p->context)));
11116 }
11117 
11118 /*! \brief Used in the SUBSCRIBE notification subsystem (RFC3265) */
11119 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
11120 {
11121    struct ast_str *tmp = ast_str_alloca(4000);
11122    char from[256], to[256];
11123    char *c, *mfrom, *mto;
11124    struct sip_request req;
11125    char hint[AST_MAX_EXTENSION];
11126    char *statestring = "terminated";
11127    const struct cfsubscription_types *subscriptiontype;
11128    enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
11129    char *pidfstate = "--";
11130    char *pidfnote= "Ready";
11131    
11132    memset(from, 0, sizeof(from));
11133    memset(to, 0, sizeof(to));
11134 
11135    switch (state) {
11136    case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
11137       statestring = (sip_cfg.notifyringing) ? "early" : "confirmed";
11138       local_state = NOTIFY_INUSE;
11139       pidfstate = "busy";
11140       pidfnote = "Ringing";
11141       break;
11142    case AST_EXTENSION_RINGING:
11143       statestring = "early";
11144       local_state = NOTIFY_INUSE;
11145       pidfstate = "busy";
11146       pidfnote = "Ringing";
11147       break;
11148    case AST_EXTENSION_INUSE:
11149       statestring = "confirmed";
11150       local_state = NOTIFY_INUSE;
11151       pidfstate = "busy";
11152       pidfnote = "On the phone";
11153       break;
11154    case AST_EXTENSION_BUSY:
11155       statestring = "confirmed";
11156       local_state = NOTIFY_CLOSED;
11157       pidfstate = "busy";
11158       pidfnote = "On the phone";
11159       break;
11160    case AST_EXTENSION_UNAVAILABLE:
11161       statestring = "terminated";
11162       local_state = NOTIFY_CLOSED;
11163       pidfstate = "away";
11164       pidfnote = "Unavailable";
11165       break;
11166    case AST_EXTENSION_ONHOLD:
11167       statestring = "confirmed";
11168       local_state = NOTIFY_CLOSED;
11169       pidfstate = "busy";
11170       pidfnote = "On hold";
11171       break;
11172    case AST_EXTENSION_NOT_INUSE:
11173    default:
11174       /* Default setting */
11175       break;
11176    }
11177 
11178    subscriptiontype = find_subscription_type(p->subscribed);
11179    
11180    /* Check which device/devices we are watching  and if they are registered */
11181    if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten)) {
11182       char *hint2 = hint, *individual_hint = NULL;
11183       int hint_count = 0, unavailable_count = 0;
11184 
11185       while ((individual_hint = strsep(&hint2, "&"))) {
11186          hint_count++;
11187 
11188          if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
11189             unavailable_count++;
11190       }
11191 
11192       /* If none of the hinted devices are registered, we will
11193        * override notification and show no availability.
11194        */
11195       if (hint_count > 0 && hint_count == unavailable_count) {
11196          local_state = NOTIFY_CLOSED;
11197          pidfstate = "away";
11198          pidfnote = "Not online";
11199       }
11200    }
11201 
11202    ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
11203    c = get_in_brackets(from);
11204    if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
11205       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
11206       return -1;
11207    }
11208    
11209    mfrom = remove_uri_parameters(c);
11210 
11211    ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
11212    c = get_in_brackets(to);
11213    if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
11214       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
11215       return -1;
11216    }
11217    mto = remove_uri_parameters(c);
11218 
11219    reqprep(&req, p, SIP_NOTIFY, 0, 1);
11220 
11221    
11222    add_header(&req, "Event", subscriptiontype->event);
11223    add_header(&req, "Content-Type", subscriptiontype->mediatype);
11224    switch(state) {
11225    case AST_EXTENSION_DEACTIVATED:
11226       if (timeout)
11227          add_header(&req, "Subscription-State", "terminated;reason=timeout");
11228       else {
11229          add_header(&req, "Subscription-State", "terminated;reason=probation");
11230          add_header(&req, "Retry-After", "60");
11231       }
11232       break;
11233    case AST_EXTENSION_REMOVED:
11234       add_header(&req, "Subscription-State", "terminated;reason=noresource");
11235       break;
11236    default:
11237       if (p->expiry)
11238          add_header(&req, "Subscription-State", "active");
11239       else  /* Expired */
11240          add_header(&req, "Subscription-State", "terminated;reason=timeout");
11241    }
11242    switch (p->subscribed) {
11243    case XPIDF_XML:
11244    case CPIM_PIDF_XML:
11245       ast_str_append(&tmp, 0,
11246          "<?xml version=\"1.0\"?>\n"
11247          "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n"
11248          "<presence>\n");
11249       ast_str_append(&tmp, 0, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
11250       ast_str_append(&tmp, 0, "<atom id=\"%s\">\n", p->exten);
11251       ast_str_append(&tmp, 0, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
11252       ast_str_append(&tmp, 0, "<status status=\"%s\" />\n", (local_state ==  NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
11253       ast_str_append(&tmp, 0, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
11254       ast_str_append(&tmp, 0, "</address>\n</atom>\n</presence>\n");
11255       break;
11256    case PIDF_XML: /* Eyebeam supports this format */
11257       ast_str_append(&tmp, 0,
11258          "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
11259          "<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);
11260       ast_str_append(&tmp, 0, "<pp:person><status>\n");
11261       if (pidfstate[0] != '-')
11262          ast_str_append(&tmp, 0, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
11263       ast_str_append(&tmp, 0, "</status></pp:person>\n");
11264       ast_str_append(&tmp, 0, "<note>%s</note>\n", pidfnote); /* Note */
11265       ast_str_append(&tmp, 0, "<tuple id=\"%s\">\n", p->exten); /* Tuple start */
11266       ast_str_append(&tmp, 0, "<contact priority=\"1\">%s</contact>\n", mto);
11267       if (pidfstate[0] == 'b') /* Busy? Still open ... */
11268          ast_str_append(&tmp, 0, "<status><basic>open</basic></status>\n");
11269       else
11270          ast_str_append(&tmp, 0, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
11271       ast_str_append(&tmp, 0, "</tuple>\n</presence>\n");
11272       break;
11273    case DIALOG_INFO_XML: /* SNOM subscribes in this format */
11274       ast_str_append(&tmp, 0, "<?xml version=\"1.0\"?>\n");
11275       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);
11276       if ((state & AST_EXTENSION_RINGING) && sip_cfg.notifyringing) {
11277          const char *local_display = p->exten;
11278          char *local_target = mto;
11279 
11280          /* There are some limitations to how this works.  The primary one is that the
11281             callee must be dialing the same extension that is being monitored.  Simply dialing
11282             the hint'd device is not sufficient. */
11283          if (sip_cfg.notifycid) {
11284             struct ast_channel *caller = ast_channel_search_locked(find_calling_channel, p);
11285 
11286             if (caller) {
11287                int need = strlen(caller->cid.cid_num) + strlen(p->fromdomain) + sizeof("sip:@");
11288                local_target = alloca(need);
11289                snprintf(local_target, need, "sip:%s@%s", caller->cid.cid_num, p->fromdomain);
11290                local_display = ast_strdupa(caller->cid.cid_name);
11291                ast_channel_unlock(caller);
11292                caller = NULL;
11293             }
11294          }
11295 
11296          /* We create a fake call-id which the phone will send back in an INVITE
11297             Replaces header which we can grab and do some magic with. */
11298          ast_str_append(&tmp, 0, 
11299                "<dialog id=\"%s\" call-id=\"pickup-%s\" direction=\"recipient\">\n"
11300                "<remote>\n"
11301                /* See the limitations of this above.  Luckily the phone seems to still be
11302                   happy when these values are not correct. */
11303                "<identity display=\"%s\">%s</identity>\n"
11304                "<target uri=\"%s\"/>\n"
11305                "</remote>\n"
11306                "<local>\n"
11307                "<identity>%s</identity>\n"
11308                "<target uri=\"%s\"/>\n"
11309                "</local>\n",
11310                p->exten, p->callid, local_display, local_target, local_target, mto, mto);
11311       } else {
11312          ast_str_append(&tmp, 0, "<dialog id=\"%s\">\n", p->exten);
11313       }
11314       ast_str_append(&tmp, 0, "<state>%s</state>\n", statestring);
11315       if (state == AST_EXTENSION_ONHOLD) {
11316          ast_str_append(&tmp, 0, "<local>\n<target uri=\"%s\">\n"
11317                                          "<param pname=\"+sip.rendering\" pvalue=\"no\"/>\n"
11318                                          "</target>\n</local>\n", mto);
11319       }
11320       ast_str_append(&tmp, 0, "</dialog>\n</dialog-info>\n");
11321       break;
11322    case NONE:
11323    default:
11324       break;
11325    }
11326 
11327    add_content(&req, tmp->str);
11328 
11329    p->pendinginvite = p->ocseq;  /* Remember that we have a pending NOTIFY in order not to confuse the NOTIFY subsystem */
11330 
11331    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11332 }
11333 
11334 /*! \brief Notify user of messages waiting in voicemail (RFC3842)
11335 \note - Notification only works for registered peers with mailbox= definitions
11336    in sip.conf
11337    - We use the SIP Event package message-summary
11338     MIME type defaults to  "application/simple-message-summary";
11339  */
11340 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten)
11341 {
11342    struct sip_request req;
11343    struct ast_str *out = ast_str_alloca(500);
11344    int ourport = ntohs(p->ourip.sin_port);
11345    const char *exten = S_OR(vmexten, default_vmexten);
11346 
11347    initreqprep(&req, p, SIP_NOTIFY);
11348    add_header(&req, "Event", "message-summary");
11349    add_header(&req, "Content-Type", default_notifymime);
11350    ast_str_append(&out, 0, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
11351 
11352    if (!ast_strlen_zero(p->fromdomain)) {
11353       ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, p->fromdomain);
11354    } else if (!sip_standard_port(p->socket.type, ourport)) {
11355       if (p->socket.type == SIP_TRANSPORT_UDP) {
11356          ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr), ourport);
11357       } else {
11358          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));
11359       }
11360    } else {
11361       if (p->socket.type == SIP_TRANSPORT_UDP) {
11362          ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr));
11363       } else {
11364          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));
11365       }
11366    }
11367    /* Cisco has a bug in the SIP stack where it can't accept the
11368       (0/0) notification. This can temporarily be disabled in
11369       sip.conf with the "buggymwi" option */
11370    ast_str_append(&out, 0, "Voice-Message: %d/%d%s\r\n",
11371       newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));
11372 
11373    if (p->subscribed) {
11374       if (p->expiry)
11375          add_header(&req, "Subscription-State", "active");
11376       else  /* Expired */
11377          add_header(&req, "Subscription-State", "terminated;reason=timeout");
11378    }
11379 
11380    add_content(&req, out->str);
11381 
11382    if (!p->initreq.headers) 
11383       initialize_initreq(p, &req);
11384    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11385 }
11386 
11387 /*! \brief Notify a transferring party of the status of transfer (RFC3515) */
11388 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
11389 {
11390    struct sip_request req;
11391    char tmp[SIPBUFSIZE/2];
11392    
11393    reqprep(&req, p, SIP_NOTIFY, 0, 1);
11394    snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
11395    add_header(&req, "Event", tmp);
11396    add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
11397    add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
11398    add_header(&req, "Allow", ALLOWED_METHODS);
11399    add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
11400 
11401    snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
11402    add_content(&req, tmp);
11403 
11404    if (!p->initreq.headers)
11405       initialize_initreq(p, &req);
11406 
11407    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11408 }
11409 
11410 /*! \brief Notify device with custom headers from sip_notify.conf */
11411 static int transmit_notify_custom(struct sip_pvt *p, struct ast_variable *vars) {
11412    struct sip_request req;
11413    struct ast_variable *var, *newvar;
11414 
11415    initreqprep(&req, p, SIP_NOTIFY);
11416 
11417    /* Copy notify vars and add headers */
11418    p->notify_headers = newvar = ast_variable_new("Subscription-State", "terminated", "");
11419    add_header(&req, newvar->name, newvar->value);
11420    for (var = vars; var; var = var->next) {
11421       char buf[512];
11422 
11423       if (!strcasecmp(var->name, "Content-Length")) {
11424          ast_debug(2, "Ignoring pair %s=%s\n", var->name, var->value);
11425          continue; /* ignore content-length, it is calculated automatically */
11426       }
11427 
11428       ast_debug(2, "  Adding pair %s=%s\n", var->name, var->value);
11429       ast_copy_string(buf, var->value, sizeof(buf));
11430       add_header(&req, var->name, ast_unescape_semicolon(buf));
11431       newvar->next = ast_variable_new(var->name, var->value, "");
11432       newvar = newvar->next;
11433    }
11434 
11435    if (!p->initreq.headers) { /* Initialize first request before sending */
11436       initialize_initreq(p, &req);
11437    }
11438 
11439    return send_request(p, &req, XMIT_UNRELIABLE, p->ocseq);
11440 }
11441 
11442 static int manager_sipnotify(struct mansession *s, const struct message *m)
11443 {
11444    const char *channame = astman_get_header(m, "Channel");
11445    struct ast_variable *vars = astman_get_variables(m);
11446    struct sip_pvt *p;
11447 
11448    if (ast_strlen_zero(channame)) {
11449       astman_send_error(s, m, "SIPNotify requires a channel name");
11450       return 0;
11451    }
11452 
11453    if (!strncasecmp(channame, "sip/", 4)) {
11454       channame += 4;
11455    }
11456 
11457    if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
11458       astman_send_error(s, m, "Unable to build sip pvt data for notify (memory/socket error)");
11459       return 0;
11460    }
11461 
11462    if (create_addr(p, channame, NULL, 0)) {
11463       /* Maybe they're not registered, etc. */
11464       dialog_unlink_all(p, TRUE, TRUE);
11465       dialog_unref(p, "unref dialog inside for loop" );
11466       /* sip_destroy(p); */
11467       astman_send_error(s, m, "Could not create address");
11468       return 0;
11469    }
11470 
11471    /* Notify is outgoing call */
11472    ast_set_flag(&p->flags[0], SIP_OUTGOING);
11473 
11474    /* Recalculate our side, and recalculate Call ID */
11475    ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
11476    build_via(p);
11477    ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
11478    build_callid_pvt(p);
11479    ao2_t_link(dialogs, p, "Linking in new name");
11480    dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
11481    sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
11482 
11483    if (!transmit_notify_custom(p, vars)) {
11484       astman_send_ack(s, m, "Notify Sent");
11485    } else {
11486       astman_send_error(s, m, "Unable to send notify");
11487    }
11488    ast_variables_destroy(vars);
11489    return 0;
11490 }
11491 
11492 static char mandescr_sipnotify[] =
11493 "Description: Sends a SIP Notify event\n"
11494 "All parameters for this event must be specified in the body of this request\n"
11495 "via multiple Variable: name=value sequences.\n"
11496 "Variables: \n"
11497 "  *Channel: <peername>       Peer to receive the notify. Required.\n"
11498 "  *Variable: <name>=<value>  At least one variable pair must be specified.\n"
11499 "  ActionID: <id>             Action ID for this transaction. Will be returned.\n";
11500 
11501 static const struct _map_x_s regstatestrings[] = {
11502    { REG_STATE_FAILED,     "Failed" },
11503    { REG_STATE_UNREGISTERED, "Unregistered"},
11504    { REG_STATE_REGSENT, "Request Sent"},
11505    { REG_STATE_AUTHSENT, "Auth. Sent"},
11506    { REG_STATE_REGISTERED, "Registered"},
11507    { REG_STATE_REJECTED, "Rejected"},
11508    { REG_STATE_TIMEOUT, "Timeout"},
11509    { REG_STATE_NOAUTH, "No Authentication"},
11510    { -1, NULL } /* terminator */
11511 };
11512 
11513 /*! \brief Convert registration state status to string */
11514 static const char *regstate2str(enum sipregistrystate regstate)
11515 {
11516    return map_x_s(regstatestrings, regstate, "Unknown");
11517 }
11518 
11519 /*! \brief Update registration with SIP Proxy.
11520  * Called from the scheduler when the previous registration expires,
11521  * so we don't have to cancel the pending event.
11522  * We assume the reference so the sip_registry is valid, since it
11523  * is stored in the scheduled event anyways.
11524  */
11525 static int sip_reregister(const void *data) 
11526 {
11527    /* if we are here, we know that we need to reregister. */
11528    struct sip_registry *r= (struct sip_registry *) data;
11529 
11530    /* if we couldn't get a reference to the registry object, punt */
11531    if (!r)
11532       return 0;
11533 
11534    if (r->call && r->call->do_history)
11535       append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
11536    /* Since registry's are only added/removed by the the monitor thread, this
11537       may be overkill to reference/dereference at all here */
11538    if (sipdebug)
11539       ast_log(LOG_NOTICE, "   -- Re-registration for  %s@%s\n", r->username, r->hostname);
11540 
11541    r->expire = -1;
11542    r->expiry = r->configured_expiry;
11543    __sip_do_register(r);
11544    registry_unref(r, "unref the re-register scheduled event");
11545    return 0;
11546 }
11547 
11548 /*! \brief Register with SIP proxy */
11549 static int __sip_do_register(struct sip_registry *r)
11550 {
11551    int res;
11552 
11553    res = transmit_register(r, SIP_REGISTER, NULL, NULL);
11554    return res;
11555 }
11556 
11557 /*! \brief Registration timeout, register again
11558  * Registered as a timeout handler during transmit_register(),
11559  * to retransmit the packet if a reply does not come back.
11560  * This is called by the scheduler so the event is not pending anymore when
11561  * we are called.
11562  */
11563 static int sip_reg_timeout(const void *data)
11564 {
11565 
11566    /* if we are here, our registration timed out, so we'll just do it over */
11567    struct sip_registry *r = (struct sip_registry *)data; /* the ref count should have been bumped when the sched item was added */
11568    struct sip_pvt *p;
11569    int res;
11570 
11571    /* if we couldn't get a reference to the registry object, punt */
11572    if (!r)
11573       return 0;
11574 
11575    if (r->dnsmgr) {
11576       /* If the registration has timed out, maybe the IP changed.  Force a refresh. */
11577       ast_dnsmgr_refresh(r->dnsmgr);
11578    }
11579 
11580    ast_log(LOG_NOTICE, "   -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts); 
11581    /* If the initial tranmission failed, we may not have an existing dialog,
11582     * so it is possible that r->call == NULL.
11583     * Otherwise destroy it, as we have a timeout so we don't want it.
11584     */
11585    if (r->call) {
11586       /* Unlink us, destroy old call.  Locking is not relevant here because all this happens
11587          in the single SIP manager thread. */
11588       p = r->call;
11589       sip_pvt_lock(p);
11590       pvt_set_needdestroy(p, "registration timeout");
11591       /* Pretend to ACK anything just in case */
11592       __sip_pretend_ack(p);
11593       sip_pvt_unlock(p);
11594 
11595       /* decouple the two objects */
11596       /* p->registry == r, so r has 2 refs, and the unref won't take the object away */
11597       if (p->registry)
11598          p->registry = registry_unref(p->registry, "p->registry unreffed");
11599       r->call = dialog_unref(r->call, "unrefing r->call");
11600    }
11601    /* If we have a limit, stop registration and give up */
11602    r->timeout = -1;
11603    if (global_regattempts_max && r->regattempts > global_regattempts_max) {
11604       /* Ok, enough is enough. Don't try any more */
11605       /* We could add an external notification here... 
11606          steal it from app_voicemail :-) */
11607       ast_log(LOG_NOTICE, "   -- Giving up forever trying to register '%s@%s'\n", r->username, r->hostname);
11608       r->regstate = REG_STATE_FAILED;
11609    } else {
11610       r->regstate = REG_STATE_UNREGISTERED;
11611       res=transmit_register(r, SIP_REGISTER, NULL, NULL);
11612    }
11613    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));
11614    registry_unref(r, "unreffing registry_unref r");
11615    return 0;
11616 }
11617 
11618 /*! \brief Transmit register to SIP proxy or UA
11619  * auth = NULL on the initial registration (from sip_reregister())
11620  */
11621 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
11622 {
11623    struct sip_request req;
11624    char from[256];
11625    char to[256];
11626    char tmp[80];
11627    char addr[80];
11628    struct sip_pvt *p;
11629    struct sip_peer *peer = NULL;
11630    int res;
11631    char *fromdomain;
11632    char *domainport = NULL;
11633 
11634    /* exit if we are already in process with this registrar ?*/
11635    if (r == NULL || ((auth == NULL) && (r->regstate == REG_STATE_REGSENT || r->regstate == REG_STATE_AUTHSENT))) {
11636       if (r) {
11637          ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
11638       }
11639       return 0;
11640    }
11641 
11642    if (r->dnsmgr == NULL) {
11643       char transport[MAXHOSTNAMELEN];
11644       peer = find_peer(r->hostname, NULL, TRUE, FINDPEERS, FALSE, 0);
11645       snprintf(transport, sizeof(transport), "_sip._%s", get_transport(r->transport)); /* have to use static get_transport function */
11646       ast_dnsmgr_lookup(peer ? peer->tohost : r->hostname, &r->us, &r->dnsmgr, sip_cfg.srvlookup ? transport : NULL);
11647       if (peer) {
11648          peer = unref_peer(peer, "removing peer ref for dnsmgr_lookup");
11649       }
11650    }
11651 
11652    if (r->call) { /* We have a registration */
11653       if (!auth) {
11654          ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
11655          return 0;
11656       } else {
11657          p = dialog_ref(r->call, "getting a copy of the r->call dialog in transmit_register");
11658          make_our_tag(p->tag, sizeof(p->tag));  /* create a new local tag for every register attempt */
11659          ast_string_field_set(p, theirtag, NULL);  /* forget their old tag, so we don't match tags when getting response */
11660       }
11661    } else {
11662       /* Build callid for registration if we haven't registered before */
11663       if (!r->callid_valid) {
11664          build_callid_registry(r, internip.sin_addr, default_fromdomain);
11665          r->callid_valid = TRUE;
11666       }
11667       /* Allocate SIP dialog for registration */
11668       if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER, NULL))) {
11669          ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
11670          return 0;
11671       }
11672       
11673       if (p->do_history)
11674          append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
11675 
11676       /* Use port number specified if no SRV record was found */
11677       if (!r->us.sin_port && r->portno)
11678          r->us.sin_port = htons(r->portno);
11679 
11680       /* Find address to hostname */
11681       if (create_addr(p, S_OR(r->peername, r->hostname), &r->us, 0)) {
11682          /* we have what we hope is a temporary network error,
11683           * probably DNS.  We need to reschedule a registration try */
11684          dialog_unlink_all(p, TRUE, TRUE);
11685          p = dialog_unref(p, "unref dialog after unlink_all");
11686          if (r->timeout > -1) {
11687             AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
11688                               registry_unref(_data, "del for REPLACE of registry ptr"), 
11689                               registry_unref(r, "object ptr dec when SCHED_REPLACE add failed"),
11690                               registry_addref(r,"add for REPLACE registry ptr"));
11691             ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
11692          } else {
11693             r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, registry_addref(r, "add for REPLACE registry ptr"));
11694             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);
11695          }
11696          r->regattempts++;
11697          return 0;
11698       }
11699 
11700       /* Copy back Call-ID in case create_addr changed it */
11701       ast_string_field_set(r, callid, p->callid);
11702       if (!r->dnsmgr && r->portno) {
11703          p->sa.sin_port = htons(r->portno);
11704          p->recv.sin_port = htons(r->portno);
11705       } else { /* Set registry port to the port set from the peer definition/srv or default */
11706          r->portno = ntohs(p->sa.sin_port);
11707       }
11708       ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Registration is outgoing call */
11709       r->call = dialog_ref(p, "copying dialog into registry r->call");     /* Save pointer to SIP dialog */
11710       p->registry = registry_addref(r, "transmit_register: addref to p->registry in transmit_register"); /* Add pointer to registry in packet */
11711       if (!ast_strlen_zero(r->secret)) {  /* Secret (password) */
11712          ast_string_field_set(p, peersecret, r->secret);
11713       }
11714       if (!ast_strlen_zero(r->md5secret))
11715          ast_string_field_set(p, peermd5secret, r->md5secret);
11716       /* User name in this realm  
11717       - if authuser is set, use that, otherwise use username */
11718       if (!ast_strlen_zero(r->authuser)) {   
11719          ast_string_field_set(p, peername, r->authuser);
11720          ast_string_field_set(p, authname, r->authuser);
11721       } else if (!ast_strlen_zero(r->username)) {
11722          ast_string_field_set(p, peername, r->username);
11723          ast_string_field_set(p, authname, r->username);
11724          ast_string_field_set(p, fromuser, r->username);
11725       }
11726       if (!ast_strlen_zero(r->username))
11727          ast_string_field_set(p, username, r->username);
11728       /* Save extension in packet */
11729       if (!ast_strlen_zero(r->callback))
11730          ast_string_field_set(p, exten, r->callback);
11731 
11732       /* Set transport and port so the correct contact is built */
11733       set_socket_transport(&p->socket, r->transport);
11734       if (r->transport == SIP_TRANSPORT_TLS || r->transport == SIP_TRANSPORT_TCP) {
11735          p->socket.port = sip_tcp_desc.local_address.sin_port;
11736       }
11737 
11738       /*
11739         check which address we should use in our contact header 
11740         based on whether the remote host is on the external or
11741         internal network so we can register through nat
11742        */
11743       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
11744       build_contact(p);
11745    }
11746 
11747    /* set up a timeout */
11748    if (auth == NULL)  {
11749       if (r->timeout > -1)
11750          ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
11751       AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
11752                         registry_unref(_data,"reg ptr unrefed from del in SCHED_REPLACE"),
11753                         registry_unref(r,"reg ptr unrefed from add failure in SCHED_REPLACE"),
11754                         registry_addref(r,"reg ptr reffed from add in SCHED_REPLACE"));
11755       ast_debug(1, "Scheduled a registration timeout for %s id  #%d \n", r->hostname, r->timeout);
11756    }
11757 
11758    if ((fromdomain = strchr(r->username, '@'))) {
11759       /* the domain name is just behind '@' */
11760       fromdomain++ ;
11761       /* We have a domain in the username for registration */
11762       snprintf(from, sizeof(from), "<sip:%s>;tag=%s", r->username, p->tag);
11763       if (!ast_strlen_zero(p->theirtag))
11764          snprintf(to, sizeof(to), "<sip:%s>;tag=%s", r->username, p->theirtag);
11765       else
11766          snprintf(to, sizeof(to), "<sip:%s>", r->username);
11767 
11768       /* If the registration username contains '@', then the domain should be used as
11769          the equivalent of "fromdomain" for the registration */
11770       if (ast_strlen_zero(p->fromdomain)) {
11771          ast_string_field_set(p, fromdomain, fromdomain);
11772       }
11773    } else {
11774       snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->tag);
11775       if (!ast_strlen_zero(p->theirtag))
11776          snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->theirtag);
11777       else
11778          snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, p->tohost);
11779    }
11780    
11781    /* Fromdomain is what we are registering to, regardless of actual
11782       host name from SRV */
11783    if (!ast_strlen_zero(p->fromdomain)) {
11784       domainport = strrchr(p->fromdomain, ':');
11785       if (domainport) {
11786          *domainport++ = '\0'; /* trim off domainport from p->fromdomain */
11787          if (ast_strlen_zero(domainport))
11788             domainport = NULL;
11789       }     
11790       if (domainport) {       
11791          if (atoi(domainport) != STANDARD_SIP_PORT)
11792             snprintf(addr, sizeof(addr), "sip:%s:%s", p->fromdomain, domainport);
11793          else
11794             snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
11795       } else {
11796          if (r->portno && r->portno != STANDARD_SIP_PORT)
11797             snprintf(addr, sizeof(addr), "sip:%s:%d", p->fromdomain, r->portno);
11798          else
11799             snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
11800       }
11801    } else {
11802       if (r->portno && r->portno != STANDARD_SIP_PORT)
11803          snprintf(addr, sizeof(addr), "sip:%s:%d", r->hostname, r->portno);
11804       else
11805          snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
11806    }
11807    ast_string_field_set(p, uri, addr);
11808 
11809    p->branch ^= ast_random();
11810 
11811    init_req(&req, sipmethod, addr);
11812 
11813    /* Add to CSEQ */
11814    snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
11815    p->ocseq = r->ocseq;
11816 
11817    build_via(p);
11818    add_header(&req, "Via", p->via);
11819    add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
11820    add_header(&req, "From", from);
11821    add_header(&req, "To", to);
11822    add_header(&req, "Call-ID", p->callid);
11823    add_header(&req, "CSeq", tmp);
11824    if (!ast_strlen_zero(global_useragent))
11825       add_header(&req, "User-Agent", global_useragent);
11826 
11827    
11828    if (auth)   /* Add auth header */
11829       add_header(&req, authheader, auth);
11830    else if (!ast_strlen_zero(r->nonce)) {
11831       char digest[1024];
11832 
11833       /* We have auth data to reuse, build a digest header.
11834        * Note, this is not always useful because some parties do not
11835        * like nonces to be reused (for good reasons!) so they will
11836        * challenge us anyways.
11837        */
11838       if (sipdebug)
11839          ast_debug(1, "   >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
11840       ast_string_field_set(p, realm, r->realm);
11841       ast_string_field_set(p, nonce, r->nonce);
11842       ast_string_field_set(p, domain, r->domain);
11843       ast_string_field_set(p, opaque, r->opaque);
11844       ast_string_field_set(p, qop, r->qop);
11845       p->noncecount = ++r->noncecount;
11846 
11847       memset(digest, 0, sizeof(digest));
11848       if(!build_reply_digest(p, sipmethod, digest, sizeof(digest)))
11849          add_header(&req, "Authorization", digest);
11850       else
11851          ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
11852    
11853    }
11854 
11855    snprintf(tmp, sizeof(tmp), "%d", r->expiry);
11856    add_header(&req, "Expires", tmp);
11857    add_header(&req, "Contact", p->our_contact);
11858 
11859    initialize_initreq(p, &req);
11860    if (sip_debug_test_pvt(p)) {
11861       ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
11862    }
11863    r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
11864    r->regattempts++; /* Another attempt */
11865    ast_debug(4, "REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
11866    res = send_request(p, &req, XMIT_CRITICAL, p->ocseq);
11867    dialog_unref(p, "p is finished here at the end of transmit_register");
11868    return res;
11869 }
11870 
11871 /*! \brief Transmit text with SIP MESSAGE method */
11872 static int transmit_message_with_text(struct sip_pvt *p, const char *text)
11873 {
11874    struct sip_request req;
11875    
11876    reqprep(&req, p, SIP_MESSAGE, 0, 1);
11877    add_text(&req, text);
11878    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11879 }
11880 
11881 /*! \brief Allocate SIP refer structure */
11882 static int sip_refer_allocate(struct sip_pvt *p)
11883 {
11884    p->refer = ast_calloc(1, sizeof(struct sip_refer)); 
11885    return p->refer ? 1 : 0;
11886 }
11887 
11888 /*! \brief Transmit SIP REFER message (initiated by the transfer() dialplan application
11889    \note this is currently broken as we have no way of telling the dialplan
11890    engine whether a transfer succeeds or fails.
11891    \todo Fix the transfer() dialplan function so that a transfer may fail
11892 */
11893 static int transmit_refer(struct sip_pvt *p, const char *dest)
11894 {
11895    struct sip_request req = { 
11896       .headers = 0,  
11897    };
11898    char from[256];
11899    const char *of;
11900    char *c;
11901    char referto[256];
11902    char *ttag, *ftag;
11903    char *theirtag = ast_strdupa(p->theirtag);
11904    int   use_tls=FALSE;
11905 
11906    if (sipdebug)
11907       ast_debug(1, "SIP transfer of %s to %s\n", p->callid, dest);
11908 
11909    /* Are we transfering an inbound or outbound call ? */
11910    if (ast_test_flag(&p->flags[0], SIP_OUTGOING))  {
11911       of = get_header(&p->initreq, "To");
11912       ttag = theirtag;
11913       ftag = p->tag;
11914    } else {
11915       of = get_header(&p->initreq, "From");
11916       ftag = theirtag;
11917       ttag = p->tag;
11918    }
11919 
11920    ast_copy_string(from, of, sizeof(from));
11921    of = get_in_brackets(from);
11922    ast_string_field_set(p, from, of);
11923    if (!strncasecmp(of, "sip:", 4)) {
11924       of += 4;
11925    }else if (!strncasecmp(of, "sips:", 5)) {
11926       of += 5;
11927       use_tls = TRUE;
11928    } else {
11929       ast_log(LOG_NOTICE, "From address missing 'sip(s):', assuming sip:\n");
11930    }
11931    /* Get just the username part */
11932    if ((c = strchr(dest, '@')))
11933       c = NULL;
11934    else if ((c = strchr(of, '@')))
11935       *c++ = '\0';
11936    if (c) 
11937       snprintf(referto, sizeof(referto), "<sip%s:%s@%s>", use_tls ? "s" : "", dest, c);
11938    else
11939       snprintf(referto, sizeof(referto), "<sip%s:%s>", use_tls ? "s" : "", dest);
11940 
11941    /* save in case we get 407 challenge */
11942    sip_refer_allocate(p);
11943    ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
11944    ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
11945    p->refer->status = REFER_SENT;   /* Set refer status */
11946 
11947    reqprep(&req, p, SIP_REFER, 0, 1);
11948 
11949    add_header(&req, "Refer-To", referto);
11950    add_header(&req, "Allow", ALLOWED_METHODS);
11951    add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
11952    if (!ast_strlen_zero(p->our_contact))
11953       add_header(&req, "Referred-By", p->our_contact);
11954 
11955    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11956 
11957    /* We should propably wait for a NOTIFY here until we ack the transfer */
11958    /* Maybe fork a new thread and wait for a STATUS of REFER_200OK on the refer status before returning to app_transfer */
11959 
11960    /*! \todo In theory, we should hang around and wait for a reply, before
11961    returning to the dial plan here. Don't know really how that would
11962    affect the transfer() app or the pbx, but, well, to make this
11963    useful we should have a STATUS code on transfer().
11964    */
11965 }
11966 
11967 
11968 /*! \brief Send SIP INFO dtmf message, see Cisco documentation on cisco.com */
11969 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
11970 {
11971    struct sip_request req;
11972    
11973    reqprep(&req, p, SIP_INFO, 0, 1);
11974    add_digit(&req, digit, duration, (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO));
11975    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11976 }
11977 
11978 /*! \brief Send SIP INFO with video update request */
11979 static int transmit_info_with_vidupdate(struct sip_pvt *p)
11980 {
11981    struct sip_request req;
11982    
11983    reqprep(&req, p, SIP_INFO, 0, 1);
11984    add_vidupdate(&req);
11985    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11986 }
11987 
11988 /*! \brief Transmit generic SIP request 
11989    returns XMIT_ERROR if transmit failed with a critical error (don't retry)
11990 */
11991 static int transmit_request(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
11992 {
11993    struct sip_request resp;
11994    
11995    if (sipmethod == SIP_ACK)
11996       p->invitestate = INV_CONFIRMED;
11997 
11998    reqprep(&resp, p, sipmethod, seqno, newbranch);
11999    if (sipmethod == SIP_CANCEL && p->answered_elsewhere) 
12000       add_header(&resp, "Reason", "SIP;cause=200;text=\"Call completed elsewhere\"");
12001 
12002    return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
12003 }
12004 
12005 /*! \brief return the request and response heade for a 401 or 407 code */
12006 static void auth_headers(enum sip_auth_type code, char **header, char **respheader)
12007 {
12008    if (code == WWW_AUTH) {       /* 401 */
12009       *header = "WWW-Authenticate";
12010       *respheader = "Authorization";
12011    } else if (code == PROXY_AUTH) { /* 407 */
12012       *header = "Proxy-Authenticate";
12013       *respheader = "Proxy-Authorization";
12014    } else {
12015       ast_verbose("-- wrong response code %d\n", code);
12016       *header = *respheader = "Invalid";
12017    }
12018 }
12019 
12020 /*! \brief Transmit SIP request, auth added */
12021 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
12022 {
12023    struct sip_request resp;
12024    
12025    reqprep(&resp, p, sipmethod, seqno, newbranch);
12026    if (!ast_strlen_zero(p->realm)) {
12027       char digest[1024];
12028 
12029       memset(digest, 0, sizeof(digest));
12030       if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
12031          char *dummy, *response;
12032          enum sip_auth_type code = p->options ? p->options->auth_type : PROXY_AUTH; /* XXX force 407 if unknown */
12033          auth_headers(code, &dummy, &response);
12034          add_header(&resp, response, digest);
12035       } else
12036          ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
12037    }
12038    /* If we are hanging up and know a cause for that, send it in clear text to make
12039       debugging easier. */
12040    if (sipmethod == SIP_BYE)  {
12041       char buf[10];
12042 
12043       add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->hangupcause));
12044       snprintf(buf, sizeof(buf), "%d", p->hangupcause);
12045       add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
12046    }
12047 
12048    return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);   
12049 }
12050 
12051 /*! \brief Remove registration data from realtime database or AST/DB when registration expires */
12052 static void destroy_association(struct sip_peer *peer)
12053 {
12054    int realtimeregs = ast_check_realtime("sipregs");
12055    char *tablename = (realtimeregs) ? "sipregs" : "sippeers";
12056 
12057    if (!sip_cfg.ignore_regexpire) {
12058       if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
12059          ast_update_realtime(tablename, "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", peer->deprecated_username ? "username" : "defaultuser", "", "regserver", "", "useragent", "", "lastms", "", SENTINEL);
12060       } else {
12061          ast_db_del("SIP/Registry", peer->name);
12062       }
12063    }
12064 }
12065 
12066 static void set_socket_transport(struct sip_socket *socket, int transport)
12067 {
12068    /* if the transport type changes, clear all socket data */
12069    if (socket->type != transport) {
12070       socket->fd = -1;
12071       socket->type = transport;
12072       if (socket->tcptls_session) {
12073          ao2_ref(socket->tcptls_session, -1);
12074          socket->tcptls_session = NULL;
12075       }
12076    }
12077 }
12078 
12079 /*! \brief Expire registration of SIP peer */
12080 static int expire_register(const void *data)
12081 {
12082    struct sip_peer *peer = (struct sip_peer *)data;
12083 
12084    if (!peer)     /* Hmmm. We have no peer. Weird. */
12085       return 0;
12086 
12087    peer->expire = -1;
12088    peer->portinuri = 0;
12089    memset(&peer->addr, 0, sizeof(peer->addr));
12090 
12091    destroy_association(peer); /* remove registration data from storage */
12092    set_socket_transport(&peer->socket, peer->default_outbound_transport);
12093 
12094    if (peer->socket.tcptls_session) {
12095       ao2_ref(peer->socket.tcptls_session, -1);
12096       peer->socket.tcptls_session = NULL;
12097    }
12098 
12099    manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
12100    register_peer_exten(peer, FALSE);   /* Remove regexten */
12101    ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
12102 
12103    /* Do we need to release this peer from memory? 
12104       Only for realtime peers and autocreated peers
12105    */
12106    if (peer->is_realtime)
12107       ast_debug(3, "-REALTIME- peer expired registration. Name: %s. Realtime peer objects now %d\n", peer->name, rpeerobjs);
12108 
12109    if (peer->selfdestruct ||
12110        ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
12111       ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
12112       if (peer->addr.sin_addr.s_addr) {
12113          ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
12114       }
12115    }
12116 
12117    unref_peer(peer, "removing peer ref for expire_register");
12118 
12119    return 0;
12120 }
12121 
12122 /*! \brief Poke peer (send qualify to check if peer is alive and well) */
12123 static int sip_poke_peer_s(const void *data)
12124 {
12125    struct sip_peer *peer = (struct sip_peer *)data;
12126 
12127    peer->pokeexpire = -1;
12128 
12129    sip_poke_peer(peer, 0);
12130 
12131    unref_peer(peer, "removing poke peer ref");
12132 
12133    return 0;
12134 }
12135 
12136 /*! \brief Get registration details from Asterisk DB */
12137 static void reg_source_db(struct sip_peer *peer)
12138 {
12139    char data[256];
12140    struct in_addr in;
12141    int expire;
12142    int port;
12143    char *scan, *addr, *port_str, *expiry_str, *username, *contact;
12144 
12145    if (peer->rt_fromcontact) 
12146       return;
12147    if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data)))
12148       return;
12149 
12150    scan = data;
12151    addr = strsep(&scan, ":");
12152    port_str = strsep(&scan, ":");
12153    expiry_str = strsep(&scan, ":");
12154    username = strsep(&scan, ":");
12155    contact = scan;   /* Contact include sip: and has to be the last part of the database entry as long as we use : as a separator */
12156 
12157    if (!inet_aton(addr, &in))
12158       return;
12159 
12160    if (port_str)
12161       port = atoi(port_str);
12162    else
12163       return;
12164 
12165    if (expiry_str)
12166       expire = atoi(expiry_str);
12167    else
12168       return;
12169 
12170    if (username)
12171       ast_string_field_set(peer, username, username);
12172    if (contact)
12173       ast_string_field_set(peer, fullcontact, contact);
12174 
12175    ast_debug(2, "SIP Seeding peer from astdb: '%s' at %s@%s:%d for %d\n",
12176        peer->name, peer->username, ast_inet_ntoa(in), port, expire);
12177 
12178    memset(&peer->addr, 0, sizeof(peer->addr));
12179    peer->addr.sin_family = AF_INET;
12180    peer->addr.sin_addr = in;
12181    peer->addr.sin_port = htons(port);
12182    if (sipsock < 0) {
12183       /* SIP isn't up yet, so schedule a poke only, pretty soon */
12184       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ast_random() % 5000 + 1, sip_poke_peer_s, peer,
12185             unref_peer(_data, "removing poke peer ref"),
12186             unref_peer(peer, "removing poke peer ref"),
12187             ref_peer(peer, "adding poke peer ref"));
12188    } else {
12189       sip_poke_peer(peer, 0);
12190    }
12191    AST_SCHED_REPLACE_UNREF(peer->expire, sched, (expire + 10) * 1000, expire_register, peer,
12192          unref_peer(_data, "remove registration ref"),
12193          unref_peer(peer, "remove registration ref"),
12194          ref_peer(peer, "add registration ref"));
12195    register_peer_exten(peer, TRUE);
12196 }
12197 
12198 /*! \brief Save contact header for 200 OK on INVITE */
12199 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
12200 {
12201    char contact[SIPBUFSIZE]; 
12202    char *c;
12203 
12204    /* Look for brackets */
12205    ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
12206    c = get_in_brackets(contact);
12207 
12208    /* Save full contact to call pvt for later bye or re-invite */
12209    ast_string_field_set(pvt, fullcontact, c);
12210 
12211    /* Save URI for later ACKs, BYE or RE-invites */
12212    ast_string_field_set(pvt, okcontacturi, c);
12213 
12214    /* We should return false for URI:s we can't handle,
12215       like tel:, mailto:,ldap: etc */
12216    return TRUE;      
12217 }
12218 
12219 static int __set_address_from_contact(const char *fullcontact, struct sockaddr_in *sin, int tcp)
12220 {
12221    struct hostent *hp;
12222    struct ast_hostent ahp;
12223    int port = STANDARD_SIP_PORT;
12224    char *host, *pt, *transport;
12225    char contact_buf[256];
12226    char *contact;
12227 
12228    /* Work on a copy */
12229    ast_copy_string(contact_buf, fullcontact, sizeof(contact_buf));
12230    contact = contact_buf;
12231 
12232    /* 
12233     * We have only the part in <brackets> here so we just need to parse a SIP URI.
12234     *
12235     * Note: The outbound proxy could be using UDP between the proxy and Asterisk.
12236     * We still need to be able to send to the remote agent through the proxy.
12237     */
12238 
12239    if (parse_uri(contact, "sip:,sips:", &contact, NULL, &host, &pt, NULL, &transport)) {
12240       ast_log(LOG_WARNING, "Invalid contact uri %s (missing sip: or sips:), attempting to use anyway\n", fullcontact);
12241    }
12242 
12243    /* set port */
12244    if (((get_transport_str2enum(transport) == SIP_TRANSPORT_TLS)) || !(strncasecmp(fullcontact, "sips", 4))) {
12245       port = port_str2int(pt, STANDARD_TLS_PORT);
12246    } else {
12247       port = port_str2int(pt, STANDARD_SIP_PORT);
12248    }
12249 
12250 
12251    /* XXX This could block for a long time XXX */
12252    /* We should only do this if it's a name, not an IP */
12253    /* \todo - if there's no PORT number in contact - we are required to check NAPTR/SRV records
12254       to find transport, port address and hostname. If there's a port number, we have to
12255       assume that the domain part is a host name and only look for an A/AAAA record in DNS.
12256    */
12257    hp = ast_gethostbyname(host, &ahp);
12258    if (!hp)  {
12259       ast_log(LOG_WARNING, "Invalid host name in Contact: (can't resolve in DNS) : '%s'\n", host);
12260       return -1;
12261    }
12262    sin->sin_family = AF_INET;
12263    memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
12264    sin->sin_port = htons(port);
12265 
12266    return 0;
12267 }
12268 
12269 /*! \brief Change the other partys IP address based on given contact */
12270 static int set_address_from_contact(struct sip_pvt *pvt)
12271 {
12272    if (ast_test_flag(&pvt->flags[0], SIP_NAT_ROUTE)) {
12273       /* NAT: Don't trust the contact field.  Just use what they came to us
12274          with. */
12275       /*! \todo We need to save the TRANSPORT here too */
12276       pvt->sa = pvt->recv;
12277       return 0;
12278    }
12279 
12280    return __set_address_from_contact(pvt->fullcontact, &pvt->sa, pvt->socket.type == SIP_TRANSPORT_TLS ? 1 : 0);
12281 }
12282 
12283 /*! \brief Parse contact header and save registration (peer registration) */
12284 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
12285 {
12286    char contact[SIPBUFSIZE];
12287    char data[SIPBUFSIZE];
12288    const char *expires = get_header(req, "Expires");
12289    int expire = atoi(expires);
12290    char *curi, *host, *pt, *transport;
12291    int port;
12292    int transport_type;
12293    const char *useragent;
12294    struct hostent *hp;
12295    struct ast_hostent ahp;
12296    struct sockaddr_in oldsin, testsin;
12297 
12298 
12299    ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
12300 
12301    if (ast_strlen_zero(expires)) {  /* No expires header, try look in Contact: */
12302       char *s = strcasestr(contact, ";expires=");
12303       if (s) {
12304          expires = strsep(&s, ";"); /* trim ; and beyond */
12305          if (sscanf(expires + 9, "%30d", &expire) != 1)
12306             expire = default_expiry;
12307       } else {
12308          /* Nothing has been specified */
12309          expire = default_expiry;
12310       }
12311    }
12312 
12313    copy_socket_data(&pvt->socket, &req->socket);
12314 
12315    /* Look for brackets */
12316    curi = contact;
12317    if (strchr(contact, '<') == NULL)   /* No <, check for ; and strip it */
12318       strsep(&curi, ";");  /* This is Header options, not URI options */
12319    curi = get_in_brackets(contact);
12320 
12321    /* if they did not specify Contact: or Expires:, they are querying
12322       what we currently have stored as their contact address, so return
12323       it
12324    */
12325    if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
12326       /* If we have an active registration, tell them when the registration is going to expire */
12327       if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact))
12328          pvt->expiry = ast_sched_when(sched, peer->expire);
12329       return PARSE_REGISTER_QUERY;
12330    } else if (!strcasecmp(curi, "*") || !expire) { /* Unregister this peer */
12331       /* This means remove all registrations and return OK */
12332       memset(&peer->addr, 0, sizeof(peer->addr));
12333       set_socket_transport(&peer->socket, peer->default_outbound_transport);
12334 
12335       AST_SCHED_DEL_UNREF(sched, peer->expire,
12336             unref_peer(peer, "remove register expire ref"));
12337 
12338       destroy_association(peer);
12339 
12340       register_peer_exten(peer, FALSE);   /* Remove extension from regexten= setting in sip.conf */
12341       ast_string_field_set(peer, fullcontact, "");
12342       ast_string_field_set(peer, useragent, "");
12343       peer->sipoptions = 0;
12344       peer->lastms = 0;
12345       peer->portinuri = 0;
12346       pvt->expiry = 0;
12347 
12348       ast_verb(3, "Unregistered SIP '%s'\n", peer->name);
12349 
12350       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\n", peer->name);
12351       return PARSE_REGISTER_UPDATE;
12352    }
12353 
12354    /* Store whatever we got as a contact from the client */
12355    ast_string_field_set(peer, fullcontact, curi);
12356 
12357    /* For the 200 OK, we should use the received contact */
12358    ast_string_field_build(pvt, our_contact, "<%s>", curi);
12359 
12360    /* Make sure it's a SIP URL */
12361    if (parse_uri(curi, "sip:,sips:", &curi, NULL, &host, &pt, NULL, &transport)) {
12362       ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:) trying to use anyway\n");
12363    }
12364 
12365    /* If we have a port number in the given URI, make sure we do remember to not check for NAPTR/SRV records. 
12366       The domain part is actually a host. */
12367    peer->portinuri = !ast_strlen_zero(pt) ? TRUE : FALSE;
12368 
12369    /* handle the transport type specified in Contact header. */
12370    if ((transport_type = get_transport_str2enum(transport))) {
12371       /* if the port is not specified but the transport is, make sure to set the
12372        * default port to match the specified transport.  This may or may not be the
12373        * same transport used by the pvt struct for the Register dialog. */
12374       
12375       port = port_str2int(pt, (transport_type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
12376    } else {
12377       port = port_str2int(pt, STANDARD_SIP_PORT);
12378       transport_type = pvt->socket.type;
12379    }
12380 
12381    /* if the peer's socket type is different than the Registration
12382     * transport type, change it.  If it got this far, it is a
12383     * supported type, but check just in case */
12384    if ((peer->socket.type != transport_type) && (peer->transports & transport_type)) {
12385       set_socket_transport(&peer->socket, transport_type);
12386    }
12387 
12388    oldsin = peer->addr;
12389 
12390    /* If we were already linked into the peers_by_ip container unlink ourselves so nobody can find us */
12391    if (peer->addr.sin_addr.s_addr) {
12392       ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
12393    }
12394 
12395    if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE)) {
12396       /* use the data provided in the Contact header for call routing */
12397       ast_debug(1, "Store REGISTER's Contact header for call routing.\n");
12398       /* XXX This could block for a long time XXX */
12399       /*! \todo Check NAPTR/SRV if we have not got a port in the URI */
12400       hp = ast_gethostbyname(host, &ahp);
12401       if (!hp)  {
12402          ast_log(LOG_WARNING, "Invalid host '%s'\n", host);
12403          ast_string_field_set(peer, fullcontact, "");
12404          ast_string_field_set(pvt, our_contact, "");
12405          return PARSE_REGISTER_FAILED;
12406       }
12407       peer->addr.sin_family = AF_INET;
12408       memcpy(&peer->addr.sin_addr, hp->h_addr, sizeof(peer->addr.sin_addr));
12409       peer->addr.sin_port = htons(port);
12410    } else {
12411       /* Don't trust the contact field.  Just use what they came to us
12412          with */
12413       ast_debug(1, "Store REGISTER's src-IP:port for call routing.\n");
12414       peer->addr = pvt->recv;
12415    }
12416 
12417    /* Check that they're allowed to register at this IP */
12418    memcpy(&testsin.sin_addr, &peer->addr.sin_addr, sizeof(testsin.sin_addr));
12419    if (ast_apply_ha(global_contact_ha, &testsin) != AST_SENSE_ALLOW ||
12420          ast_apply_ha(peer->contactha, &testsin) != AST_SENSE_ALLOW) {
12421       ast_log(LOG_WARNING, "Host '%s' disallowed by contact ACL (violating IP %s)\n", host, ast_inet_ntoa(testsin.sin_addr));
12422       ast_string_field_set(peer, fullcontact, "");
12423       ast_string_field_set(pvt, our_contact, "");
12424       return PARSE_REGISTER_DENIED;
12425    }
12426 
12427    /* if the Contact header information copied into peer->addr matches the
12428     * received address, and the transport types are the same, then copy socket
12429     * data into the peer struct */
12430    if ((peer->socket.type == pvt->socket.type) &&
12431       (peer->addr.sin_addr.s_addr == pvt->recv.sin_addr.s_addr) &&
12432       (peer->addr.sin_port == pvt->recv.sin_port)){
12433 
12434       copy_socket_data(&peer->socket, &pvt->socket);
12435    }
12436 
12437    /* Now that our address has been updated put ourselves back into the container for lookups */
12438    ao2_t_link(peers_by_ip, peer, "ao2_link into peers_by_ip table");
12439 
12440    /* Save SIP options profile */
12441    peer->sipoptions = pvt->sipoptions;
12442 
12443    if (!ast_strlen_zero(curi) && ast_strlen_zero(peer->username))
12444       ast_string_field_set(peer, username, curi);
12445 
12446    AST_SCHED_DEL_UNREF(sched, peer->expire,
12447          unref_peer(peer, "remove register expire ref"));
12448 
12449    if (expire > max_expiry)
12450       expire = max_expiry;
12451    if (expire < min_expiry)
12452       expire = min_expiry;
12453    if (peer->is_realtime && !ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
12454       peer->expire = -1;
12455    } else {
12456       peer->expire = ast_sched_add(sched, (expire + 10) * 1000, expire_register,
12457             ref_peer(peer, "add registration ref"));
12458       if (peer->expire == -1) {
12459          unref_peer(peer, "remote registration ref");
12460       }
12461    }
12462    pvt->expiry = expire;
12463    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);
12464    /* Saving TCP connections is useless, we won't be able to reconnect 
12465       XXX WHY???? XXX
12466       \todo Fix this immediately.
12467    */
12468    if (!peer->rt_fromcontact && (peer->socket.type & SIP_TRANSPORT_UDP))
12469       ast_db_put("SIP/Registry", peer->name, data);
12470    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));
12471 
12472    /* Is this a new IP address for us? */
12473    if (VERBOSITY_ATLEAST(2) && inaddrcmp(&peer->addr, &oldsin)) {
12474       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));
12475    }
12476    sip_poke_peer(peer, 0);
12477    register_peer_exten(peer, 1);
12478    
12479    /* Save User agent */
12480    useragent = get_header(req, "User-Agent");
12481    if (strcasecmp(useragent, peer->useragent)) {
12482       ast_string_field_set(peer, useragent, useragent);
12483       ast_verb(4, "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
12484    }
12485    return PARSE_REGISTER_UPDATE;
12486 }
12487 
12488 /*! \brief Remove route from route list */
12489 static void free_old_route(struct sip_route *route)
12490 {
12491    struct sip_route *next;
12492 
12493    while (route) {
12494       next = route->next;
12495       ast_free(route);
12496       route = next;
12497    }
12498 }
12499 
12500 /*! \brief List all routes - mostly for debugging */
12501 static void list_route(struct sip_route *route)
12502 {
12503    if (!route)
12504       ast_verbose("list_route: no route\n");
12505    else {
12506       for (;route; route = route->next)
12507          ast_verbose("list_route: hop: <%s>\n", route->hop);
12508    }
12509 }
12510 
12511 /*! \brief Build route list from Record-Route header */
12512 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
12513 {
12514    struct sip_route *thishop, *head, *tail;
12515    int start = 0;
12516    int len;
12517    const char *rr, *contact, *c;
12518 
12519    /* Once a persistant route is set, don't fool with it */
12520    if (p->route && p->route_persistant) {
12521       ast_debug(1, "build_route: Retaining previous route: <%s>\n", p->route->hop);
12522       return;
12523    }
12524 
12525    if (p->route) {
12526       free_old_route(p->route);
12527       p->route = NULL;
12528    }
12529 
12530    /* We only want to create the route set the first time this is called */
12531    p->route_persistant = 1;
12532    
12533    /* Build a tailq, then assign it to p->route when done.
12534     * If backwards, we add entries from the head so they end up
12535     * in reverse order. However, we do need to maintain a correct
12536     * tail pointer because the contact is always at the end.
12537     */
12538    head = NULL;
12539    tail = head;
12540    /* 1st we pass through all the hops in any Record-Route headers */
12541    for (;;) {
12542       /* Each Record-Route header */
12543       rr = __get_header(req, "Record-Route", &start);
12544       if (*rr == '\0')
12545          break;
12546       for (; (rr = strchr(rr, '<')) ; rr += len) { /* Each route entry */
12547          ++rr;
12548          len = strcspn(rr, ">") + 1;
12549          /* Make a struct route */
12550          if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
12551             /* ast_calloc is not needed because all fields are initialized in this block */
12552             ast_copy_string(thishop->hop, rr, len);
12553             ast_debug(2, "build_route: Record-Route hop: <%s>\n", thishop->hop);
12554             /* Link in */
12555             if (backwards) {
12556                /* Link in at head so they end up in reverse order */
12557                thishop->next = head;
12558                head = thishop;
12559                /* If this was the first then it'll be the tail */
12560                if (!tail)
12561                   tail = thishop;
12562             } else {
12563                thishop->next = NULL;
12564                /* Link in at the end */
12565                if (tail)
12566                   tail->next = thishop;
12567                else
12568                   head = thishop;
12569                tail = thishop;
12570             }
12571          }
12572       }
12573    }
12574 
12575    /* Only append the contact if we are dealing with a strict router */
12576    if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop, ";lr") == NULL) ) {
12577       /* 2nd append the Contact: if there is one */
12578       /* Can be multiple Contact headers, comma separated values - we just take the first */
12579       contact = get_header(req, "Contact");
12580       if (!ast_strlen_zero(contact)) {
12581          ast_debug(2, "build_route: Contact hop: %s\n", contact);
12582          /* Look for <: delimited address */
12583          c = strchr(contact, '<');
12584          if (c) {
12585             /* Take to > */
12586             ++c;
12587             len = strcspn(c, ">") + 1;
12588          } else {
12589             /* No <> - just take the lot */
12590             c = contact;
12591             len = strlen(contact) + 1;
12592          }
12593          if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
12594             /* ast_calloc is not needed because all fields are initialized in this block */
12595             ast_copy_string(thishop->hop, c, len);
12596             thishop->next = NULL;
12597             /* Goes at the end */
12598             if (tail)
12599                tail->next = thishop;
12600             else
12601                head = thishop;
12602          }
12603       }
12604    }
12605 
12606    /* Store as new route */
12607    p->route = head;
12608 
12609    /* For debugging dump what we ended up with */
12610    if (sip_debug_test_pvt(p))
12611       list_route(p->route);
12612 }
12613 
12614 /*! \brief builds the sip_pvt's randdata field which is used for the nonce
12615  *  challenge.  When forceupdate is not set, the nonce is only updated if
12616  *  the current one is stale.  In this case, a stalenonce is one which
12617  *  has already received a response, if a nonce has not received a response
12618  *  it is not always necessary or beneficial to create a new one. */
12619 
12620 static void set_nonce_randdata(struct sip_pvt *p, int forceupdate)
12621 {
12622    if (p->stalenonce || forceupdate || ast_strlen_zero(p->randdata)) {
12623       ast_string_field_build(p, randdata, "%08lx", ast_random()); /* Create nonce for challenge */
12624       p->stalenonce = 0;
12625    }
12626 }
12627 
12628 AST_THREADSTORAGE(check_auth_buf);
12629 #define CHECK_AUTH_BUF_INITLEN   256
12630 
12631 /*! \brief  Check user authorization from peer definition 
12632    Some actions, like REGISTER and INVITEs from peers require
12633    authentication (if peer have secret set) 
12634     \return 0 on success, non-zero on error
12635 */
12636 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
12637                 const char *secret, const char *md5secret, int sipmethod,
12638                 char *uri, enum xmittype reliable, int ignore)
12639 {
12640    const char *response;
12641    char *reqheader, *respheader;
12642    const char *authtoken;
12643    char a1_hash[256];
12644    char resp_hash[256]="";
12645    char *c;
12646    int  wrongnonce = FALSE;
12647    int  good_response;
12648    const char *usednonce = p->randdata;
12649    struct ast_str *buf;
12650    int res;
12651 
12652    /* table of recognised keywords, and their value in the digest */
12653    enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
12654    struct x {
12655       const char *key;
12656       const char *s;
12657    } *i, keys[] = {
12658       [K_RESP] = { "response=", "" },
12659       [K_URI] = { "uri=", "" },
12660       [K_USER] = { "username=", "" },
12661       [K_NONCE] = { "nonce=", "" },
12662       [K_LAST] = { NULL, NULL}
12663    };
12664 
12665    /* Always OK if no secret */
12666    if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
12667       return AUTH_SUCCESSFUL;
12668 
12669    /* Always auth with WWW-auth since we're NOT a proxy */
12670    /* Using proxy-auth in a B2BUA may block proxy authorization in the same transaction */
12671    response = "401 Unauthorized";
12672 
12673    /*
12674     * Note the apparent swap of arguments below, compared to other
12675     * usages of auth_headers().
12676     */
12677    auth_headers(WWW_AUTH, &respheader, &reqheader);
12678 
12679    authtoken =  get_header(req, reqheader);  
12680    if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
12681       /* This is a retransmitted invite/register/etc, don't reconstruct authentication
12682          information */
12683       if (!reliable) {
12684          /* Resend message if this was NOT a reliable delivery.   Otherwise the
12685             retransmission should get it */
12686          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
12687          /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
12688          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12689       }
12690       return AUTH_CHALLENGE_SENT;
12691    } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
12692       /* We have no auth, so issue challenge and request authentication */
12693       set_nonce_randdata(p, 1); /* Create nonce for challenge */
12694       transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
12695       /* Schedule auto destroy in 32 seconds */
12696       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12697       return AUTH_CHALLENGE_SENT;
12698    } 
12699 
12700    /* --- We have auth, so check it */
12701 
12702    /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
12703       an example in the spec of just what it is you're doing a hash on. */
12704 
12705    if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN)))
12706       return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
12707 
12708    /* Make a copy of the response and parse it */
12709    res = ast_str_set(&buf, 0, "%s", authtoken);
12710 
12711    if (res == AST_DYNSTR_BUILD_FAILED)
12712       return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
12713 
12714    c = buf->str;
12715 
12716    while(c && *(c = ast_skip_blanks(c)) ) { /* lookup for keys */
12717       for (i = keys; i->key != NULL; i++) {
12718          const char *separator = ",";  /* default */
12719 
12720          if (strncasecmp(c, i->key, strlen(i->key)) != 0)
12721             continue;
12722          /* Found. Skip keyword, take text in quotes or up to the separator. */
12723          c += strlen(i->key);
12724          if (*c == '"') { /* in quotes. Skip first and look for last */
12725             c++;
12726             separator = "\"";
12727          }
12728          i->s = c;
12729          strsep(&c, separator);
12730          break;
12731       }
12732       if (i->key == NULL) /* not found, jump after space or comma */
12733          strsep(&c, " ,");
12734    }
12735 
12736    /* Verify that digest username matches  the username we auth as */
12737    if (strcmp(username, keys[K_USER].s)) {
12738       ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
12739          username, keys[K_USER].s);
12740       /* Oops, we're trying something here */
12741       return AUTH_USERNAME_MISMATCH;
12742    }
12743 
12744    /* Verify nonce from request matches our nonce, and the nonce has not already been responded to.
12745     * If this check fails, send 401 with new nonce */
12746    if (strcasecmp(p->randdata, keys[K_NONCE].s) || p->stalenonce) { /* XXX it was 'n'casecmp ? */
12747       wrongnonce = TRUE;
12748       usednonce = keys[K_NONCE].s;
12749    } else {
12750       p->stalenonce = 1; /* now, since the nonce has a response, mark it as stale so it can't be sent or responded to again */
12751    }
12752 
12753    if (!ast_strlen_zero(md5secret))
12754       ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
12755    else {
12756       char a1[256];
12757       snprintf(a1, sizeof(a1), "%s:%s:%s", username, sip_cfg.realm, secret);
12758       ast_md5_hash(a1_hash, a1);
12759    }
12760 
12761    /* compute the expected response to compare with what we received */
12762    {
12763       char a2[256];
12764       char a2_hash[256];
12765       char resp[256];
12766 
12767       snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
12768             S_OR(keys[K_URI].s, uri));
12769       ast_md5_hash(a2_hash, a2);
12770       snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
12771       ast_md5_hash(resp_hash, resp);
12772    }
12773 
12774    good_response = keys[K_RESP].s &&
12775          !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
12776    if (wrongnonce) {
12777       if (good_response) {
12778          if (sipdebug)
12779             ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "From"));
12780          /* We got working auth token, based on stale nonce . */
12781          set_nonce_randdata(p, 0);
12782          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
12783       } else {
12784          /* Everything was wrong, so give the device one more try with a new challenge */
12785          if (!req->ignore) {
12786             if (sipdebug)
12787                ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
12788             set_nonce_randdata(p, 1);
12789          } else {
12790             if (sipdebug)
12791                ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", get_header(req, "To"));
12792          }
12793          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
12794       }
12795 
12796       /* Schedule auto destroy in 32 seconds */
12797       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12798       return AUTH_CHALLENGE_SENT;
12799    } 
12800    if (good_response) {
12801       append_history(p, "AuthOK", "Auth challenge successful for %s", username);
12802       return AUTH_SUCCESSFUL;
12803    }
12804 
12805    /* Ok, we have a bad username/secret pair */
12806    /* Tell the UAS not to re-send this authentication data, because
12807       it will continue to fail
12808    */
12809 
12810    return AUTH_SECRET_FAILED;
12811 }
12812 
12813 /*! \brief Change onhold state of a peer using a pvt structure */
12814 static void sip_peer_hold(struct sip_pvt *p, int hold)
12815 {
12816    struct sip_peer *peer = find_peer(p->peername, NULL, 1, FINDALLDEVICES, FALSE, 0);
12817 
12818    if (!peer)
12819       return;
12820 
12821    /* If they put someone on hold, increment the value... otherwise decrement it */
12822    ast_atomic_fetchadd_int(&peer->onHold, (hold ? +1 : -1));
12823 
12824    /* Request device state update */
12825    ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
12826    unref_peer(peer, "sip_peer_hold: from find_peer operation");
12827    
12828    return;
12829 }
12830 
12831 /*! \brief Receive MWI events that we have subscribed to */
12832 static void mwi_event_cb(const struct ast_event *event, void *userdata)
12833 {
12834    struct sip_peer *peer = userdata;
12835 
12836    ao2_lock(peer);
12837    sip_send_mwi_to_peer(peer, event, 0);
12838    ao2_unlock(peer);
12839 }
12840 
12841 /*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem
12842 \note If you add an "hint" priority to the extension in the dial plan,
12843    you will get notifications on device state changes */
12844 static int cb_extensionstate(char *context, char* exten, int state, void *data)
12845 {
12846    struct sip_pvt *p = data;
12847 
12848    sip_pvt_lock(p);
12849 
12850    switch(state) {
12851    case AST_EXTENSION_DEACTIVATED:  /* Retry after a while */
12852    case AST_EXTENSION_REMOVED:   /* Extension is gone */
12853       if (p->autokillid > -1 && sip_cancel_destroy(p))   /* Remove subscription expiry for renewals */
12854          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
12855       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);  /* Delete subscription in 32 secs */
12856       ast_verb(2, "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
12857       p->stateid = -1;
12858       p->subscribed = NONE;
12859       append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
12860       break;
12861    default: /* Tell user */
12862       p->laststate = state;
12863       break;
12864    }
12865    if (p->subscribed != NONE) {  /* Only send state NOTIFY if we know the format */
12866       if (!p->pendinginvite) {
12867          transmit_state_notify(p, state, 1, FALSE);
12868       } else {
12869          /* We already have a NOTIFY sent that is not answered. Queue the state up.
12870             if many state changes happen meanwhile, we will only send a notification of the last one */
12871          ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
12872       }
12873    }
12874    ast_verb(2, "Extension Changed %s[%s] new state %s for Notify User %s %s\n", exten, context, ast_extension_state2str(state), p->username,
12875          ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
12876 
12877    sip_pvt_unlock(p);
12878 
12879    return 0;
12880 }
12881 
12882 /*! \brief Send a fake 401 Unauthorized response when the administrator
12883   wants to hide the names of local devices  from fishers
12884  */
12885 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable)
12886 {
12887    /* We have to emulate EXACTLY what we'd get with a good peer
12888     * and a bad password, or else we leak information. */
12889    const char *response = "407 Proxy Authentication Required";
12890    const char *reqheader = "Proxy-Authorization";
12891    const char *respheader = "Proxy-Authenticate";
12892    const char *authtoken;
12893    struct ast_str *buf;
12894    char *c;
12895 
12896    /* table of recognised keywords, and their value in the digest */
12897    enum keys { K_NONCE, K_LAST };
12898    struct x {
12899       const char *key;
12900       const char *s;
12901    } *i, keys[] = {
12902       [K_NONCE] = { "nonce=", "" },
12903       [K_LAST] = { NULL, NULL}
12904    };
12905 
12906    if (sipmethod == SIP_REGISTER || sipmethod == SIP_SUBSCRIBE) {
12907       response = "401 Unauthorized";
12908       reqheader = "Authorization";
12909       respheader = "WWW-Authenticate";
12910    }
12911    authtoken = get_header(req, reqheader);
12912    if (req->ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
12913       /* This is a retransmitted invite/register/etc, don't reconstruct authentication
12914        * information */
12915       transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
12916       /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
12917       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12918       return;
12919    } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
12920       /* We have no auth, so issue challenge and request authentication */
12921       set_nonce_randdata(p, 1);
12922       transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
12923       /* Schedule auto destroy in 32 seconds */
12924       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12925       return;
12926    }
12927 
12928    if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
12929       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
12930       return;
12931    }
12932 
12933    /* Make a copy of the response and parse it */
12934    if (ast_str_set(&buf, 0, "%s", authtoken) == AST_DYNSTR_BUILD_FAILED) {
12935       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
12936       return;
12937    }
12938 
12939    c = buf->str;
12940 
12941    while (c && *(c = ast_skip_blanks(c))) { /* lookup for keys */
12942       for (i = keys; i->key != NULL; i++) {
12943          const char *separator = ",";  /* default */
12944 
12945          if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
12946             continue;
12947          }
12948          /* Found. Skip keyword, take text in quotes or up to the separator. */
12949          c += strlen(i->key);
12950          if (*c == '"') { /* in quotes. Skip first and look for last */
12951             c++;
12952             separator = "\"";
12953          }
12954          i->s = c;
12955          strsep(&c, separator);
12956          break;
12957       }
12958       if (i->key == NULL) { /* not found, jump after space or comma */
12959          strsep(&c, " ,");
12960       }
12961    }
12962 
12963    /* Verify nonce from request matches our nonce.  If not, send 401 with new nonce */
12964    if (strcasecmp(p->randdata, keys[K_NONCE].s)) {
12965       if (!req->ignore) {
12966          set_nonce_randdata(p, 1);
12967       }
12968       transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
12969 
12970       /* Schedule auto destroy in 32 seconds */
12971       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12972    } else {
12973       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
12974    }
12975 }
12976 
12977 /*!
12978  * Terminate the uri at the first ';' or space.
12979  * Technically we should ignore escaped space per RFC3261 (19.1.1 etc)
12980  * but don't do it for the time being. Remember the uri format is:
12981  * (User-parameters was added after RFC 3261)
12982  *\verbatim
12983  *
12984  * sip:user:password;user-parameters@host:port;uri-parameters?headers
12985  * sips:user:password;user-parameters@host:port;uri-parameters?headers
12986  *
12987  *\endverbatim
12988  * \todo As this function does not support user-parameters, it's considered broken
12989  * and needs fixing.
12990  */
12991 static char *terminate_uri(char *uri)
12992 {
12993    char *t = uri;
12994    while (*t && *t > ' ' && *t != ';')
12995       t++;
12996    *t = '\0';
12997    return uri;
12998 }
12999 
13000 /*! \brief Verify registration of user 
13001    - Registration is done in several steps, first a REGISTER without auth
13002      to get a challenge (nonce) then a second one with auth
13003    - Registration requests are only matched with peers that are marked as "dynamic"
13004  */
13005 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
13006                      struct sip_request *req, char *uri)
13007 {
13008    enum check_auth_result res = AUTH_NOT_FOUND;
13009    struct sip_peer *peer;
13010    char tmp[256];
13011    char *name, *c;
13012    char *domain;
13013 
13014    terminate_uri(uri);  /* warning, overwrite the string */
13015 
13016    ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
13017    if (sip_cfg.pedanticsipchecking)
13018       ast_uri_decode(tmp);
13019 
13020    c = get_in_brackets(tmp);
13021    c = remove_uri_parameters(c);
13022 
13023    if (!strncasecmp(c, "sip:", 4)) {
13024       name = c + 4;
13025    } else if (!strncasecmp(c, "sips:", 5)) {
13026       name = c + 5;
13027    } else {
13028       name = c;
13029       ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_inet_ntoa(sin->sin_addr));
13030    }
13031 
13032    /*! \todo XXX here too we interpret a missing @domain as a name-only
13033     * URI, whereas the RFC says this is a domain-only uri.
13034     */
13035    /* Strip off the domain name */
13036    if ((c = strchr(name, '@'))) {
13037       *c++ = '\0';
13038       domain = c;
13039       if ((c = strchr(domain, ':')))   /* Remove :port */
13040          *c = '\0';
13041       if (!AST_LIST_EMPTY(&domain_list)) {
13042          if (!check_sip_domain(domain, NULL, 0)) {
13043             transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
13044             return AUTH_UNKNOWN_DOMAIN;
13045          }
13046       }
13047    }
13048    c = strchr(name, ';');  /* Remove any Username parameters */
13049    if (c)
13050       *c = '\0';
13051 
13052    ast_string_field_set(p, exten, name);
13053    build_contact(p);
13054    if (req->ignore) {
13055       /* Expires is a special case, where we only want to load the peer if this isn't a deregistration attempt */
13056       const char *expires = get_header(req, "Expires");
13057       int expire = atoi(expires);
13058 
13059       if (ast_strlen_zero(expires)) { /* No expires header; look in Contact */
13060          if ((expires = strcasestr(get_header(req, "Contact"), ";expires="))) {
13061             expire = atoi(expires + 9);
13062          }
13063       }
13064       if (!ast_strlen_zero(expires) && expire == 0) {
13065          transmit_response_with_date(p, "200 OK", req);
13066          return 0;
13067       }
13068    }
13069    peer = find_peer(name, NULL, TRUE, FINDPEERS, FALSE, 0);
13070    if (!(peer && ast_apply_ha(peer->ha, sin))) {
13071       /* Peer fails ACL check */
13072       if (peer) {
13073          unref_peer(peer, "register_verify: unref_peer: from find_peer operation");
13074          peer = NULL;
13075          res = AUTH_ACL_FAILED;
13076       } else
13077          res = AUTH_NOT_FOUND;
13078    }
13079 
13080    if (peer) {
13081       /*! \todo OEJ Remove this - there's never RTP in a REGISTER dialog... */
13082       /* Set Frame packetization */
13083       if (p->rtp) {
13084          ast_rtp_codec_setpref(p->rtp, &peer->prefs);
13085          p->autoframing = peer->autoframing;
13086       }
13087       if (!peer->host_dynamic) {
13088          ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
13089          res = AUTH_PEER_NOT_DYNAMIC;
13090       } else {
13091          ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT);
13092          if (ast_test_flag(&p->flags[1], SIP_PAGE2_REGISTERTRYING))
13093             transmit_response(p, "100 Trying", req);
13094          if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri, XMIT_UNRELIABLE, req->ignore))) {
13095             if (sip_cancel_destroy(p))
13096                ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
13097 
13098             if (check_request_transport(peer, req)) {
13099                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
13100                transmit_response_with_date(p, "403 Forbidden", req);
13101                res = AUTH_BAD_TRANSPORT;
13102             } else {
13103 
13104                /* We have a successful registration attempt with proper authentication,
13105                   now, update the peer */
13106                switch (parse_register_contact(p, peer, req)) {
13107                case PARSE_REGISTER_DENIED:
13108                   ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
13109                   transmit_response_with_date(p, "603 Denied", req);
13110                   peer->lastmsgssent = -1;
13111                   res = 0;
13112                   break;
13113                case PARSE_REGISTER_FAILED:
13114                   ast_log(LOG_WARNING, "Failed to parse contact info\n");
13115                   transmit_response_with_date(p, "400 Bad Request", req);
13116                   peer->lastmsgssent = -1;
13117                   res = 0;
13118                   break;
13119                case PARSE_REGISTER_QUERY:
13120                   ast_string_field_set(p, fullcontact, peer->fullcontact);
13121                   transmit_response_with_date(p, "200 OK", req);
13122                   peer->lastmsgssent = -1;
13123                   res = 0;
13124                   break;
13125                case PARSE_REGISTER_UPDATE:
13126                   ast_string_field_set(p, fullcontact, peer->fullcontact);
13127                   update_peer(peer, p->expiry);
13128                   /* Say OK and ask subsystem to retransmit msg counter */
13129                   transmit_response_with_date(p, "200 OK", req);
13130                   if (!ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY))
13131                      peer->lastmsgssent = -1;
13132                   res = 0;
13133                   break;
13134                }
13135             }
13136 
13137          } 
13138       }
13139    }
13140    if (!peer && sip_cfg.autocreatepeer) {
13141       /* Create peer if we have autocreate mode enabled */
13142       peer = temp_peer(name);
13143       if (peer) {
13144          ao2_t_link(peers, peer, "link peer into peer table");
13145          if (peer->addr.sin_addr.s_addr) {
13146             ao2_t_link(peers_by_ip, peer, "link peer into peers-by-ip table");
13147          }
13148          
13149          if (sip_cancel_destroy(p))
13150             ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
13151          switch (parse_register_contact(p, peer, req)) {
13152          case PARSE_REGISTER_DENIED:
13153             ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
13154             transmit_response_with_date(p, "403 Forbidden (ACL)", req);
13155             peer->lastmsgssent = -1;
13156             res = 0;
13157             break;
13158          case PARSE_REGISTER_FAILED:
13159             ast_log(LOG_WARNING, "Failed to parse contact info\n");
13160             transmit_response_with_date(p, "400 Bad Request", req);
13161             peer->lastmsgssent = -1;
13162             res = 0;
13163             break;
13164          case PARSE_REGISTER_QUERY:
13165             ast_string_field_set(p, fullcontact, peer->fullcontact);
13166             transmit_response_with_date(p, "200 OK", req);
13167             peer->lastmsgssent = -1;
13168             res = 0;
13169             break;
13170          case PARSE_REGISTER_UPDATE:
13171             ast_string_field_set(p, fullcontact, peer->fullcontact);
13172             /* Say OK and ask subsystem to retransmit msg counter */
13173             transmit_response_with_date(p, "200 OK", req);
13174             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));
13175             peer->lastmsgssent = -1;
13176             res = 0;
13177             break;
13178          }
13179       }
13180    }
13181    if (!peer && sip_cfg.alwaysauthreject) {
13182       /* If we found a peer, we transmit a 100 Trying.  Therefore, if we're
13183        * trying to avoid leaking information, we MUST also transmit the same
13184        * response when we DON'T find a peer. */
13185       transmit_response(p, "100 Trying", req);
13186       /* Insert a fake delay between the 100 and the subsequent failure. */
13187       sched_yield();
13188    }
13189    if (!res) {
13190       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
13191    }
13192    if (res < 0) {
13193       switch (res) {
13194       case AUTH_SECRET_FAILED:
13195          /* Wrong password in authentication. Go away, don't try again until you fixed it */
13196          transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
13197          if (global_authfailureevents)
13198             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", 
13199                name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13200          break;
13201       case AUTH_USERNAME_MISMATCH:
13202          /* Username and digest username does not match.
13203             Asterisk uses the From: username for authentication. We need the
13204             devices to use the same authentication user name until we support
13205             proper authentication by digest auth name */
13206       case AUTH_NOT_FOUND:
13207       case AUTH_PEER_NOT_DYNAMIC:
13208       case AUTH_ACL_FAILED:
13209          if (sip_cfg.alwaysauthreject) {
13210             transmit_fake_auth_response(p, SIP_REGISTER, &p->initreq, XMIT_UNRELIABLE);
13211             if (global_authfailureevents) {
13212                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",
13213                   name, res == AUTH_PEER_NOT_DYNAMIC ? "AUTH_PEER_NOT_DYNAMIC" : "URI_NOT_FOUND",
13214                   ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13215             }
13216          } else {
13217             /* URI not found */
13218             if (res == AUTH_PEER_NOT_DYNAMIC) {
13219                transmit_response(p, "403 Forbidden", &p->initreq);
13220                if (global_authfailureevents) {
13221                   manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
13222                      "ChannelType: SIP\r\n"
13223                      "Peer: SIP/%s\r\n"
13224                      "PeerStatus: Rejected\r\n"
13225                      "Cause: AUTH_PEER_NOT_DYNAMIC\r\n"
13226                      "Address: %s\r\n"
13227                      "Port: %d\r\n",
13228                      name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13229                }
13230             } else {
13231                transmit_response(p, "404 Not found", &p->initreq);
13232                if (global_authfailureevents) {
13233                   manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
13234                      "ChannelType: SIP\r\n"
13235                      "Peer: SIP/%s\r\n"
13236                      "PeerStatus: Rejected\r\n"
13237                      "Cause: %s\r\n"
13238                      "Address: %s\r\n"
13239                      "Port: %d\r\n",
13240                      name,
13241                      (res == AUTH_USERNAME_MISMATCH) ? "AUTH_USERNAME_MISMATCH" : "URI_NOT_FOUND",
13242                      ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13243                }
13244             }
13245          }
13246          break;
13247       case AUTH_BAD_TRANSPORT:
13248       default:
13249          break;
13250       }
13251    }
13252    if (peer)
13253       unref_peer(peer, "register_verify: unref_peer: tossing stack peer pointer at end of func");
13254 
13255    return res;
13256 }
13257 
13258 /*! \brief Translate referring cause */
13259 static void sip_set_redirstr(struct sip_pvt *p, char *reason) {
13260 
13261    if (!strcmp(reason, "unknown")) {
13262       ast_string_field_set(p, redircause, "UNKNOWN");
13263    } else if (!strcmp(reason, "user-busy")) {
13264       ast_string_field_set(p, redircause, "BUSY");
13265    } else if (!strcmp(reason, "no-answer")) {
13266       ast_string_field_set(p, redircause, "NOANSWER");
13267    } else if (!strcmp(reason, "unavailable")) {
13268       ast_string_field_set(p, redircause, "UNREACHABLE");
13269    } else if (!strcmp(reason, "unconditional")) {
13270       ast_string_field_set(p, redircause, "UNCONDITIONAL");
13271    } else if (!strcmp(reason, "time-of-day")) {
13272       ast_string_field_set(p, redircause, "UNKNOWN");
13273    } else if (!strcmp(reason, "do-not-disturb")) {
13274       ast_string_field_set(p, redircause, "UNKNOWN");
13275    } else if (!strcmp(reason, "deflection")) {
13276       ast_string_field_set(p, redircause, "UNKNOWN");
13277    } else if (!strcmp(reason, "follow-me")) {
13278       ast_string_field_set(p, redircause, "UNKNOWN");
13279    } else if (!strcmp(reason, "out-of-service")) {
13280       ast_string_field_set(p, redircause, "UNREACHABLE");
13281    } else if (!strcmp(reason, "away")) {
13282       ast_string_field_set(p, redircause, "UNREACHABLE");
13283    } else {
13284       ast_string_field_set(p, redircause, "UNKNOWN");
13285    }
13286 }
13287 
13288 /*! \brief Get referring dnis */
13289 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq)
13290 {
13291    char tmp[256], *exten, *rexten, *rdomain;
13292    char *params, *reason = NULL;
13293    struct sip_request *req;
13294    
13295    req = oreq ? oreq : &p->initreq;
13296 
13297    ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
13298    if (ast_strlen_zero(tmp))
13299       return 0;
13300 
13301    /*! \todo This function does not take user-parameters into consideration.
13302       First look for @, then start looking for ; to find uri-parameters.
13303    */
13304    params = strchr(tmp, ';');
13305 
13306    exten = get_in_brackets(tmp);
13307    if (!strncasecmp(exten, "sip:", 4)) {
13308       exten += 4;
13309    } else if (!strncasecmp(exten, "sips:", 5)) {
13310       exten += 5;
13311    } else {
13312       ast_log(LOG_WARNING, "Huh?  Not an RDNIS SIP header (%s)?\n", exten);
13313       return -1;
13314    }
13315 
13316    /* Get diversion-reason param if present */
13317    if (params) {
13318       *params = '\0';   /* Cut off parameters  */
13319       params++;
13320       while (*params == ';' || *params == ' ')
13321          params++;
13322       /* Check if we have a reason parameter */
13323       if ((reason = strcasestr(params, "reason="))) {
13324          reason+=7;
13325          /* Remove enclosing double-quotes */
13326          if (*reason == '"') 
13327             ast_strip_quoted(reason, "\"", "\"");
13328          if (!ast_strlen_zero(reason)) {
13329             sip_set_redirstr(p, reason);
13330             if (p->owner) {
13331                pbx_builtin_setvar_helper(p->owner, "__PRIREDIRECTREASON", p->redircause);
13332                pbx_builtin_setvar_helper(p->owner, "__SIPREDIRECTREASON", reason);
13333             }
13334          }
13335       }
13336    }
13337 
13338    rdomain = exten;
13339    rexten = strsep(&rdomain, "@");  /* trim anything after @ */
13340    if (p->owner) 
13341       pbx_builtin_setvar_helper(p->owner, "__SIPRDNISDOMAIN", rdomain);
13342 
13343    if (sip_debug_test_pvt(p))
13344       ast_verbose("RDNIS for this call is is %s (reason %s)\n", exten, reason ? reason : "");
13345 
13346    ast_string_field_set(p, rdnis, rexten);
13347 
13348    return 0;
13349 }
13350 
13351 /*! \brief Find out who the call is for.
13352    We use the request uri as a destination. 
13353    This code assumes authentication has been done, so that the
13354    device (peer/user) context is already set.
13355    \return 0 on success (found a matching extension),
13356    1 for pickup extension or overlap dialling support (if we support it),
13357    -1 on error.
13358 
13359   \note If the incoming uri is a SIPS: uri, we are required to carry this across
13360    the dialplan, so that the outbound call also is a sips: call or encrypted
13361    IAX2 call. If that's not available, the call should FAIL.
13362 */
13363 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
13364 {
13365    char tmp[256] = "", *uri, *a;
13366    char tmpf[256] = "", *from = NULL;
13367    struct sip_request *req;
13368    char *colon;
13369    char *decoded_uri;
13370    
13371    req = oreq;
13372    if (!req)
13373       req = &p->initreq;
13374 
13375    /* Find the request URI */
13376    if (req->rlPart2)
13377       ast_copy_string(tmp, REQ_OFFSET_TO_STR(req, rlPart2), sizeof(tmp));
13378    
13379    if (sip_cfg.pedanticsipchecking)
13380       ast_uri_decode(tmp);
13381 
13382    uri = get_in_brackets(tmp);
13383    
13384    if (!strncasecmp(uri, "sip:", 4)) {
13385       uri += 4;
13386    } else if (!strncasecmp(uri, "sips:", 5)) {
13387       uri += 5;
13388    } else {
13389       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", uri);
13390       return -1;
13391    }
13392 
13393    /* Now find the From: caller ID and name */
13394    /* XXX Why is this done in get_destination? Isn't it already done?
13395       Needs to be checked 
13396         */
13397    ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
13398    if (!ast_strlen_zero(tmpf)) {
13399       if (sip_cfg.pedanticsipchecking)
13400          ast_uri_decode(tmpf);
13401       from = get_in_brackets(tmpf);
13402    } 
13403    
13404    if (!ast_strlen_zero(from)) {
13405       if (!strncasecmp(from, "sip:", 4)) {
13406          from += 4;
13407       } else if (!strncasecmp(from, "sips:", 5)) {
13408          from += 5;
13409       } else {
13410          ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", from);
13411          return -1;
13412       }
13413       if ((a = strchr(from, '@')))
13414          *a++ = '\0';
13415       else
13416          a = from;   /* just a domain */
13417       from = strsep(&from, ";"); /* Remove userinfo options */
13418       a = strsep(&a, ";");    /* Remove URI options */
13419       ast_string_field_set(p, fromdomain, a);
13420    }
13421 
13422    /* Skip any options and find the domain */
13423 
13424    /* Get the target domain */
13425    if ((a = strchr(uri, '@'))) {
13426       *a++ = '\0';
13427    } else { /* No username part */
13428       a = uri;
13429       uri = "s";  /* Set extension to "s" */
13430    }
13431    colon = strchr(a, ':'); /* Remove :port */
13432    if (colon)
13433       *colon = '\0';
13434 
13435    uri = strsep(&uri, ";");   /* Remove userinfo options */
13436    a = strsep(&a, ";");    /* Remove URI options */
13437 
13438    ast_string_field_set(p, domain, a);
13439 
13440    if (!AST_LIST_EMPTY(&domain_list)) {
13441       char domain_context[AST_MAX_EXTENSION];
13442 
13443       domain_context[0] = '\0';
13444       if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
13445          if (!sip_cfg.allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
13446             ast_debug(1, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
13447             return -2;
13448          }
13449       }
13450       /* If we don't have a peer (i.e. we're a guest call),
13451        * overwrite the original context */
13452       if (!ast_test_flag(&p->flags[1], SIP_PAGE2_HAVEPEERCONTEXT) && !ast_strlen_zero(domain_context))
13453          ast_string_field_set(p, context, domain_context);
13454    }
13455 
13456    /* If the request coming in is a subscription and subscribecontext has been specified use it */
13457    if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext))
13458       ast_string_field_set(p, context, p->subscribecontext);
13459 
13460    if (sip_debug_test_pvt(p))
13461       ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
13462 
13463    /* If this is a subscription we actually just need to see if a hint exists for the extension */
13464    if (req->method == SIP_SUBSCRIBE) {
13465       char hint[AST_MAX_EXTENSION];
13466       return (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten) ? 0 : -1);
13467    } else {
13468       decoded_uri = ast_strdupa(uri);
13469       ast_uri_decode(decoded_uri);
13470       /* Check the dialplan for the username part of the request URI,
13471          the domain will be stored in the SIPDOMAIN variable
13472          Since extensions.conf can have unescaped characters, try matching a decoded
13473          uri in addition to the non-decoded uri
13474          Return 0 if we have a matching extension */
13475       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)) ||
13476           !strcmp(decoded_uri, ast_pickup_ext())) {
13477          if (!oreq)
13478             ast_string_field_set(p, exten, decoded_uri);
13479          return 0;
13480       } 
13481    }
13482 
13483    /* Return 1 for pickup extension or overlap dialling support (if we support it) */
13484    if((ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) && 
13485        ast_canmatch_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))) ||
13486        !strncmp(decoded_uri, ast_pickup_ext(), strlen(decoded_uri))) {
13487       return 1;
13488    }
13489    
13490    return -1;
13491 }
13492 
13493 /*! \brief Lock dialog lock and find matching pvt lock  
13494    \return a reference, remember to release it when done 
13495 */
13496 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag) 
13497 {
13498    struct sip_pvt *sip_pvt_ptr;
13499    struct sip_pvt tmp_dialog = {
13500       .callid = callid,
13501    };
13502 
13503    if (totag)
13504       ast_debug(4, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
13505 
13506    /* Search dialogs and find the match */
13507    
13508    sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find of dialog in dialogs table");
13509    if (sip_pvt_ptr) {
13510       /* Go ahead and lock it (and its owner) before returning */
13511       sip_pvt_lock(sip_pvt_ptr);
13512       if (sip_cfg.pedanticsipchecking) {
13513          unsigned char frommismatch = 0, tomismatch = 0;
13514 
13515          if (ast_strlen_zero(fromtag)) {
13516             sip_pvt_unlock(sip_pvt_ptr);
13517             ast_debug(4, "Matched %s call for callid=%s - no from tag specified, pedantic check fails\n",
13518                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
13519             return NULL;
13520          }
13521 
13522          if (ast_strlen_zero(totag)) {
13523             sip_pvt_unlock(sip_pvt_ptr);
13524             ast_debug(4, "Matched %s call for callid=%s - no to tag specified, pedantic check fails\n",
13525                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
13526             return NULL;
13527          }
13528          /* RFC 3891
13529           * > 3.  User Agent Server Behavior: Receiving a Replaces Header
13530           * > The Replaces header contains information used to match an existing
13531           * > SIP dialog (call-id, to-tag, and from-tag).  Upon receiving an INVITE
13532           * > with a Replaces header, the User Agent (UA) attempts to match this
13533           * > information with a confirmed or early dialog.  The User Agent Server
13534           * > (UAS) matches the to-tag and from-tag parameters as if they were tags
13535           * > present in an incoming request.  In other words, the to-tag parameter
13536           * > is compared to the local tag, and the from-tag parameter is compared
13537           * > to the remote tag.
13538           *
13539           * Thus, the totag is always compared to the local tag, regardless if
13540           * this our call is an incoming or outgoing call.
13541           */
13542          frommismatch = !!strcmp(fromtag, sip_pvt_ptr->theirtag);
13543          tomismatch = !!strcmp(totag, sip_pvt_ptr->tag);
13544 
13545          if (frommismatch || tomismatch) {
13546             sip_pvt_unlock(sip_pvt_ptr);
13547             if (frommismatch) {
13548                ast_debug(4, "Matched %s call for callid=%s - pedantic from tag check fails; their tag is %s our tag is %s\n",
13549                     sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid, 
13550                     fromtag, sip_pvt_ptr->theirtag);
13551             }
13552             if (tomismatch) {
13553                ast_debug(4, "Matched %s call for callid=%s - pedantic to tag check fails; their tag is %s our tag is %s\n",
13554                     sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid, 
13555                     totag, sip_pvt_ptr->tag);
13556             }
13557             return NULL;
13558          }
13559       }
13560       
13561       if (totag)
13562          ast_debug(4, "Matched %s call - their tag is %s Our tag is %s\n",
13563                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING",
13564                  sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
13565 
13566       /* deadlock avoidance... */
13567       while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
13568          sip_pvt_unlock(sip_pvt_ptr);
13569          usleep(1);
13570          sip_pvt_lock(sip_pvt_ptr);
13571       }
13572    }
13573    
13574    return sip_pvt_ptr;
13575 }
13576 
13577 /*! \brief Call transfer support (the REFER method) 
13578  *    Extracts Refer headers into pvt dialog structure 
13579  *
13580  * \note If we get a SIPS uri in the refer-to header, we're required to set up a secure signalling path
13581  * to that extension. As a minimum, this needs to be added to a channel variable, if not a channel
13582  * flag.
13583  */
13584 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
13585 {
13586 
13587    const char *p_referred_by = NULL;
13588    char *h_refer_to = NULL; 
13589    char *h_referred_by = NULL;
13590    char *refer_to;
13591    const char *p_refer_to;
13592    char *referred_by_uri = NULL;
13593    char *ptr;
13594    struct sip_request *req = NULL;
13595    const char *transfer_context = NULL;
13596    struct sip_refer *referdata;
13597 
13598 
13599    req = outgoing_req;
13600    referdata = transferer->refer;
13601 
13602    if (!req)
13603       req = &transferer->initreq;
13604 
13605    p_refer_to = get_header(req, "Refer-To");
13606    if (ast_strlen_zero(p_refer_to)) {
13607       ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
13608       return -2;  /* Syntax error */
13609    }
13610    h_refer_to = ast_strdupa(p_refer_to);
13611    refer_to = get_in_brackets(h_refer_to);
13612    if (sip_cfg.pedanticsipchecking)
13613       ast_uri_decode(refer_to);
13614 
13615    if (!strncasecmp(refer_to, "sip:", 4)) {
13616       refer_to += 4;       /* Skip sip: */
13617    } else if (!strncasecmp(refer_to, "sips:", 5)) {
13618       refer_to += 5;
13619    } else {
13620       ast_log(LOG_WARNING, "Can't transfer to non-sip: URI.  (Refer-to: %s)?\n", refer_to);
13621       return -3;
13622    }
13623 
13624    /* Get referred by header if it exists */
13625    p_referred_by = get_header(req, "Referred-By");
13626 
13627    /* Give useful transfer information to the dialplan */
13628    if (transferer->owner) {
13629       struct ast_channel *peer = ast_bridged_channel(transferer->owner);
13630       if (peer) {
13631          pbx_builtin_setvar_helper(peer, "SIPREFERRINGCONTEXT", transferer->context);
13632          pbx_builtin_setvar_helper(peer, "SIPREFERREDBYHDR", p_referred_by);
13633       }
13634    }
13635 
13636    if (!ast_strlen_zero(p_referred_by)) {
13637       char *lessthan;
13638       h_referred_by = ast_strdupa(p_referred_by);
13639       if (sip_cfg.pedanticsipchecking)
13640          ast_uri_decode(h_referred_by);
13641 
13642       /* Store referrer's caller ID name */
13643       ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
13644       if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
13645          *(lessthan - 1) = '\0'; /* Space */
13646       }
13647 
13648       referred_by_uri = get_in_brackets(h_referred_by);
13649       if (!strncasecmp(referred_by_uri, "sip:", 4)) {
13650          referred_by_uri += 4;      /* Skip sip: */
13651       } else if (!strncasecmp(referred_by_uri, "sips:", 5)) {
13652          referred_by_uri += 5;      /* Skip sips: */
13653       } else {
13654          ast_log(LOG_WARNING, "Huh?  Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
13655          referred_by_uri = NULL;
13656       }
13657    }
13658 
13659    /* Check for arguments in the refer_to header */
13660    if ((ptr = strcasestr(refer_to, "replaces="))) {
13661       char *to = NULL, *from = NULL;
13662       
13663       /* This is an attended transfer */
13664       referdata->attendedtransfer = 1;
13665       ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
13666       ast_uri_decode(referdata->replaces_callid);
13667       if ((ptr = strchr(referdata->replaces_callid, ';')))  /* Find options */ {
13668          *ptr++ = '\0';
13669       }
13670       
13671       if (ptr) {
13672          /* Find the different tags before we destroy the string */
13673          to = strcasestr(ptr, "to-tag=");
13674          from = strcasestr(ptr, "from-tag=");
13675       }
13676       
13677       /* Grab the to header */
13678       if (to) {
13679          ptr = to + 7;
13680          if ((to = strchr(ptr, '&')))
13681             *to = '\0';
13682          if ((to = strchr(ptr, ';')))
13683             *to = '\0';
13684          ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
13685       }
13686       
13687       if (from) {
13688          ptr = from + 9;
13689          if ((to = strchr(ptr, '&')))
13690             *to = '\0';
13691          if ((to = strchr(ptr, ';')))
13692             *to = '\0';
13693          ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
13694       }
13695       
13696       if (!sip_cfg.pedanticsipchecking)
13697          ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
13698       else
13699          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>" );
13700    }
13701    
13702    if ((ptr = strchr(refer_to, '@'))) {   /* Separate domain */
13703       char *urioption = NULL, *domain;
13704       *ptr++ = '\0';
13705 
13706       if ((urioption = strchr(ptr, ';'))) /* Separate urioptions */
13707          *urioption++ = '\0';
13708       
13709       domain = ptr;
13710       if ((ptr = strchr(domain, ':'))) /* Remove :port */
13711          *ptr = '\0';
13712       
13713       /* Save the domain for the dial plan */
13714       ast_copy_string(referdata->refer_to_domain, domain, sizeof(referdata->refer_to_domain));
13715       if (urioption)
13716          ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
13717    }
13718 
13719    if ((ptr = strchr(refer_to, ';')))  /* Remove options */
13720       *ptr = '\0';
13721    ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
13722    
13723    if (referred_by_uri) {
13724       if ((ptr = strchr(referred_by_uri, ';')))    /* Remove options */
13725          *ptr = '\0';
13726       ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
13727    } else {
13728       referdata->referred_by[0] = '\0';
13729    }
13730 
13731    /* Determine transfer context */
13732    if (transferer->owner)  /* Mimic behaviour in res_features.c */
13733       transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
13734 
13735    /* By default, use the context in the channel sending the REFER */
13736    if (ast_strlen_zero(transfer_context)) {
13737       transfer_context = S_OR(transferer->owner->macrocontext,
13738                S_OR(transferer->context, sip_cfg.default_context));
13739    }
13740 
13741    ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
13742    
13743    /* Either an existing extension or the parking extension */
13744    if (referdata->attendedtransfer || ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
13745       if (sip_debug_test_pvt(transferer)) {
13746          ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
13747       }
13748       /* We are ready to transfer to the extension */
13749       return 0;
13750    } 
13751    if (sip_debug_test_pvt(transferer))
13752       ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
13753 
13754    /* Failure, we can't find this extension */
13755    return -1;
13756 }
13757 
13758 
13759 /*! \brief Call transfer support (old way, deprecated by the IETF)
13760  * \note does not account for SIPS: uri requirements, nor check transport
13761  */
13762 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
13763 {
13764    char tmp[256] = "", *c, *a;
13765    struct sip_request *req = oreq ? oreq : &p->initreq;
13766    struct sip_refer *referdata = NULL;
13767    const char *transfer_context = NULL;
13768    
13769    if (!p->refer && !sip_refer_allocate(p))
13770       return -1;
13771 
13772    referdata = p->refer;
13773 
13774    ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
13775    c = get_in_brackets(tmp);
13776 
13777    if (sip_cfg.pedanticsipchecking)
13778       ast_uri_decode(c);
13779 
13780    if (!strncasecmp(c, "sip:", 4)) {
13781       c += 4;
13782    } else if (!strncasecmp(c, "sips:", 5)) {
13783       c += 5;
13784    } else {
13785       ast_log(LOG_WARNING, "Huh?  Not a SIP header in Also: transfer (%s)?\n", c);
13786       return -1;
13787    }
13788 
13789    if ((a = strchr(c, ';')))  /* Remove arguments */
13790       *a = '\0';
13791    
13792    if ((a = strchr(c, '@'))) {   /* Separate Domain */
13793       *a++ = '\0';
13794       ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
13795    }
13796    
13797    if (sip_debug_test_pvt(p))
13798       ast_verbose("Looking for %s in %s\n", c, p->context);
13799 
13800    if (p->owner)  /* Mimic behaviour in res_features.c */
13801       transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
13802 
13803    /* By default, use the context in the channel sending the REFER */
13804    if (ast_strlen_zero(transfer_context)) {
13805       transfer_context = S_OR(p->owner->macrocontext,
13806                S_OR(p->context, sip_cfg.default_context));
13807    }
13808    if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
13809       /* This is a blind transfer */
13810       ast_debug(1, "SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
13811       ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
13812       ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
13813       ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
13814       referdata->refer_call = dialog_unref(referdata->refer_call, "unreffing referdata->refer_call");
13815       /* Set new context */
13816       ast_string_field_set(p, context, transfer_context);
13817       return 0;
13818    } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
13819       return 1;
13820    }
13821 
13822    return -1;
13823 }
13824 
13825 /*! \brief check received= and rport= in a SIP response.
13826  * If we get a response with received= and/or rport= in the Via:
13827  * line, use them as 'p->ourip' (see RFC 3581 for rport,
13828  * and RFC 3261 for received).
13829  * Using these two fields SIP can produce the correct
13830  * address and port in the SIP headers without the need for STUN.
13831  * The address part is also reused for the media sessions.
13832  * Note that ast_sip_ouraddrfor() still rewrites p->ourip
13833  * if you specify externip/seternaddr/stunaddr.
13834  */
13835 static attribute_unused void check_via_response(struct sip_pvt *p, struct sip_request *req)
13836 {
13837    char via[256];
13838    char *cur, *opts;
13839 
13840    ast_copy_string(via, get_header(req, "Via"), sizeof(via));
13841 
13842    /* Work on the leftmost value of the topmost Via header */
13843    opts = strchr(via, ',');
13844    if (opts)
13845       *opts = '\0';
13846 
13847    /* parse all relevant options */
13848    opts = strchr(via, ';');
13849    if (!opts)
13850       return;  /* no options to parse */
13851    *opts++ = '\0';
13852    while ( (cur = strsep(&opts, ";")) ) {
13853       if (!strncmp(cur, "rport=", 6)) {
13854          int port = strtol(cur+6, NULL, 10);
13855          /* XXX add error checking */
13856          p->ourip.sin_port = ntohs(port);
13857       } else if (!strncmp(cur, "received=", 9)) {
13858          if (ast_parse_arg(cur+9, PARSE_INADDR, &p->ourip))
13859             ;  /* XXX add error checking */
13860       }
13861    }
13862 }
13863 
13864 /*! \brief check Via: header for hostname, port and rport request/answer */
13865 static void check_via(struct sip_pvt *p, struct sip_request *req)
13866 {
13867    char via[512];
13868    char *c, *pt, *maddr;
13869    struct hostent *hp;
13870    struct ast_hostent ahp;
13871 
13872    ast_copy_string(via, get_header(req, "Via"), sizeof(via));
13873 
13874    /* Work on the leftmost value of the topmost Via header */
13875    c = strchr(via, ',');
13876    if (c)
13877       *c = '\0';
13878 
13879    /* Check for rport */
13880    c = strstr(via, ";rport");
13881    if (c && (c[6] != '=')) /* rport query, not answer */
13882       ast_set_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT);
13883 
13884    /* Check for maddr */
13885    maddr = strstr(via, "maddr=");
13886    if (maddr) {
13887       maddr += 6;
13888       c = maddr + strspn(maddr, "0123456789.");
13889       *c = '\0';
13890    }
13891 
13892    c = strchr(via, ';');
13893    if (c)
13894       *c = '\0';
13895 
13896    c = strchr(via, ' ');
13897    if (c) {
13898       *c = '\0';
13899       c = ast_skip_blanks(c+1);
13900       if (strcasecmp(via, "SIP/2.0/UDP") && strcasecmp(via, "SIP/2.0/TCP") && strcasecmp(via, "SIP/2.0/TLS")) {
13901          ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
13902          return;
13903       }
13904       pt = strchr(c, ':');
13905       if (pt)
13906          *pt++ = '\0';  /* remember port pointer */
13907       /* Use maddr if found */
13908       if (maddr)
13909          c = maddr;
13910       hp = ast_gethostbyname(c, &ahp);
13911       if (!hp) {
13912          ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
13913          return;
13914       }
13915       memset(&p->sa, 0, sizeof(p->sa));
13916       p->sa.sin_family = AF_INET;
13917       memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
13918       p->sa.sin_port = htons(port_str2int(pt, STANDARD_SIP_PORT));
13919 
13920       if (sip_debug_test_pvt(p)) {
13921          const struct sockaddr_in *dst = sip_real_dst(p);
13922          ast_verbose("Sending to %s : %d (%s)\n", ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), sip_nat_mode(p));
13923       }
13924    }
13925 }
13926 
13927 /*! \brief  Get caller id name from SIP headers */
13928 static char *get_calleridname(const char *input, char *output, size_t outputsize)
13929 {
13930    const char *end = strchr(input, '<');  /* first_bracket */
13931    const char *tmp = strchr(input, '"');  /* first quote */
13932    int bytes = 0;
13933    int maxbytes = outputsize - 1;
13934 
13935    if (!end || end == input)  /* we require a part in brackets */
13936       return NULL;
13937 
13938    end--; /* move just before "<" */
13939 
13940    if (tmp && tmp <= end) {
13941       /* The quote (tmp) precedes the bracket (end+1).
13942        * Find the matching quote and return the content.
13943        */
13944       end = strchr(tmp+1, '"');
13945       if (!end)
13946          return NULL;
13947       bytes = (int) (end - tmp);
13948       /* protect the output buffer */
13949       if (bytes > maxbytes)
13950          bytes = maxbytes;
13951       ast_copy_string(output, tmp + 1, bytes);
13952    } else {
13953       /* No quoted string, or it is inside brackets. */
13954       /* clear the empty characters in the begining*/
13955       input = ast_skip_blanks(input);
13956       /* clear the empty characters in the end */
13957       while(*end && *end < 33 && end > input)
13958          end--;
13959       if (end >= input) {
13960          bytes = (int) (end - input) + 2;
13961          /* protect the output buffer */
13962          if (bytes > maxbytes)
13963             bytes = maxbytes;
13964          ast_copy_string(output, input, bytes);
13965       } else
13966          return NULL;
13967    }
13968    return output;
13969 }
13970 
13971 /*! \brief  Get caller id number from Remote-Party-ID header field 
13972  * Returns true if number should be restricted (privacy setting found)
13973  * output is set to NULL if no number found
13974  */
13975 static int get_rpid_num(const char *input, char *output, int maxlen)
13976 {
13977    char *start;
13978    char *end;
13979 
13980    start = strchr(input, ':');
13981    if (!start) {
13982       output[0] = '\0';
13983       return 0;
13984    }
13985    start++;
13986 
13987    /* we found "number" */
13988    ast_copy_string(output, start, maxlen);
13989    output[maxlen-1] = '\0';
13990 
13991    end = strchr(output, '@');
13992    if (end)
13993       *end = '\0';
13994    else
13995       output[0] = '\0';
13996    if (strstr(input, "privacy=full") || strstr(input, "privacy=uri"))
13997       return AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
13998 
13999    return 0;
14000 }
14001 
14002 
14003 /*! \brief helper function for check_{user|peer}_ok() */
14004 static void replace_cid(struct sip_pvt *p, const char *rpid_num, const char *calleridname)
14005 {
14006    /* replace callerid if rpid found, and not restricted */
14007    if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
14008       char *tmp = ast_strdupa(rpid_num); /* XXX the copy can be done later */
14009       if (!ast_strlen_zero(calleridname))
14010          ast_string_field_set(p, cid_name, calleridname);
14011       if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
14012          ast_shrink_phone_number(tmp);
14013       ast_string_field_set(p, cid_num, tmp);
14014    }
14015 }
14016 
14017 /*! \brief Validate device authentication */
14018 static enum check_auth_result check_peer_ok(struct sip_pvt *p, char *of,
14019    struct sip_request *req, int sipmethod, struct sockaddr_in *sin,
14020    struct sip_peer **authpeer,
14021    enum xmittype reliable,
14022    char *rpid_num, char *calleridname, char *uri2)
14023 {
14024    enum check_auth_result res;
14025    int debug=sip_debug_test_addr(sin);
14026    struct sip_peer *peer;
14027 
14028    if (sipmethod == SIP_SUBSCRIBE) {
14029       /* For subscribes, match on device name only; for other methods,
14030       * match on IP address-port of the incoming request.
14031       */
14032       peer = find_peer(of, NULL, TRUE, FINDALLDEVICES, FALSE, 0);
14033    } else {
14034       /* First find devices based on username (avoid all type=peer's) */
14035       peer = find_peer(of, NULL, TRUE, FINDUSERS, FALSE, 0);
14036 
14037       /* Then find devices based on IP */
14038       if (!peer) {
14039          peer = find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
14040       }
14041    }
14042 
14043    if (!peer) {
14044       if (debug)
14045          ast_verbose("No matching peer for '%s' from '%s:%d'\n",
14046             of, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
14047       return AUTH_DONT_KNOW;
14048    }
14049    if (!ast_apply_ha(peer->ha, sin)) {
14050       ast_debug(2, "Found peer '%s' for '%s', but fails host access\n", peer->name, of);
14051       unref_peer(peer, "unref_peer: check_peer_ok: from find_peer call, early return of AUTH_ACL_FAILED");
14052       return AUTH_ACL_FAILED;
14053    }
14054    if (debug)
14055       ast_verbose("Found peer '%s' for '%s' from %s:%d\n",
14056          peer->name, of, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
14057 
14058    /* XXX what about p->prefs = peer->prefs; ? */
14059    /* Set Frame packetization */
14060    if (p->rtp) {
14061       ast_rtp_codec_setpref(p->rtp, &peer->prefs);
14062       p->autoframing = peer->autoframing;
14063    }
14064 
14065    /* Take the peer */
14066    ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
14067    ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
14068 
14069    if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && p->udptl) {
14070       p->t38_maxdatagram = peer->t38_maxdatagram;
14071       set_t38_capabilities(p);
14072    }
14073 
14074    /* Copy SIP extensions profile to peer */
14075    /* XXX is this correct before a successful auth ? */
14076    if (p->sipoptions)
14077       peer->sipoptions = p->sipoptions;
14078 
14079    replace_cid(p, rpid_num, calleridname);
14080    do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE));
14081 
14082    ast_string_field_set(p, peersecret, peer->secret);
14083    ast_string_field_set(p, peermd5secret, peer->md5secret);
14084    ast_string_field_set(p, subscribecontext, peer->subscribecontext);
14085    ast_string_field_set(p, mohinterpret, peer->mohinterpret);
14086    ast_string_field_set(p, mohsuggest, peer->mohsuggest);
14087    ast_string_field_set(p, parkinglot, peer->parkinglot);
14088    if (peer->callingpres)  /* Peer calling pres setting will override RPID */
14089       p->callingpres = peer->callingpres;
14090    if (peer->maxms && peer->lastms)
14091       p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
14092    else
14093       p->timer_t1 = peer->timer_t1;
14094  
14095    /* Set timer B to control transaction timeouts */
14096    if (peer->timer_b)
14097       p->timer_b = peer->timer_b;
14098    else
14099       p->timer_b = 64 * p->timer_t1;
14100  
14101    if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
14102       /* Pretend there is no required authentication */
14103       ast_string_field_set(p, peersecret, NULL);
14104       ast_string_field_set(p, peermd5secret, NULL);
14105    }
14106    if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, req->ignore))) {
14107       ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
14108       ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
14109       /* If we have a call limit, set flag */
14110       if (peer->call_limit)
14111          ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
14112       ast_string_field_set(p, peername, peer->name);
14113       ast_string_field_set(p, authname, peer->name);
14114 
14115       if (sipmethod == SIP_INVITE) {
14116          /* copy channel vars */
14117          p->chanvars = copy_vars(peer->chanvars);
14118       }
14119 
14120       if (authpeer) {
14121          ao2_t_ref(peer, 1, "copy pointer into (*authpeer)");
14122          (*authpeer) = peer;  /* Add a ref to the object here, to keep it in memory a bit longer if it is realtime */
14123       }
14124 
14125       if (!ast_strlen_zero(peer->username)) {
14126          ast_string_field_set(p, username, peer->username);
14127          /* Use the default username for authentication on outbound calls */
14128          /* XXX this takes the name from the caller... can we override ? */
14129          ast_string_field_set(p, authname, peer->username);
14130       }
14131       if (!ast_strlen_zero(peer->cid_num)) {
14132          char *tmp = ast_strdupa(peer->cid_num);
14133          if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
14134             ast_shrink_phone_number(tmp);
14135          ast_string_field_set(p, cid_num, tmp);
14136       }
14137       if (!ast_strlen_zero(peer->cid_name)) 
14138          ast_string_field_set(p, cid_name, peer->cid_name);
14139       ast_string_field_set(p, fullcontact, peer->fullcontact);
14140       if (!ast_strlen_zero(peer->context))
14141          ast_string_field_set(p, context, peer->context);
14142       ast_string_field_set(p, peersecret, peer->secret);
14143       ast_string_field_set(p, peermd5secret, peer->md5secret);
14144       ast_string_field_set(p, language, peer->language);
14145       ast_string_field_set(p, accountcode, peer->accountcode);
14146       p->amaflags = peer->amaflags;
14147       p->callgroup = peer->callgroup;
14148       p->pickupgroup = peer->pickupgroup;
14149       p->capability = peer->capability;
14150       p->prefs = peer->prefs;
14151       p->jointcapability = peer->capability;
14152       if (p->peercapability)
14153          p->jointcapability &= p->peercapability;
14154       p->maxcallbitrate = peer->maxcallbitrate;
14155       if (!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) &&
14156             (!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
14157                !(p->capability & AST_FORMAT_VIDEO_MASK)) &&
14158             p->vrtp) {
14159          ast_rtp_destroy(p->vrtp);
14160          p->vrtp = NULL;
14161       }
14162       if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) || !(p->capability & AST_FORMAT_TEXT_MASK)) && p->trtp) {
14163          ast_rtp_destroy(p->trtp);
14164          p->trtp = NULL;
14165       }
14166       if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
14167           (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
14168          p->noncodeccapability |= AST_RTP_DTMF;
14169       else
14170          p->noncodeccapability &= ~AST_RTP_DTMF;
14171       p->jointnoncodeccapability = p->noncodeccapability;
14172    }
14173    unref_peer(peer, "check_peer_ok: unref_peer: tossing temp ptr to peer from find_peer");
14174    return res;
14175 }
14176 
14177 
14178 /*! \brief  Check if matching user or peer is defined 
14179    Match user on From: user name and peer on IP/port
14180    This is used on first invite (not re-invites) and subscribe requests 
14181     \return 0 on success, non-zero on failure
14182 */
14183 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
14184                      int sipmethod, char *uri, enum xmittype reliable,
14185                      struct sockaddr_in *sin, struct sip_peer **authpeer)
14186 {
14187    char from[256];
14188    char *dummy;   /* dummy return value for parse_uri */
14189    char *domain;  /* dummy return value for parse_uri */
14190    char *of;
14191    char rpid_num[50];
14192    const char *rpid;
14193    enum check_auth_result res;
14194    char calleridname[50];
14195    char *uri2 = ast_strdupa(uri);
14196 
14197    terminate_uri(uri2); /* trim extra stuff */
14198 
14199    ast_copy_string(from, get_header(req, "From"), sizeof(from));
14200    if (sip_cfg.pedanticsipchecking)
14201       ast_uri_decode(from);
14202    /* XXX here tries to map the username for invite things */
14203    memset(calleridname, 0, sizeof(calleridname));
14204    get_calleridname(from, calleridname, sizeof(calleridname));
14205    if (calleridname[0])
14206       ast_string_field_set(p, cid_name, calleridname);
14207 
14208    rpid = get_header(req, "Remote-Party-ID");
14209    memset(rpid_num, 0, sizeof(rpid_num));
14210    if (!ast_strlen_zero(rpid)) 
14211       p->callingpres = get_rpid_num(rpid, rpid_num, sizeof(rpid_num));
14212 
14213    of = get_in_brackets(from);
14214    if (ast_strlen_zero(p->exten)) {
14215       char *t = uri2;
14216       if (!strncasecmp(t, "sip:", 4))
14217          t+= 4;
14218       else if (!strncasecmp(t, "sips:", 5))
14219          t += 5;
14220       ast_string_field_set(p, exten, t);
14221       t = strchr(p->exten, '@');
14222       if (t)
14223          *t = '\0';
14224       if (ast_strlen_zero(p->our_contact))
14225          build_contact(p);
14226    }
14227    /* save the URI part of the From header */
14228    ast_string_field_set(p, from, of);
14229 
14230    /* ignore all fields but name */
14231    if (parse_uri(of, "sip:,sips:", &of, &dummy, &domain, &dummy, &dummy, NULL)) {
14232       ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
14233    }
14234 
14235    if (ast_strlen_zero(of)) {
14236       /* XXX note: the original code considered a missing @host
14237        * as a username-only URI. The SIP RFC (19.1.1) says that
14238        * this is wrong, and it should be considered as a domain-only URI.
14239        * For backward compatibility, we keep this block, but it is
14240        * really a mistake and should go away.
14241        */
14242       of = domain;
14243    } else {
14244       char *tmp = ast_strdupa(of);
14245       /* We need to be able to handle auth-headers looking like
14246          <sip:8164444422;phone-context=+1@1.2.3.4:5060;user=phone;tag=SDadkoa01-gK0c3bdb43>
14247       */
14248       tmp = strsep(&tmp, ";");
14249       if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
14250          ast_shrink_phone_number(tmp);
14251       ast_string_field_set(p, cid_num, tmp);
14252    }
14253 
14254    if (global_match_auth_username) {
14255       /*
14256        * XXX This is experimental code to grab the search key from the
14257        * Auth header's username instead of the 'From' name, if available.
14258        * Do not enable this block unless you understand the side effects (if any!)
14259        * Note, the search for "username" should be done in a more robust way.
14260        * Note2, at the moment we check both fields, though maybe we should
14261        * pick one or another depending on the request ? XXX
14262        */
14263       const char *hdr = get_header(req, "Authorization");
14264       if (ast_strlen_zero(hdr))
14265          hdr = get_header(req, "Proxy-Authorization");
14266 
14267       if ( !ast_strlen_zero(hdr) && (hdr = strstr(hdr, "username=\"")) ) {
14268          ast_copy_string(from, hdr + strlen("username=\""), sizeof(from));
14269          of = from;
14270          of = strsep(&of, "\"");
14271       }
14272    }
14273 
14274    res = check_peer_ok(p, of, req, sipmethod, sin,
14275          authpeer, reliable, rpid_num, calleridname, uri2);
14276    if (res != AUTH_DONT_KNOW)
14277       return res;
14278 
14279    /* Finally, apply the guest policy */
14280    if (sip_cfg.allowguest) {
14281       replace_cid(p, rpid_num, calleridname);
14282       res = AUTH_SUCCESSFUL;
14283    } else if (sip_cfg.alwaysauthreject)
14284       res = AUTH_FAKE_AUTH; /* reject with fake authorization request */
14285    else
14286       res = AUTH_SECRET_FAILED; /* we don't want any guests, authentication will fail */
14287 
14288 
14289    if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT)) {
14290       ast_set_flag(&p->flags[0], SIP_NAT_ROUTE);
14291    }
14292 
14293    return res;
14294 }
14295 
14296 /*! \brief  Find user 
14297    If we get a match, this will add a reference pointer to the user object in ASTOBJ, that needs to be unreferenced
14298 */
14299 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin)
14300 {
14301    return check_user_full(p, req, sipmethod, uri, reliable, sin, NULL);
14302 }
14303 
14304 /*! \brief  Get text out of a SIP MESSAGE packet */
14305 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline)
14306 {
14307    int x;
14308    int y;
14309 
14310    buf[0] = '\0';
14311    /*XXX isn't strlen(buf) going to always be 0? */
14312    y = len - strlen(buf) - 5;
14313    if (y < 0)
14314       y = 0;
14315    for (x = 0; x < req->lines; x++) {
14316       char *line = REQ_OFFSET_TO_STR(req, line[x]);
14317       strncat(buf, line, y); /* safe */
14318       y -= strlen(line) + 1;
14319       if (y < 0)
14320          y = 0;
14321       if (y != 0 && addnewline)
14322          strcat(buf, "\n"); /* safe */
14323    }
14324    return 0;
14325 }
14326 
14327 
14328 /*! \brief  Receive SIP MESSAGE method messages
14329 \note We only handle messages within current calls currently 
14330    Reference: RFC 3428 */
14331 static void receive_message(struct sip_pvt *p, struct sip_request *req)
14332 {
14333    char buf[1400];   
14334    struct ast_frame f;
14335    const char *content_type = get_header(req, "Content-Type");
14336 
14337    if (strncmp(content_type, "text/plain", strlen("text/plain"))) { /* No text/plain attachment */
14338       transmit_response(p, "415 Unsupported Media Type", req); /* Good enough, or? */
14339       if (!p->owner)
14340          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14341       return;
14342    }
14343 
14344    if (get_msg_text(buf, sizeof(buf), req, FALSE)) {
14345       ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
14346       transmit_response(p, "202 Accepted", req);
14347       if (!p->owner)
14348          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14349       return;
14350    }
14351 
14352    if (p->owner) {
14353       if (sip_debug_test_pvt(p))
14354          ast_verbose("SIP Text message received: '%s'\n", buf);
14355       memset(&f, 0, sizeof(f));
14356       f.frametype = AST_FRAME_TEXT;
14357       f.subclass = 0;
14358       f.offset = 0;
14359       f.data.ptr = buf;
14360       f.datalen = strlen(buf);
14361       ast_queue_frame(p->owner, &f);
14362       transmit_response(p, "202 Accepted", req); /* We respond 202 accepted, since we relay the message */
14363       return;
14364    }
14365 
14366    /* Message outside of a call, we do not support that */
14367    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);
14368    transmit_response(p, "405 Method Not Allowed", req);
14369    sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14370    return;
14371 }
14372 
14373 /*! \brief  CLI Command to show calls within limits set by call_limit */
14374 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14375 {
14376 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
14377 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
14378    char ilimits[40];
14379    char iused[40];
14380    int showall = FALSE;
14381    struct ao2_iterator i;
14382    struct sip_peer *peer;
14383    
14384    switch (cmd) {
14385    case CLI_INIT:
14386       e->command = "sip show inuse";
14387       e->usage =
14388          "Usage: sip show inuse [all]\n"
14389          "       List all SIP devices usage counters and limits.\n"
14390          "       Add option \"all\" to show all devices, not only those with a limit.\n";
14391       return NULL;
14392    case CLI_GENERATE:
14393       return NULL;
14394    }
14395 
14396    if (a->argc < 3) 
14397       return CLI_SHOWUSAGE;
14398 
14399    if (a->argc == 4 && !strcmp(a->argv[3], "all")) 
14400       showall = TRUE;
14401    
14402    ast_cli(a->fd, FORMAT, "* Peer name", "In use", "Limit");
14403 
14404    i = ao2_iterator_init(peers, 0);
14405    while ((peer = ao2_t_iterator_next(&i, "iterate thru peer table"))) {
14406       ao2_lock(peer);
14407       if (peer->call_limit)
14408          snprintf(ilimits, sizeof(ilimits), "%d", peer->call_limit);
14409       else 
14410          ast_copy_string(ilimits, "N/A", sizeof(ilimits));
14411       snprintf(iused, sizeof(iused), "%d/%d/%d", peer->inUse, peer->inRinging, peer->onHold);
14412       if (showall || peer->call_limit)
14413          ast_cli(a->fd, FORMAT2, peer->name, iused, ilimits);
14414       ao2_unlock(peer);
14415       unref_peer(peer, "toss iterator pointer");
14416    }
14417    ao2_iterator_destroy(&i);
14418 
14419    return CLI_SUCCESS;
14420 #undef FORMAT
14421 #undef FORMAT2
14422 }
14423 
14424 
14425 /*! \brief Convert transfer mode to text string */
14426 static char *transfermode2str(enum transfermodes mode)
14427 {
14428    if (mode == TRANSFER_OPENFORALL)
14429       return "open";
14430    else if (mode == TRANSFER_CLOSED)
14431       return "closed";
14432    return "strict";
14433 }
14434 
14435 static struct _map_x_s natmodes[] = {
14436    { SIP_NAT_NEVER,        "No"},
14437    { SIP_NAT_ROUTE,        "Route"},
14438    { SIP_NAT_ALWAYS,       "Always"},
14439    { SIP_NAT_RFC3581,      "RFC3581"},
14440    { -1,                   NULL}, /* terminator */
14441 };
14442 
14443 /*! \brief  Convert NAT setting to text string */
14444 static const char *nat2str(int nat)
14445 {
14446    return map_x_s(natmodes, nat, "Unknown");
14447 }
14448 
14449 #ifdef NOTUSED
14450 /* OEJ: This is not used, but may be useful in the future, so I don't want to 
14451    delete it. Keeping it enabled generates compiler warnings.
14452  */
14453 
14454 static struct _map_x_s natcfgmodes[] = {
14455    { SIP_NAT_NEVER,        "never"},
14456    { SIP_NAT_ROUTE,        "route"},
14457    { SIP_NAT_ALWAYS,       "yes"},
14458    { SIP_NAT_RFC3581,      "no"},
14459    { -1,                   NULL}, /* terminator */
14460 };
14461 
14462 /*! \brief  Convert NAT setting to text string appropriate for config files */
14463 static const char *nat2strconfig(int nat)
14464 {
14465    return map_x_s(natcfgmodes, nat, "Unknown");
14466 }
14467 #endif
14468 
14469 /*! \brief  Report Peer status in character string
14470  *  \return 0 if peer is unreachable, 1 if peer is online, -1 if unmonitored
14471  */
14472 
14473 
14474 /* Session-Timer Modes */
14475 static struct _map_x_s stmodes[] = {
14476         { SESSION_TIMER_MODE_ACCEPT,    "Accept"},
14477         { SESSION_TIMER_MODE_ORIGINATE, "Originate"},
14478         { SESSION_TIMER_MODE_REFUSE,    "Refuse"},
14479         { -1,                           NULL},
14480 };
14481 
14482 static const char *stmode2str(enum st_mode m)
14483 {
14484    return map_x_s(stmodes, m, "Unknown");
14485 }
14486 
14487 static enum st_mode str2stmode(const char *s)
14488 {
14489    return map_s_x(stmodes, s, -1);
14490 }
14491 
14492 /* Session-Timer Refreshers */
14493 static struct _map_x_s strefreshers[] = {
14494         { SESSION_TIMER_REFRESHER_AUTO,     "auto"},
14495         { SESSION_TIMER_REFRESHER_UAC,      "uac"},
14496         { SESSION_TIMER_REFRESHER_UAS,      "uas"},
14497         { -1,                               NULL},
14498 };
14499 
14500 static const char *strefresher2str(enum st_refresher r)
14501 {
14502    return map_x_s(strefreshers, r, "Unknown");
14503 }
14504 
14505 static enum st_refresher str2strefresher(const char *s)
14506 {
14507    return map_s_x(strefreshers, s, -1);
14508 }
14509 
14510 
14511 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
14512 {
14513    int res = 0;
14514    if (peer->maxms) {
14515       if (peer->lastms < 0) {
14516          ast_copy_string(status, "UNREACHABLE", statuslen);
14517       } else if (peer->lastms > peer->maxms) {
14518          snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
14519          res = 1;
14520       } else if (peer->lastms) {
14521          snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
14522          res = 1;
14523       } else {
14524          ast_copy_string(status, "UNKNOWN", statuslen);
14525       }
14526    } else { 
14527       ast_copy_string(status, "Unmonitored", statuslen);
14528       /* Checking if port is 0 */
14529       res = -1;
14530    }
14531    return res;
14532 }
14533 
14534 /*! \brief return Yes or No depending on the argument.
14535  * This is used in many places in CLI command, having a function to generate
14536  * this helps maintaining a consistent output (and possibly emitting the
14537  * output in other languages, at some point).
14538  */
14539 static const char *cli_yesno(int x)
14540 {
14541    return x ? "Yes" : "No";
14542 }
14543 
14544 /*! \brief  Show active TCP connections */
14545 static char *sip_show_tcp(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14546 {
14547    struct sip_threadinfo *th;
14548    struct ao2_iterator i;
14549 
14550 #define FORMAT2 "%-30.30s %3.6s %9.9s %6.6s\n"
14551 #define FORMAT  "%-30.30s %-6d %-9.9s %-6.6s\n"
14552 
14553    switch (cmd) {
14554    case CLI_INIT:
14555       e->command = "sip show tcp";
14556       e->usage =
14557          "Usage: sip show tcp\n"
14558          "       Lists all active TCP/TLS sessions.\n";
14559       return NULL;
14560    case CLI_GENERATE:
14561       return NULL;
14562    }
14563 
14564    if (a->argc != 3)
14565       return CLI_SHOWUSAGE;
14566 
14567    ast_cli(a->fd, FORMAT2, "Host", "Port", "Transport", "Type");
14568    i = ao2_iterator_init(threadt, 0);
14569    while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
14570       ast_cli(a->fd, FORMAT, ast_inet_ntoa(th->tcptls_session->remote_address.sin_addr), 
14571          ntohs(th->tcptls_session->remote_address.sin_port), 
14572          get_transport(th->type), 
14573          (th->tcptls_session->client ? "Client" : "Server"));
14574       ao2_t_ref(th, -1, "decrement ref from iterator");
14575    }
14576    ao2_iterator_destroy(&i);
14577    return CLI_SUCCESS;
14578 #undef FORMAT
14579 #undef FORMAT2
14580 }
14581 
14582 /*! \brief  CLI Command 'SIP Show Users' */
14583 static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14584 {
14585    regex_t regexbuf;
14586    int havepattern = FALSE;
14587    struct ao2_iterator user_iter;
14588    struct sip_peer *user;
14589 
14590 #define FORMAT  "%-25.25s  %-15.15s  %-15.15s  %-15.15s  %-5.5s%-10.10s\n"
14591 
14592    switch (cmd) {
14593    case CLI_INIT:
14594       e->command = "sip show users";
14595       e->usage =
14596          "Usage: sip show users [like <pattern>]\n"
14597          "       Lists all known SIP users.\n"
14598          "       Optional regular expression pattern is used to filter the user list.\n";
14599       return NULL;
14600    case CLI_GENERATE:
14601       return NULL;
14602    }
14603 
14604    switch (a->argc) {
14605    case 5:
14606       if (!strcasecmp(a->argv[3], "like")) {
14607          if (regcomp(&regexbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
14608             return CLI_SHOWUSAGE;
14609          havepattern = TRUE;
14610       } else
14611          return CLI_SHOWUSAGE;
14612    case 3:
14613       break;
14614    default:
14615       return CLI_SHOWUSAGE;
14616    }
14617 
14618    ast_cli(a->fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "NAT");
14619 
14620    user_iter = ao2_iterator_init(peers, 0);
14621    while ((user = ao2_iterator_next(&user_iter))) {
14622       ao2_lock(user);
14623       if (!(user->type & SIP_TYPE_USER)) {
14624          ao2_unlock(user);
14625          unref_peer(user, "sip show users");
14626          continue;
14627       }
14628 
14629       if (havepattern && regexec(&regexbuf, user->name, 0, NULL, 0)) {
14630          ao2_unlock(user);
14631          unref_peer(user, "sip show users");
14632          continue;
14633       }
14634 
14635       ast_cli(a->fd, FORMAT, user->name, 
14636          user->secret, 
14637          user->accountcode,
14638          user->context,
14639          cli_yesno(user->ha != NULL),
14640          nat2str(ast_test_flag(&user->flags[0], SIP_NAT)));
14641       ao2_unlock(user);
14642       unref_peer(user, "sip show users");
14643    }
14644    ao2_iterator_destroy(&user_iter);
14645 
14646    if (havepattern)
14647       regfree(&regexbuf);
14648 
14649    return CLI_SUCCESS;
14650 #undef FORMAT
14651 }
14652 
14653 /*! \brief Manager Action SIPShowRegistry description */
14654 static char mandescr_show_registry[] =
14655 "Description: Lists all registration requests and status\n"
14656 "Registrations will follow as separate events. followed by a final event called\n"
14657 "RegistrationsComplete.\n"
14658 "Variables: \n"
14659 "  ActionID: <id>       Action ID for this transaction. Will be returned.\n";
14660 
14661 /*! \brief Show SIP registrations in the manager API */
14662 static int manager_show_registry(struct mansession *s, const struct message *m)
14663 {
14664    const char *id = astman_get_header(m, "ActionID");
14665    char idtext[256] = "";
14666    int total = 0;
14667 
14668    if (!ast_strlen_zero(id))
14669       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
14670 
14671    astman_send_listack(s, m, "Registrations will follow", "start");
14672 
14673    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
14674       ASTOBJ_RDLOCK(iterator);
14675       astman_append(s,
14676          "Event: RegistryEntry\r\n"
14677          "%s"
14678          "Host: %s\r\n"
14679          "Port: %d\r\n"
14680          "Username: %s\r\n"
14681          "Refresh: %d\r\n"
14682          "State: %s\r\n"
14683          "RegistrationTime: %ld\r\n"
14684          "\r\n", idtext, iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT,
14685                  iterator->username, iterator->refresh, regstate2str(iterator->regstate), (long) iterator->regtime.tv_sec);
14686       ASTOBJ_UNLOCK(iterator);
14687       total++;
14688    } while(0));
14689 
14690    astman_append(s,
14691       "Event: RegistrationsComplete\r\n"
14692       "EventList: Complete\r\n"
14693       "ListItems: %d\r\n"
14694       "%s"
14695       "\r\n", total, idtext);
14696    
14697    return 0;
14698 }
14699 
14700 static char mandescr_show_peers[] = 
14701 "Description: Lists SIP peers in text format with details on current status.\n"
14702 "Peerlist will follow as separate events, followed by a final event called\n"
14703 "PeerlistComplete.\n"
14704 "Variables: \n"
14705 "  ActionID: <id> Action ID for this transaction. Will be returned.\n";
14706 
14707 /*! \brief  Show SIP peers in the manager API */
14708 /*    Inspired from chan_iax2 */
14709 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
14710 {
14711    const char *id = astman_get_header(m, "ActionID");
14712    const char *a[] = {"sip", "show", "peers"};
14713    char idtext[256] = "";
14714    int total = 0;
14715 
14716    if (!ast_strlen_zero(id))
14717       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
14718 
14719    astman_send_listack(s, m, "Peer status list will follow", "start");
14720    /* List the peers in separate manager events */
14721    _sip_show_peers(-1, &total, s, m, 3, a);
14722    /* Send final confirmation */
14723    astman_append(s,
14724    "Event: PeerlistComplete\r\n"
14725    "EventList: Complete\r\n"
14726    "ListItems: %d\r\n"
14727    "%s"
14728    "\r\n", total, idtext);
14729    return 0;
14730 }
14731 
14732 /*! \brief  CLI Show Peers command */
14733 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14734 {
14735    switch (cmd) {
14736    case CLI_INIT:
14737       e->command = "sip show peers";
14738       e->usage =
14739          "Usage: sip show peers [like <pattern>]\n"
14740          "       Lists all known SIP peers.\n"
14741          "       Optional regular expression pattern is used to filter the peer list.\n";
14742       return NULL;
14743    case CLI_GENERATE:
14744       return NULL;
14745    }
14746 
14747    return _sip_show_peers(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
14748 }
14749 
14750 int peercomparefunc(const void *a, const void *b);
14751 
14752 int peercomparefunc(const void *a, const void *b)
14753 {
14754    struct sip_peer **ap = (struct sip_peer **)a;
14755    struct sip_peer **bp = (struct sip_peer **)b;
14756    return strcmp((*ap)->name, (*bp)->name);
14757 }
14758 
14759 
14760 /*! \brief Execute sip show peers command */
14761 static char *_sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
14762 {
14763    regex_t regexbuf;
14764    int havepattern = FALSE;
14765    struct sip_peer *peer;
14766    struct ao2_iterator i;
14767    
14768 /* the last argument is left-aligned, so we don't need a size anyways */
14769 #define FORMAT2 "%-25.25s  %-15.15s %-3.3s %-3.3s %-3.3s %-8s %-10s %s\n"
14770 #define FORMAT  "%-25.25s  %-15.15s %-3.3s %-3.3s %-3.3s %-8d %-10s %s\n"
14771 
14772    char name[256];
14773    int total_peers = 0;
14774    int peers_mon_online = 0;
14775    int peers_mon_offline = 0;
14776    int peers_unmon_offline = 0;
14777    int peers_unmon_online = 0;
14778    const char *id;
14779    char idtext[256] = "";
14780    int realtimepeers;
14781    int objcount = ao2_container_count(peers);
14782    struct sip_peer **peerarray;
14783    int k;
14784    
14785    
14786    realtimepeers = ast_check_realtime("sippeers");
14787    peerarray = ast_calloc(sizeof(struct sip_peer *), objcount);
14788 
14789    if (s) { /* Manager - get ActionID */
14790       id = astman_get_header(m, "ActionID");
14791       if (!ast_strlen_zero(id))
14792          snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
14793    }
14794 
14795    switch (argc) {
14796    case 5:
14797       if (!strcasecmp(argv[3], "like")) {
14798          if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
14799             return CLI_SHOWUSAGE;
14800          havepattern = TRUE;
14801       } else
14802          return CLI_SHOWUSAGE;
14803    case 3:
14804       break;
14805    default:
14806       return CLI_SHOWUSAGE;
14807    }
14808 
14809    if (!s) /* Normal list */
14810       ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Nat", "ACL", "Port", "Status", (realtimepeers ? "Realtime" : ""));
14811    
14812 
14813    i = ao2_iterator_init(peers, 0);
14814    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {  
14815       ao2_lock(peer);
14816 
14817       if (!(peer->type & SIP_TYPE_PEER)) {
14818          ao2_unlock(peer);
14819          unref_peer(peer, "unref peer because it's actually a user");
14820          continue;
14821       }
14822 
14823       if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0)) {
14824          objcount--;
14825          ao2_unlock(peer);
14826          unref_peer(peer, "toss iterator peer ptr before continue");
14827          continue;
14828       }
14829 
14830       peerarray[total_peers++] = peer;
14831       ao2_unlock(peer);
14832    }
14833    ao2_iterator_destroy(&i);
14834    
14835    qsort(peerarray, total_peers, sizeof(struct sip_peer *), peercomparefunc);
14836 
14837    for(k=0; k < total_peers; k++) {
14838       char status[20] = "";
14839       char srch[2000];
14840       char pstatus;
14841       peer = peerarray[k];
14842       
14843       ao2_lock(peer);
14844       if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0)) {
14845          ao2_unlock(peer);
14846          unref_peer(peer, "toss iterator peer ptr before continue");
14847          continue;
14848       }
14849 
14850       if (!ast_strlen_zero(peer->username) && !s)
14851          snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
14852       else
14853          ast_copy_string(name, peer->name, sizeof(name));
14854       
14855       pstatus = peer_status(peer, status, sizeof(status));
14856       if (pstatus == 1)
14857          peers_mon_online++;
14858       else if (pstatus == 0)
14859          peers_mon_offline++;
14860       else {
14861          if (peer->addr.sin_port == 0)
14862             peers_unmon_offline++;
14863          else
14864             peers_unmon_online++;
14865       }
14866 
14867       snprintf(srch, sizeof(srch), FORMAT, name,
14868          peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
14869          peer->host_dynamic ? " D " : "   ",    /* Dynamic or not? */
14870          ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? " N " : "   ", /* NAT=yes? */
14871          peer->ha ? " A " : "   ",  /* permit/deny */
14872          ntohs(peer->addr.sin_port), status,
14873          realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
14874 
14875       if (!s)  {/* Normal CLI list */
14876          ast_cli(fd, FORMAT, name, 
14877          peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
14878          peer->host_dynamic ? " D " : "   ",    /* Dynamic or not? */
14879          ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? " N " : "   ", /* NAT=yes? */
14880          peer->ha ? " A " : "   ",       /* permit/deny */
14881          
14882          ntohs(peer->addr.sin_port), status,
14883          realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
14884       } else { /* Manager format */
14885          /* The names here need to be the same as other channels */
14886          astman_append(s, 
14887          "Event: PeerEntry\r\n%s"
14888          "Channeltype: SIP\r\n"
14889          "ObjectName: %s\r\n"
14890          "ChanObjectType: peer\r\n" /* "peer" or "user" */
14891          "IPaddress: %s\r\n"
14892          "IPport: %d\r\n"
14893          "Dynamic: %s\r\n"
14894          "Natsupport: %s\r\n"
14895          "VideoSupport: %s\r\n"
14896          "TextSupport: %s\r\n"
14897          "ACL: %s\r\n"
14898          "Status: %s\r\n"
14899          "RealtimeDevice: %s\r\n\r\n", 
14900          idtext,
14901          peer->name, 
14902          peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "-none-",
14903          ntohs(peer->addr.sin_port), 
14904          peer->host_dynamic ? "yes" : "no",  /* Dynamic or not? */
14905          ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? "yes" : "no",  /* NAT=yes? */
14906          ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no",  /* VIDEOSUPPORT=yes? */
14907          ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "yes" : "no",   /* TEXTSUPPORT=yes? */
14908          peer->ha ? "yes" : "no",       /* permit/deny */
14909          status,
14910          realtimepeers ? (peer->is_realtime ? "yes":"no") : "no");
14911       }
14912       ao2_unlock(peer);
14913       unref_peer(peer, "toss iterator peer ptr");
14914    }
14915    
14916    if (!s)
14917       ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
14918               total_peers, peers_mon_online, peers_mon_offline, peers_unmon_online, peers_unmon_offline);
14919 
14920    if (havepattern)
14921       regfree(&regexbuf);
14922 
14923    if (total)
14924       *total = total_peers;
14925    
14926    ast_free(peerarray);
14927    
14928    return CLI_SUCCESS;
14929 #undef FORMAT
14930 #undef FORMAT2
14931 }
14932 
14933 static int peer_dump_func(void *userobj, void *arg, int flags)
14934 {
14935    struct sip_peer *peer = userobj;
14936    int refc = ao2_t_ref(userobj, 0, "");
14937    int *fd = arg;
14938    
14939    ast_cli(*fd, "name: %s\ntype: peer\nobjflags: %d\nrefcount: %d\n\n", 
14940           peer->name, 0, refc);
14941    return 0;
14942 }
14943 
14944 static int dialog_dump_func(void *userobj, void *arg, int flags)
14945 {
14946    struct sip_pvt *pvt = userobj;
14947    int refc = ao2_t_ref(userobj, 0, "");
14948    int *fd = arg;
14949    
14950    ast_cli(*fd, "name: %s\ntype: dialog\nobjflags: %d\nrefcount: %d\n\n", 
14951           pvt->callid, 0, refc);
14952    return 0;
14953 }
14954 
14955 
14956 /*! \brief List all allocated SIP Objects (realtime or static) */
14957 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14958 {
14959    char tmp[256];
14960    
14961    switch (cmd) {
14962    case CLI_INIT:
14963       e->command = "sip show objects";
14964       e->usage =
14965          "Usage: sip show objects\n"
14966          "       Lists status of known SIP objects\n";
14967       return NULL;
14968    case CLI_GENERATE:
14969       return NULL;
14970    }  
14971 
14972    if (a->argc != 3)
14973       return CLI_SHOWUSAGE;
14974    ast_cli(a->fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
14975    ao2_t_callback(peers, OBJ_NODATA, peer_dump_func, &a->fd, "initiate ao2_callback to dump peers");
14976    ast_cli(a->fd, "-= Registry objects: %d =-\n\n", regobjs);
14977    ASTOBJ_CONTAINER_DUMP(a->fd, tmp, sizeof(tmp), &regl);
14978    ast_cli(a->fd, "-= Dialog objects:\n\n");
14979    ao2_t_callback(dialogs, OBJ_NODATA, dialog_dump_func, &a->fd, "initiate ao2_callback to dump dialogs");
14980    return CLI_SUCCESS;
14981 }
14982 /*! \brief Print call group and pickup group */
14983 static void  print_group(int fd, ast_group_t group, int crlf)
14984 {
14985    char buf[256];
14986    ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
14987 }
14988 
14989 /*! \brief mapping between dtmf flags and strings */
14990 static struct _map_x_s dtmfstr[] = {
14991    { SIP_DTMF_RFC2833,     "rfc2833" },
14992    { SIP_DTMF_INFO,        "info" },
14993    { SIP_DTMF_SHORTINFO,   "shortinfo" },
14994    { SIP_DTMF_INBAND,      "inband" },
14995    { SIP_DTMF_AUTO,        "auto" },
14996    { -1,                   NULL }, /* terminator */
14997 };
14998 
14999 /*! \brief Convert DTMF mode to printable string */
15000 static const char *dtmfmode2str(int mode)
15001 {
15002    return map_x_s(dtmfstr, mode, "<error>");
15003 }
15004 
15005 /*! \brief maps a string to dtmfmode, returns -1 on error */
15006 static int str2dtmfmode(const char *str)
15007 {
15008    return map_s_x(dtmfstr, str, -1);
15009 }
15010 
15011 static struct _map_x_s insecurestr[] = {
15012    { SIP_INSECURE_PORT,    "port" },
15013    { SIP_INSECURE_INVITE,  "invite" },
15014    { SIP_INSECURE_PORT | SIP_INSECURE_INVITE, "port,invite" },
15015    { 0,                    "no" },
15016    { -1,                   NULL }, /* terminator */
15017 };
15018 
15019 /*! \brief Convert Insecure setting to printable string */
15020 static const char *insecure2str(int mode)
15021 {
15022    return map_x_s(insecurestr, mode, "<error>");
15023 }
15024 
15025 /*! \brief Destroy disused contexts between reloads
15026    Only used in reload_config so the code for regcontext doesn't get ugly
15027 */
15028 static void cleanup_stale_contexts(char *new, char *old)
15029 {
15030    char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
15031 
15032    while ((oldcontext = strsep(&old, "&"))) {
15033       stalecontext = '\0';
15034       ast_copy_string(newlist, new, sizeof(newlist));
15035       stringp = newlist;
15036       while ((newcontext = strsep(&stringp, "&"))) {
15037          if (!strcmp(newcontext, oldcontext)) {
15038             /* This is not the context you're looking for */
15039             stalecontext = '\0';
15040             break;
15041          } else if (strcmp(newcontext, oldcontext)) {
15042             stalecontext = oldcontext;
15043          }
15044          
15045       }
15046       if (stalecontext)
15047          ast_context_destroy(ast_context_find(stalecontext), "SIP");
15048    }
15049 }
15050 
15051 /*! 
15052  * \brief Match dialogs that need to be destroyed
15053  *
15054  * \details This is used with ao2_callback to unlink/delete all dialogs that
15055  * are marked needdestroy. It will return CMP_MATCH for candidates, and they
15056  * will be unlinked.
15057  *
15058  * \todo Re-work this to improve efficiency.  Currently, this function is called
15059  * on _every_ dialog after processing _every_ incoming SIP/UDP packet, or
15060  * potentially even more often when the scheduler has entries to run.
15061  */
15062 
15063 static int dialog_needdestroy(void *dialogobj, void *arg, int flags) 
15064 {
15065    struct sip_pvt *dialog = dialogobj;
15066    time_t *t = arg;
15067 
15068    if (sip_pvt_trylock(dialog)) {
15069       /* Don't block the monitor thread.  This function is called often enough
15070        * that we can wait for the next time around. */
15071       return 0;
15072    }
15073    
15074    /* Check RTP timeouts and kill calls if we have a timeout set and do not get RTP */
15075    check_rtp_timeout(dialog, *t);
15076 
15077    /* If we have sessions that needs to be destroyed, do it now */
15078    /* Check if we have outstanding requests not responsed to or an active call
15079       - if that's the case, wait with destruction */
15080    if (dialog->needdestroy && !dialog->packets && !dialog->owner) {
15081       /* We absolutely cannot destroy the rtp struct while a bridge is active or we WILL crash */
15082       if (dialog->rtp && ast_rtp_get_bridged(dialog->rtp)) {
15083          ast_debug(2, "Bridge still active.  Delaying destruction of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
15084          sip_pvt_unlock(dialog);
15085          return 0;
15086       }
15087       
15088       if (dialog->vrtp && ast_rtp_get_bridged(dialog->vrtp)) {
15089          ast_debug(2, "Bridge still active.  Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
15090          sip_pvt_unlock(dialog);
15091          return 0;
15092       }
15093 
15094       sip_pvt_unlock(dialog);
15095       /* no, the unlink should handle this: dialog_unref(dialog, "needdestroy: one more refcount decrement to allow dialog to be destroyed"); */
15096       /* the CMP_MATCH will unlink this dialog from the dialog hash table */
15097       dialog_unlink_all(dialog, TRUE, FALSE);
15098       return 0; /* the unlink_all should unlink this from the table, so.... no need to return a match */
15099    }
15100 
15101    sip_pvt_unlock(dialog);
15102 
15103    return 0;
15104 }
15105 
15106 /* this func is used with ao2_callback to unlink/delete all marked
15107    peers */
15108 static int peer_is_marked(void *peerobj, void *arg, int flags)
15109 {
15110    struct sip_peer *peer = peerobj;
15111    return peer->the_mark ? CMP_MATCH : 0;
15112 }
15113 
15114 /*! \brief Remove temporary realtime objects from memory (CLI) */
15115 /*! \todo XXXX Propably needs an overhaul after removal of the devices */
15116 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15117 {
15118    struct sip_peer *peer, *pi;
15119    int prunepeer = FALSE;
15120    int multi = FALSE;
15121    char *name = NULL;
15122    regex_t regexbuf;
15123    struct ao2_iterator i;
15124    static char *choices[] = { "all", "like", NULL };
15125    char *cmplt;
15126    
15127    if (cmd == CLI_INIT) {
15128       e->command = "sip prune realtime [peer|all]";
15129       e->usage =
15130          "Usage: sip prune realtime [peer [<name>|all|like <pattern>]|all]\n"
15131          "       Prunes object(s) from the cache.\n"
15132          "       Optional regular expression pattern is used to filter the objects.\n";
15133       return NULL;
15134    } else if (cmd == CLI_GENERATE) {
15135       if (a->pos == 4 && !strcasecmp(a->argv[3], "peer")) {
15136          cmplt = ast_cli_complete(a->word, choices, a->n);
15137          if (!cmplt)
15138             cmplt = complete_sip_peer(a->word, a->n - sizeof(choices), SIP_PAGE2_RTCACHEFRIENDS);
15139          return cmplt;
15140       }
15141       if (a->pos == 5 && !strcasecmp(a->argv[4], "like"))
15142          return complete_sip_peer(a->word, a->n, SIP_PAGE2_RTCACHEFRIENDS);
15143       return NULL;
15144    }
15145    switch (a->argc) {
15146    case 4:
15147       name = a->argv[3];
15148       /* we accept a name in position 3, but keywords are not good. */
15149       if (!strcasecmp(name, "peer") || !strcasecmp(name, "like"))
15150          return CLI_SHOWUSAGE;
15151       prunepeer = TRUE;
15152       if (!strcasecmp(name, "all")) {
15153          multi = TRUE;
15154          name = NULL;
15155       }
15156       /* else a single name, already set */
15157       break;
15158    case 5:
15159       /* sip prune realtime {peer|like} name */
15160       name = a->argv[4];
15161       if (!strcasecmp(a->argv[3], "peer"))
15162          prunepeer = TRUE;
15163       else if (!strcasecmp(a->argv[3], "like")) {
15164          prunepeer = TRUE;
15165          multi = TRUE;
15166       } else
15167          return CLI_SHOWUSAGE;
15168       if (!strcasecmp(name, "like"))
15169          return CLI_SHOWUSAGE;
15170       if (!multi && !strcasecmp(name, "all")) {
15171          multi = TRUE;
15172          name = NULL;
15173       }
15174       break;
15175    case 6:
15176       name = a->argv[5];
15177       multi = TRUE;
15178       /* sip prune realtime {peer} like name */
15179       if (strcasecmp(a->argv[4], "like"))
15180          return CLI_SHOWUSAGE;
15181       if (!strcasecmp(a->argv[3], "peer")) {
15182          prunepeer = TRUE;
15183       } else
15184          return CLI_SHOWUSAGE;
15185       break;
15186    default:
15187       return CLI_SHOWUSAGE;
15188    }
15189 
15190    if (multi && name) {
15191       if (regcomp(&regexbuf, name, REG_EXTENDED | REG_NOSUB))
15192          return CLI_SHOWUSAGE;
15193    }
15194 
15195    if (multi) {
15196       if (prunepeer) {
15197          int pruned = 0;
15198          
15199          i = ao2_iterator_init(peers, 0);
15200          while ((pi = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
15201             ao2_lock(pi);
15202             if (name && regexec(&regexbuf, pi->name, 0, NULL, 0)) {
15203                unref_peer(pi, "toss iterator peer ptr before continue");
15204                ao2_unlock(pi);
15205                continue;
15206             };
15207             if (ast_test_flag(&pi->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
15208                pi->the_mark = 1;
15209                pruned++;
15210             }
15211             ao2_unlock(pi);
15212             unref_peer(pi, "toss iterator peer ptr");
15213          }
15214          ao2_iterator_destroy(&i);
15215          if (pruned) {
15216             ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, NULL,
15217                   "initiating callback to remove marked peers");
15218             ast_cli(a->fd, "%d peers pruned.\n", pruned);
15219          } else
15220             ast_cli(a->fd, "No peers found to prune.\n");
15221       }
15222    } else {
15223       if (prunepeer) {
15224          struct sip_peer tmp;
15225          ast_copy_string(tmp.name, name, sizeof(tmp.name));
15226          if ((peer = ao2_t_find(peers, &tmp, OBJ_POINTER | OBJ_UNLINK, "finding to unlink from peers"))) {
15227             if (peer->addr.sin_addr.s_addr) {
15228                ao2_t_unlink(peers_by_ip, peer, "unlinking peer from peers_by_ip also");
15229             }
15230             if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
15231                ast_cli(a->fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
15232                /* put it back! */
15233                ao2_t_link(peers, peer, "link peer into peer table");
15234                if (peer->addr.sin_addr.s_addr) {
15235                   ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
15236                }
15237                
15238             } else
15239                ast_cli(a->fd, "Peer '%s' pruned.\n", name);
15240             unref_peer(peer, "sip_prune_realtime: unref_peer: tossing temp peer ptr");
15241          } else
15242             ast_cli(a->fd, "Peer '%s' not found.\n", name);
15243       }
15244    }
15245 
15246    return CLI_SUCCESS;
15247 }
15248 
15249 /*! \brief Print codec list from preference to CLI/manager */
15250 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
15251 {
15252    int x, codec;
15253 
15254    for(x = 0; x < 32 ; x++) {
15255       codec = ast_codec_pref_index(pref, x);
15256       if (!codec)
15257          break;
15258       ast_cli(fd, "%s", ast_getformatname(codec));
15259       ast_cli(fd, ":%d", pref->framing[x]);
15260       if (x < 31 && ast_codec_pref_index(pref, x + 1))
15261          ast_cli(fd, ",");
15262    }
15263    if (!x)
15264       ast_cli(fd, "none");
15265 }
15266 
15267 /*! \brief Print domain mode to cli */
15268 static const char *domain_mode_to_text(const enum domain_mode mode)
15269 {
15270    switch (mode) {
15271    case SIP_DOMAIN_AUTO:
15272       return "[Automatic]";
15273    case SIP_DOMAIN_CONFIG:
15274       return "[Configured]";
15275    }
15276 
15277    return "";
15278 }
15279 
15280 /*! \brief CLI command to list local domains */
15281 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15282 {
15283    struct domain *d;
15284 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
15285 
15286    switch (cmd) {
15287    case CLI_INIT:
15288       e->command = "sip show domains";
15289       e->usage =
15290          "Usage: sip show domains\n"
15291          "       Lists all configured SIP local domains.\n"
15292          "       Asterisk only responds to SIP messages to local domains.\n";
15293       return NULL;
15294    case CLI_GENERATE:
15295       return NULL;
15296    }
15297 
15298    if (AST_LIST_EMPTY(&domain_list)) {
15299       ast_cli(a->fd, "SIP Domain support not enabled.\n\n");
15300       return CLI_SUCCESS;
15301    } else {
15302       ast_cli(a->fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
15303       AST_LIST_LOCK(&domain_list);
15304       AST_LIST_TRAVERSE(&domain_list, d, list)
15305          ast_cli(a->fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
15306             domain_mode_to_text(d->mode));
15307       AST_LIST_UNLOCK(&domain_list);
15308       ast_cli(a->fd, "\n");
15309       return CLI_SUCCESS;
15310    }
15311 }
15312 #undef FORMAT
15313 
15314 static char mandescr_show_peer[] = 
15315 "Description: Show one SIP peer with details on current status.\n"
15316 "Variables: \n"
15317 "  Peer: <name>           The peer name you want to check.\n"
15318 "  ActionID: <id>   Optional action ID for this AMI transaction.\n";
15319 
15320 /*! \brief Show SIP peers in the manager API  */
15321 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
15322 {
15323    const char *a[4];
15324    const char *peer;
15325 
15326    peer = astman_get_header(m, "Peer");
15327    if (ast_strlen_zero(peer)) {
15328       astman_send_error(s, m, "Peer: <name> missing.");
15329       return 0;
15330    }
15331    a[0] = "sip";
15332    a[1] = "show";
15333    a[2] = "peer";
15334    a[3] = peer;
15335 
15336    _sip_show_peer(1, -1, s, m, 4, a);
15337    astman_append(s, "\r\n\r\n" );
15338    return 0;
15339 }
15340 
15341 /*! \brief Show one peer in detail */
15342 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15343 {
15344    switch (cmd) {
15345    case CLI_INIT:
15346       e->command = "sip show peer";
15347       e->usage =
15348          "Usage: sip show peer <name> [load]\n"
15349          "       Shows all details on one SIP peer and the current status.\n"
15350          "       Option \"load\" forces lookup of peer in realtime storage.\n";
15351       return NULL;
15352    case CLI_GENERATE:
15353       return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
15354    }
15355    return _sip_show_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
15356 }
15357 
15358 /*! \brief Send qualify message to peer from cli or manager. Mostly for debugging. */
15359 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
15360 {
15361    struct sip_peer *peer;
15362    int load_realtime;
15363 
15364    if (argc < 4)
15365       return CLI_SHOWUSAGE;
15366 
15367    load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
15368    if ((peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0))) {
15369       sip_poke_peer(peer, 1);
15370       unref_peer(peer, "qualify: done with peer");
15371    } else if (type == 0) {
15372       ast_cli(fd, "Peer '%s' not found\n", argv[3]);
15373    } else {
15374       astman_send_error(s, m, "Peer not found");
15375    }
15376    return CLI_SUCCESS;
15377 }
15378 
15379 /*! \brief Qualify SIP peers in the manager API  */
15380 static int manager_sip_qualify_peer(struct mansession *s, const struct message *m)
15381 {
15382    const char *a[4];
15383    const char *peer;
15384 
15385    peer = astman_get_header(m, "Peer");
15386    if (ast_strlen_zero(peer)) {
15387       astman_send_error(s, m, "Peer: <name> missing.");
15388       return 0;
15389    }
15390    a[0] = "sip";
15391    a[1] = "qualify";
15392    a[2] = "peer";
15393    a[3] = peer;
15394 
15395    _sip_qualify_peer(1, -1, s, m, 4, a);
15396    astman_append(s, "\r\n\r\n" );
15397    return 0;
15398 }
15399 
15400 /*! \brief Send an OPTIONS packet to a SIP peer */
15401 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15402 {
15403    switch (cmd) {
15404    case CLI_INIT:
15405       e->command = "sip qualify peer";
15406       e->usage =
15407          "Usage: sip qualify peer <name> [load]\n"
15408          "       Requests a response from one SIP peer and the current status.\n"
15409          "       Option \"load\" forces lookup of peer in realtime storage.\n";
15410       return NULL;
15411    case CLI_GENERATE:
15412       return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
15413    }
15414    return _sip_qualify_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
15415 }
15416 
15417 /*! \brief list peer mailboxes to CLI */
15418 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer)
15419 {
15420    struct sip_mailbox *mailbox;
15421 
15422    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
15423       ast_str_append(mailbox_str, 0, "%s%s%s%s",
15424          mailbox->mailbox,
15425          ast_strlen_zero(mailbox->context) ? "" : "@",
15426          S_OR(mailbox->context, ""),
15427          AST_LIST_NEXT(mailbox, entry) ? "," : "");
15428    }
15429 }
15430 
15431 static struct _map_x_s faxecmodes[] = {
15432    { SIP_PAGE2_T38SUPPORT_UDPTL,       "None"},
15433    { SIP_PAGE2_T38SUPPORT_UDPTL_FEC,      "FEC"},
15434    { SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY,  "Redundancy"},
15435    { -1,                NULL},
15436 };
15437 
15438 static const char *faxec2str(int faxec)
15439 {
15440    return map_x_s(faxecmodes, faxec, "Unknown");
15441 }
15442 
15443 /*! \brief Show one peer in detail (main function) */
15444 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
15445 {
15446    char status[30] = "";
15447    char cbuf[256];
15448    struct sip_peer *peer;
15449    char codec_buf[512];
15450    struct ast_codec_pref *pref;
15451    struct ast_variable *v;
15452    struct sip_auth *auth;
15453    int x = 0, codec = 0, load_realtime;
15454    int realtimepeers;
15455 
15456    realtimepeers = ast_check_realtime("sippeers");
15457 
15458    if (argc < 4)
15459       return CLI_SHOWUSAGE;
15460 
15461    load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
15462    peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0);
15463 
15464    if (s) {    /* Manager */
15465       if (peer) {
15466          const char *id = astman_get_header(m, "ActionID");
15467 
15468          astman_append(s, "Response: Success\r\n");
15469          if (!ast_strlen_zero(id))
15470             astman_append(s, "ActionID: %s\r\n", id);
15471       } else {
15472          snprintf (cbuf, sizeof(cbuf), "Peer %s not found.", argv[3]);
15473          astman_send_error(s, m, cbuf);
15474          return CLI_SUCCESS;
15475       }
15476    }
15477    if (peer && type==0 ) { /* Normal listing */
15478       struct ast_str *mailbox_str = ast_str_alloca(512);
15479       ast_cli(fd, "\n\n");
15480       ast_cli(fd, "  * Name       : %s\n", peer->name);
15481       if (realtimepeers) { /* Realtime is enabled */
15482          ast_cli(fd, "  Realtime peer: %s\n", peer->is_realtime ? "Yes, cached" : "No");
15483       }
15484       ast_cli(fd, "  Secret       : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
15485       ast_cli(fd, "  MD5Secret    : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
15486       ast_cli(fd, "  Remote Secret: %s\n", ast_strlen_zero(peer->remotesecret)?"<Not set>":"<Set>");
15487       for (auth = peer->auth; auth; auth = auth->next) {
15488          ast_cli(fd, "  Realm-auth   : Realm %-15.15s User %-10.20s ", auth->realm, auth->username);
15489          ast_cli(fd, "%s\n", !ast_strlen_zero(auth->secret)?"<Secret set>":(!ast_strlen_zero(auth->md5secret)?"<MD5secret set>" : "<Not set>"));
15490       }
15491       ast_cli(fd, "  Context      : %s\n", peer->context);
15492       ast_cli(fd, "  Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
15493       ast_cli(fd, "  Language     : %s\n", peer->language);
15494       if (!ast_strlen_zero(peer->accountcode))
15495          ast_cli(fd, "  Accountcode  : %s\n", peer->accountcode);
15496       ast_cli(fd, "  AMA flags    : %s\n", ast_cdr_flags2str(peer->amaflags));
15497       ast_cli(fd, "  Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
15498       ast_cli(fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(peer->callingpres));
15499       if (!ast_strlen_zero(peer->fromuser))
15500          ast_cli(fd, "  FromUser     : %s\n", peer->fromuser);
15501       if (!ast_strlen_zero(peer->fromdomain))
15502          ast_cli(fd, "  FromDomain   : %s\n", peer->fromdomain);
15503       ast_cli(fd, "  Callgroup    : ");
15504       print_group(fd, peer->callgroup, 0);
15505       ast_cli(fd, "  Pickupgroup  : ");
15506       print_group(fd, peer->pickupgroup, 0);
15507       peer_mailboxes_to_str(&mailbox_str, peer);
15508       ast_cli(fd, "  Mailbox      : %s\n", mailbox_str->str);
15509       ast_cli(fd, "  VM Extension : %s\n", peer->vmexten);
15510       ast_cli(fd, "  LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
15511       ast_cli(fd, "  Call limit   : %d\n", peer->call_limit);
15512       if (peer->busy_level)
15513          ast_cli(fd, "  Busy level   : %d\n", peer->busy_level);
15514       ast_cli(fd, "  Dynamic      : %s\n", cli_yesno(peer->host_dynamic));
15515       ast_cli(fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
15516       ast_cli(fd, "  MaxCallBR    : %d kbps\n", peer->maxcallbitrate);
15517       ast_cli(fd, "  Expire       : %ld\n", ast_sched_when(sched, peer->expire));
15518       ast_cli(fd, "  Insecure     : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
15519       ast_cli(fd, "  Nat          : %s\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
15520       ast_cli(fd, "  ACL          : %s\n", cli_yesno(peer->ha != NULL));
15521       ast_cli(fd, "  T.38 support : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
15522       ast_cli(fd, "  T.38 EC mode : %s\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
15523       ast_cli(fd, "  T.38 MaxDtgrm: %d\n", peer->t38_maxdatagram);
15524       ast_cli(fd, "  DirectMedia  : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)));
15525       ast_cli(fd, "  PromiscRedir : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)));
15526       ast_cli(fd, "  User=Phone   : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)));
15527       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)));
15528       ast_cli(fd, "  Text Support : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)));
15529       ast_cli(fd, "  Ign SDP ver  : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_IGNORESDPVERSION)));
15530       ast_cli(fd, "  Trust RPID   : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_TRUSTRPID)));
15531       ast_cli(fd, "  Send RPID    : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_SENDRPID)));
15532       ast_cli(fd, "  Subscriptions: %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
15533       ast_cli(fd, "  Overlap dial : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP)));
15534       ast_cli(fd, "  Forward Loop : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_FORWARD_LOOP_DETECTED)));
15535       if (peer->outboundproxy)
15536          ast_cli(fd, "  Outb. proxy  : %s %s\n", ast_strlen_zero(peer->outboundproxy->name) ? "<not set>" : peer->outboundproxy->name,
15537                      peer->outboundproxy->force ? "(forced)" : "");
15538 
15539       /* - is enumerated */
15540       ast_cli(fd, "  DTMFmode     : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
15541       ast_cli(fd, "  Timer T1     : %d\n", peer->timer_t1);
15542       ast_cli(fd, "  Timer B      : %d\n", peer->timer_b);
15543       ast_cli(fd, "  ToHost       : %s\n", peer->tohost);
15544       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));
15545       ast_cli(fd, "  Defaddr->IP  : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
15546       ast_cli(fd, "  Prim.Transp. : %s\n", get_transport(peer->socket.type));
15547       ast_cli(fd, "  Allowed.Trsp : %s\n", get_transport_list(peer->transports)); 
15548       if (!ast_strlen_zero(global_regcontext))
15549          ast_cli(fd, "  Reg. exten   : %s\n", peer->regexten);
15550       ast_cli(fd, "  Def. Username: %s\n", peer->username);
15551       ast_cli(fd, "  SIP Options  : ");
15552       if (peer->sipoptions) {
15553          int lastoption = -1;
15554          for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
15555             if (sip_options[x].id != lastoption) {
15556                if (peer->sipoptions & sip_options[x].id)
15557                   ast_cli(fd, "%s ", sip_options[x].text);
15558                lastoption = x;
15559             }
15560          }
15561       } else
15562          ast_cli(fd, "(none)");
15563 
15564       ast_cli(fd, "\n");
15565       ast_cli(fd, "  Codecs       : ");
15566       ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
15567       ast_cli(fd, "%s\n", codec_buf);
15568       ast_cli(fd, "  Codec Order  : (");
15569       print_codec_to_cli(fd, &peer->prefs);
15570       ast_cli(fd, ")\n");
15571 
15572       ast_cli(fd, "  Auto-Framing :  %s \n", cli_yesno(peer->autoframing));
15573       ast_cli(fd, "  100 on REG   : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_REGISTERTRYING) ? "Yes" : "No");
15574       ast_cli(fd, "  Status       : ");
15575       peer_status(peer, status, sizeof(status));
15576       ast_cli(fd, "%s\n", status);
15577       ast_cli(fd, "  Useragent    : %s\n", peer->useragent);
15578       ast_cli(fd, "  Reg. Contact : %s\n", peer->fullcontact);
15579       ast_cli(fd, "  Qualify Freq : %d ms\n", peer->qualifyfreq);
15580       if (peer->chanvars) {
15581          ast_cli(fd, "  Variables    :\n");
15582          for (v = peer->chanvars ; v ; v = v->next)
15583             ast_cli(fd, "                 %s = %s\n", v->name, v->value);
15584       }
15585 
15586       ast_cli(fd, "  Sess-Timers  : %s\n", stmode2str(peer->stimer.st_mode_oper));
15587       ast_cli(fd, "  Sess-Refresh : %s\n", strefresher2str(peer->stimer.st_ref));
15588       ast_cli(fd, "  Sess-Expires : %d secs\n", peer->stimer.st_max_se);
15589       ast_cli(fd, "  Min-Sess     : %d secs\n", peer->stimer.st_min_se);
15590       ast_cli(fd, "  Parkinglot   : %s\n", peer->parkinglot);
15591       ast_cli(fd, "\n");
15592       peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer ptr");
15593    } else  if (peer && type == 1) { /* manager listing */
15594       char buffer[256];
15595       struct ast_str *mailbox_str = ast_str_alloca(512);
15596       astman_append(s, "Channeltype: SIP\r\n");
15597       astman_append(s, "ObjectName: %s\r\n", peer->name);
15598       astman_append(s, "ChanObjectType: peer\r\n");
15599       astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
15600       astman_append(s, "RemoteSecretExist: %s\r\n", ast_strlen_zero(peer->remotesecret)?"N":"Y");
15601       astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
15602       astman_append(s, "Context: %s\r\n", peer->context);
15603       astman_append(s, "Language: %s\r\n", peer->language);
15604       if (!ast_strlen_zero(peer->accountcode))
15605          astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
15606       astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
15607       astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
15608       if (!ast_strlen_zero(peer->fromuser))
15609          astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
15610       if (!ast_strlen_zero(peer->fromdomain))
15611          astman_append(s, "SIP-FromDomain: %s\r\n", peer->fromdomain);
15612       astman_append(s, "Callgroup: ");
15613       astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->callgroup));
15614       astman_append(s, "Pickupgroup: ");
15615       astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->pickupgroup));
15616       peer_mailboxes_to_str(&mailbox_str, peer);
15617       astman_append(s, "VoiceMailbox: %s\r\n", mailbox_str->str);
15618       astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
15619       astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
15620       astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
15621       astman_append(s, "Busy-level: %d\r\n", peer->busy_level);
15622       astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
15623       astman_append(s, "Dynamic: %s\r\n", peer->host_dynamic?"Y":"N");
15624       astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
15625       astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched, peer->expire));
15626       astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
15627       astman_append(s, "SIP-NatSupport: %s\r\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
15628       astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
15629       astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
15630       astman_append(s, "SIP-DirectMedia: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
15631       astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
15632       astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
15633       astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
15634       astman_append(s, "SIP-TextSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)?"Y":"N"));
15635       astman_append(s, "SIP-T.38Support: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)?"Y":"N"));
15636       astman_append(s, "SIP-T.38EC: %s\r\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
15637       astman_append(s, "SIP-T.38MaxDtgrm: %d\r\n", peer->t38_maxdatagram);
15638       astman_append(s, "SIP-Sess-Timers: %s\r\n", stmode2str(peer->stimer.st_mode_oper));
15639       astman_append(s, "SIP-Sess-Refresh: %s\r\n", strefresher2str(peer->stimer.st_ref));
15640       astman_append(s, "SIP-Sess-Expires: %d\r\n", peer->stimer.st_max_se);
15641       astman_append(s, "SIP-Sess-Min: %d\r\n", peer->stimer.st_min_se);
15642 
15643       /* - is enumerated */
15644       astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
15645       astman_append(s, "ToHost: %s\r\n", peer->tohost);
15646       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));
15647       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));
15648       astman_append(s, "Default-Username: %s\r\n", peer->username);
15649       if (!ast_strlen_zero(global_regcontext))
15650          astman_append(s, "RegExtension: %s\r\n", peer->regexten);
15651       astman_append(s, "Codecs: ");
15652       ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
15653       astman_append(s, "%s\r\n", codec_buf);
15654       astman_append(s, "CodecOrder: ");
15655       pref = &peer->prefs;
15656       for(x = 0; x < 32 ; x++) {
15657          codec = ast_codec_pref_index(pref, x);
15658          if (!codec)
15659             break;
15660          astman_append(s, "%s", ast_getformatname(codec));
15661          if (x < 31 && ast_codec_pref_index(pref, x+1))
15662             astman_append(s, ",");
15663       }
15664 
15665       astman_append(s, "\r\n");
15666       astman_append(s, "Status: ");
15667       peer_status(peer, status, sizeof(status));
15668       astman_append(s, "%s\r\n", status);
15669       astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
15670       astman_append(s, "Reg-Contact: %s\r\n", peer->fullcontact);
15671       astman_append(s, "QualifyFreq: %d ms\r\n", peer->qualifyfreq);
15672       astman_append(s, "Parkinglot: %s\r\n", peer->parkinglot);
15673       if (peer->chanvars) {
15674          for (v = peer->chanvars ; v ; v = v->next) {
15675             astman_append(s, "ChanVariable: %s=%s\r\n", v->name, v->value);
15676          }
15677       }
15678 
15679       peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer");
15680 
15681    } else {
15682       ast_cli(fd, "Peer %s not found.\n", argv[3]);
15683       ast_cli(fd, "\n");
15684    }
15685 
15686    return CLI_SUCCESS;
15687 }
15688 
15689 /*! \brief Do completion on user name */
15690 static char *complete_sip_user(const char *word, int state)
15691 {
15692    char *result = NULL;
15693    int wordlen = strlen(word);
15694    int which = 0;
15695    struct ao2_iterator user_iter;
15696    struct sip_peer *user;
15697 
15698    user_iter = ao2_iterator_init(peers, 0);
15699    while ((user = ao2_iterator_next(&user_iter))) {
15700       ao2_lock(user);
15701       if (!(user->type & SIP_TYPE_USER)) {
15702          ao2_unlock(user);
15703          unref_peer(user, "complete sip user");
15704          continue;
15705       }
15706       /* locking of the object is not required because only the name and flags are being compared */
15707       if (!strncasecmp(word, user->name, wordlen) && ++which > state) {
15708          result = ast_strdup(user->name);
15709       }
15710       ao2_unlock(user);
15711       unref_peer(user, "complete sip user");
15712    }
15713    ao2_iterator_destroy(&user_iter);
15714    return result;
15715 }
15716 /*! \brief Support routine for 'sip show user' CLI */
15717 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
15718 {
15719    if (pos == 3)
15720       return complete_sip_user(word, state);
15721 
15722    return NULL;
15723 }
15724 
15725 /*! \brief Show one user in detail */
15726 static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15727 {
15728    char cbuf[256];
15729    struct sip_peer *user;
15730    struct ast_variable *v;
15731    int load_realtime;
15732 
15733    switch (cmd) {
15734    case CLI_INIT:
15735       e->command = "sip show user";
15736       e->usage =
15737          "Usage: sip show user <name> [load]\n"
15738          "       Shows all details on one SIP user and the current status.\n"
15739          "       Option \"load\" forces lookup of peer in realtime storage.\n";
15740       return NULL;
15741    case CLI_GENERATE:
15742       return complete_sip_show_user(a->line, a->word, a->pos, a->n);
15743    }
15744 
15745    if (a->argc < 4)
15746       return CLI_SHOWUSAGE;
15747 
15748    /* Load from realtime storage? */
15749    load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? TRUE : FALSE;
15750 
15751    if ((user = find_peer(a->argv[3], NULL, load_realtime, FINDUSERS, FALSE, 0))) {
15752       ao2_lock(user);
15753       ast_cli(a->fd, "\n\n");
15754       ast_cli(a->fd, "  * Name       : %s\n", user->name);
15755       ast_cli(a->fd, "  Secret       : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
15756       ast_cli(a->fd, "  MD5Secret    : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
15757       ast_cli(a->fd, "  Context      : %s\n", user->context);
15758       ast_cli(a->fd, "  Language     : %s\n", user->language);
15759       if (!ast_strlen_zero(user->accountcode))
15760          ast_cli(a->fd, "  Accountcode  : %s\n", user->accountcode);
15761       ast_cli(a->fd, "  AMA flags    : %s\n", ast_cdr_flags2str(user->amaflags));
15762       ast_cli(a->fd, "  Transfer mode: %s\n", transfermode2str(user->allowtransfer));
15763       ast_cli(a->fd, "  MaxCallBR    : %d kbps\n", user->maxcallbitrate);
15764       ast_cli(a->fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(user->callingpres));
15765       ast_cli(a->fd, "  Call limit   : %d\n", user->call_limit);
15766       ast_cli(a->fd, "  Callgroup    : ");
15767       print_group(a->fd, user->callgroup, 0);
15768       ast_cli(a->fd, "  Pickupgroup  : ");
15769       print_group(a->fd, user->pickupgroup, 0);
15770       ast_cli(a->fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
15771       ast_cli(a->fd, "  ACL          : %s\n", cli_yesno(user->ha != NULL));
15772       ast_cli(a->fd, "  Sess-Timers  : %s\n", stmode2str(user->stimer.st_mode_oper));
15773       ast_cli(a->fd, "  Sess-Refresh : %s\n", strefresher2str(user->stimer.st_ref));
15774       ast_cli(a->fd, "  Sess-Expires : %d secs\n", user->stimer.st_max_se);
15775       ast_cli(a->fd, "  Sess-Min-SE  : %d secs\n", user->stimer.st_min_se);
15776 
15777       ast_cli(a->fd, "  Codec Order  : (");
15778       print_codec_to_cli(a->fd, &user->prefs);
15779       ast_cli(a->fd, ")\n");
15780 
15781       ast_cli(a->fd, "  Auto-Framing:  %s \n", cli_yesno(user->autoframing));
15782       if (user->chanvars) {
15783          ast_cli(a->fd, "  Variables    :\n");
15784          for (v = user->chanvars ; v ; v = v->next)
15785             ast_cli(a->fd, "                 %s = %s\n", v->name, v->value);
15786       }
15787 
15788       ast_cli(a->fd, "\n");
15789 
15790       ao2_unlock(user);
15791       unref_peer(user, "sip show user");
15792    } else {
15793       ast_cli(a->fd, "User %s not found.\n", a->argv[3]);
15794       ast_cli(a->fd, "\n");
15795    }
15796 
15797    return CLI_SUCCESS;
15798 }
15799 
15800 
15801 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15802 {
15803    struct ast_str *cbuf;
15804    struct ast_cb_names cbnames = {9, { "retrans_pkt",
15805                                         "__sip_autodestruct",
15806                                         "expire_register",
15807                                         "auto_congest",
15808                                         "sip_reg_timeout",
15809                                         "sip_poke_peer_s",
15810                                         "sip_poke_noanswer",
15811                                         "sip_reregister",
15812                                         "sip_reinvite_retry"},
15813                            { retrans_pkt,
15814                                      __sip_autodestruct,
15815                                      expire_register,
15816                                      auto_congest,
15817                                      sip_reg_timeout,
15818                                      sip_poke_peer_s,
15819                                      sip_poke_noanswer,
15820                                      sip_reregister,
15821                                      sip_reinvite_retry}};
15822    
15823    switch (cmd) {
15824    case CLI_INIT:
15825       e->command = "sip show sched";
15826       e->usage =
15827          "Usage: sip show sched\n"
15828          "       Shows stats on what's in the sched queue at the moment\n";
15829       return NULL;
15830    case CLI_GENERATE:
15831       return NULL;
15832    }
15833 
15834    cbuf = ast_str_alloca(2048);
15835 
15836    ast_cli(a->fd, "\n");
15837    ast_sched_report(sched, &cbuf, &cbnames);
15838    ast_cli(a->fd, "%s", cbuf->str);
15839 
15840    return CLI_SUCCESS;
15841 }
15842 
15843 /*! \brief  Show SIP Registry (registrations with other SIP proxies */
15844 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15845 {
15846 #define FORMAT2 "%-30.30s %-6.6s %-12.12s  %8.8s %-20.20s %-25.25s\n"
15847 #define FORMAT  "%-30.30s %-6.6s %-12.12s  %8d %-20.20s %-25.25s\n"
15848    char host[80];
15849    char tmpdat[256];
15850    struct ast_tm tm;
15851    int counter = 0;
15852 
15853    switch (cmd) {
15854    case CLI_INIT:
15855       e->command = "sip show registry";
15856       e->usage =
15857          "Usage: sip show registry\n"
15858          "       Lists all registration requests and status.\n";
15859       return NULL;
15860    case CLI_GENERATE:
15861       return NULL;
15862    }
15863 
15864    if (a->argc != 3)
15865       return CLI_SHOWUSAGE;
15866    ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Refresh", "State", "Reg.Time");
15867    
15868    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
15869       ASTOBJ_RDLOCK(iterator);
15870       snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
15871       if (iterator->regtime.tv_sec) {
15872          ast_localtime(&iterator->regtime, &tm, NULL);
15873          ast_strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
15874       } else 
15875          tmpdat[0] = '\0';
15876       ast_cli(a->fd, FORMAT, host, (iterator->dnsmgr) ? "Y" : "N", iterator->username, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
15877       ASTOBJ_UNLOCK(iterator);
15878       counter++;
15879    } while(0));
15880    ast_cli(a->fd, "%d SIP registrations.\n", counter);
15881    return CLI_SUCCESS;
15882 #undef FORMAT
15883 #undef FORMAT2
15884 }
15885 
15886 /*! \brief Unregister (force expiration) a SIP peer in the registry via CLI 
15887    \note This function does not tell the SIP device what's going on,
15888    so use it with great care.
15889 */
15890 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15891 {
15892    struct sip_peer *peer;
15893    int load_realtime = 0;
15894 
15895    switch (cmd) {
15896    case CLI_INIT:
15897       e->command = "sip unregister";
15898       e->usage =
15899          "Usage: sip unregister <peer>\n"
15900          "       Unregister (force expiration) a SIP peer from the registry\n";
15901       return NULL;
15902    case CLI_GENERATE:
15903       return complete_sip_unregister(a->line, a->word, a->pos, a->n);
15904    }
15905    
15906    if (a->argc != 3)
15907       return CLI_SHOWUSAGE;
15908    
15909    if ((peer = find_peer(a->argv[2], NULL, load_realtime, FINDPEERS, TRUE, 0))) {
15910       if (peer->expire > 0) {
15911          AST_SCHED_DEL_UNREF(sched, peer->expire,
15912             unref_peer(peer, "remove register expire ref"));
15913          expire_register(ref_peer(peer, "ref for expire_register"));
15914          ast_cli(a->fd, "Unregistered peer \'%s\'\n\n", a->argv[2]);
15915       } else {
15916          ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
15917       }
15918       unref_peer(peer, "sip_unregister: unref_peer via sip_unregister: done with peer from find_peer call");
15919    } else {
15920       ast_cli(a->fd, "Peer unknown: \'%s\'. Not unregistered.\n", a->argv[2]);
15921    }
15922    
15923    return CLI_SUCCESS;
15924 }
15925 
15926 /*! \brief Callback for show_chanstats */
15927 static int show_chanstats_cb(void *__cur, void *__arg, int flags)
15928 {
15929 #define FORMAT2 "%-15.15s  %-11.11s  %-8.8s %-10.10s  %-10.10s (     %%) %-6.6s %-10.10s  %-10.10s (     %%) %-6.6s\n"
15930 #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"
15931    struct sip_pvt *cur = __cur;
15932    unsigned int rxcount, txcount, rxploss, txploss;
15933    char durbuf[10];
15934         int duration;
15935         int durh, durm, durs;
15936    struct ast_channel *c = cur->owner;
15937    struct __show_chan_arg *arg = __arg;
15938    int fd = arg->fd;
15939 
15940 
15941    if (cur->subscribed != NONE) /* Subscriptions */
15942       return 0;   /* don't care, we scan all channels */
15943 
15944    if (!cur->rtp) {
15945       if (sipdebug)
15946          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");
15947       return 0;   /* don't care, we scan all channels */
15948    }
15949    rxcount = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXCOUNT);
15950    txcount = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXCOUNT);
15951    rxploss = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXPLOSS);
15952    txploss = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXPLOSS);
15953 
15954    /* Find the duration of this channel */
15955    if (c && c->cdr && !ast_tvzero(c->cdr->start)) {
15956       duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
15957       durh = duration / 3600;
15958       durm = (duration % 3600) / 60;
15959       durs = duration % 60;
15960       snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
15961    } else {
15962       durbuf[0] = '\0';
15963    }
15964    /* Print stats for every call with RTP */
15965    ast_cli(fd, FORMAT, 
15966       ast_inet_ntoa(cur->sa.sin_addr), 
15967       cur->callid, 
15968       durbuf,
15969       rxcount > (unsigned int) 100000 ? (unsigned int) (rxcount)/(unsigned int) 1000 : rxcount,
15970       rxcount > (unsigned int) 100000 ? "K":" ",
15971       rxploss,
15972       (rxcount + rxploss) > 0 ? (double) rxploss / (rxcount + rxploss) * 100 : 0,
15973       ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXJITTER),
15974       txcount > (unsigned int) 100000 ? (unsigned int) (txcount)/(unsigned int) 1000 : txcount,
15975       txcount > (unsigned int) 100000 ? "K":" ",
15976       txploss,
15977       txcount > 0 ? (double) txploss / txcount * 100 : 0,
15978       ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXJITTER)
15979    );
15980    arg->numchans++;
15981 
15982    return 0;   /* don't care, we scan all channels */
15983 }
15984 
15985 /*! \brief SIP show channelstats CLI (main function) */
15986 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15987 {
15988    struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
15989 
15990    switch (cmd) {
15991    case CLI_INIT:
15992       e->command = "sip show channelstats";
15993       e->usage =
15994          "Usage: sip show channelstats\n"
15995          "       Lists all currently active SIP channel's RTCP statistics.\n"
15996          "       Note that calls in the much optimized RTP P2P bridge mode will not show any packets here.";
15997       return NULL;
15998    case CLI_GENERATE:
15999       return NULL;
16000    }
16001 
16002    if (a->argc != 3)
16003       return CLI_SHOWUSAGE;
16004 
16005    ast_cli(a->fd, FORMAT2, "Peer", "Call ID", "Duration", "Recv: Pack", "Lost", "Jitter", "Send: Pack", "Lost", "Jitter");
16006    /* iterate on the container and invoke the callback on each item */
16007    ao2_t_callback(dialogs, OBJ_NODATA, show_chanstats_cb, &arg, "callback to sip show chanstats");
16008    ast_cli(a->fd, "%d active SIP channel%s\n", arg.numchans, (arg.numchans != 1) ? "s" : ""); 
16009    return CLI_SUCCESS;
16010 }
16011 #undef FORMAT
16012 #undef FORMAT2
16013 
16014 /*! \brief List global settings for the SIP channel */
16015 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16016 {
16017    int realtimepeers;
16018    int realtimeregs;
16019    char codec_buf[SIPBUFSIZE];
16020    const char *msg;  /* temporary msg pointer */
16021 
16022    switch (cmd) {
16023    case CLI_INIT:
16024       e->command = "sip show settings";
16025       e->usage =
16026          "Usage: sip show settings\n"
16027          "       Provides detailed list of the configuration of the SIP channel.\n";
16028       return NULL;
16029    case CLI_GENERATE:
16030       return NULL;
16031    }
16032 
16033 
16034    realtimepeers = ast_check_realtime("sippeers");
16035    realtimeregs = ast_check_realtime("sipregs");
16036 
16037    if (a->argc != 3)
16038       return CLI_SHOWUSAGE;
16039    ast_cli(a->fd, "\n\nGlobal Settings:\n");
16040    ast_cli(a->fd, "----------------\n");
16041    ast_cli(a->fd, "  UDP SIP Port:           %d\n", ntohs(bindaddr.sin_port));
16042    ast_cli(a->fd, "  UDP Bindaddress:        %s\n", ast_inet_ntoa(bindaddr.sin_addr));
16043    ast_cli(a->fd, "  TCP SIP Port:           ");
16044    if (sip_tcp_desc.local_address.sin_family == AF_INET) {
16045       ast_cli(a->fd, "%d\n", ntohs(sip_tcp_desc.local_address.sin_port));
16046       ast_cli(a->fd, "  TCP Bindaddress:        %s\n", ast_inet_ntoa(sip_tcp_desc.local_address.sin_addr));
16047    } else {
16048       ast_cli(a->fd, "Disabled\n");
16049    }
16050    ast_cli(a->fd, "  TLS SIP Port:           ");
16051    if (default_tls_cfg.enabled != FALSE) {
16052       ast_cli(a->fd, "%d\n", ntohs(sip_tls_desc.local_address.sin_port));
16053       ast_cli(a->fd, "  TLS Bindaddress:        %s\n", ast_inet_ntoa(sip_tls_desc.local_address.sin_addr));
16054    } else {
16055       ast_cli(a->fd, "Disabled\n");
16056    }
16057    ast_cli(a->fd, "  Videosupport:           %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT)));
16058    ast_cli(a->fd, "  Textsupport:            %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT)));
16059    ast_cli(a->fd, "  Ignore SDP sess. ver.:  %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION)));
16060    ast_cli(a->fd, "  AutoCreate Peer:        %s\n", cli_yesno(sip_cfg.autocreatepeer));
16061    ast_cli(a->fd, "  Match Auth Username:    %s\n", cli_yesno(global_match_auth_username));
16062    ast_cli(a->fd, "  Allow unknown access:   %s\n", cli_yesno(sip_cfg.allowguest));
16063    ast_cli(a->fd, "  Allow subscriptions:    %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
16064    ast_cli(a->fd, "  Allow overlap dialing:  %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)));
16065    ast_cli(a->fd, "  Allow promsic. redir:   %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_PROMISCREDIR)));
16066    ast_cli(a->fd, "  Enable call counters:   %s\n", cli_yesno(global_callcounter));
16067    ast_cli(a->fd, "  SIP domain support:     %s\n", cli_yesno(!AST_LIST_EMPTY(&domain_list)));
16068    ast_cli(a->fd, "  Realm. auth:            %s\n", cli_yesno(authl != NULL));
16069    ast_cli(a->fd, "  Our auth realm          %s\n", sip_cfg.realm);
16070    ast_cli(a->fd, "  Call to non-local dom.: %s\n", cli_yesno(sip_cfg.allow_external_domains));
16071    ast_cli(a->fd, "  URI user is phone no:   %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_USEREQPHONE)));
16072    ast_cli(a->fd, "  Always auth rejects:    %s\n", cli_yesno(sip_cfg.alwaysauthreject));
16073    ast_cli(a->fd, "  Direct RTP setup:       %s\n", cli_yesno(sip_cfg.directrtpsetup));
16074    ast_cli(a->fd, "  User Agent:             %s\n", global_useragent);
16075    ast_cli(a->fd, "  SDP Session Name:       %s\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
16076    ast_cli(a->fd, "  SDP Owner Name:         %s\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner);
16077    ast_cli(a->fd, "  Reg. context:           %s\n", S_OR(global_regcontext, "(not set)"));
16078    ast_cli(a->fd, "  Regexten on Qualify:    %s\n", cli_yesno(sip_cfg.regextenonqualify));
16079    ast_cli(a->fd, "  Caller ID:              %s\n", default_callerid);
16080    ast_cli(a->fd, "  From: Domain:           %s\n", default_fromdomain);
16081    ast_cli(a->fd, "  Record SIP history:     %s\n", recordhistory ? "On" : "Off");
16082    ast_cli(a->fd, "  Call Events:            %s\n", sip_cfg.callevents ? "On" : "Off");
16083    ast_cli(a->fd, "  Auth. Failure Events:   %s\n", global_authfailureevents ? "On" : "Off");
16084 
16085    ast_cli(a->fd, "  T.38 support:           %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
16086    ast_cli(a->fd, "  T.38 EC mode:           %s\n", faxec2str(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
16087    ast_cli(a->fd, "  T.38 MaxDtgrm:          %d\n", global_t38_maxdatagram);
16088 
16089    if (!realtimepeers && !realtimeregs)
16090       ast_cli(a->fd, "  SIP realtime:           Disabled\n" );
16091    else
16092       ast_cli(a->fd, "  SIP realtime:           Enabled\n" );
16093    ast_cli(a->fd, "  Qualify Freq :          %d ms\n", global_qualifyfreq);
16094    ast_cli(a->fd, "\nNetwork QoS Settings:\n");
16095    ast_cli(a->fd, "---------------------------\n");
16096    ast_cli(a->fd, "  IP ToS SIP:             %s\n", ast_tos2str(global_tos_sip));
16097    ast_cli(a->fd, "  IP ToS RTP audio:       %s\n", ast_tos2str(global_tos_audio));
16098    ast_cli(a->fd, "  IP ToS RTP video:       %s\n", ast_tos2str(global_tos_video));
16099    ast_cli(a->fd, "  IP ToS RTP text:        %s\n", ast_tos2str(global_tos_text));
16100    ast_cli(a->fd, "  802.1p CoS SIP:         %d\n", global_cos_sip);
16101    ast_cli(a->fd, "  802.1p CoS RTP audio:   %d\n", global_cos_audio);
16102    ast_cli(a->fd, "  802.1p CoS RTP video:   %d\n", global_cos_video);
16103    ast_cli(a->fd, "  802.1p CoS RTP text:    %d\n", global_cos_text);
16104    ast_cli(a->fd, "  Jitterbuffer enabled:   %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_ENABLED)));
16105    ast_cli(a->fd, "  Jitterbuffer forced:    %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_FORCED)));
16106    ast_cli(a->fd, "  Jitterbuffer max size:  %ld\n", global_jbconf.max_size);
16107    ast_cli(a->fd, "  Jitterbuffer resync:    %ld\n", global_jbconf.resync_threshold);
16108    ast_cli(a->fd, "  Jitterbuffer impl:      %s\n", global_jbconf.impl);
16109    ast_cli(a->fd, "  Jitterbuffer log:       %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_LOG)));
16110 
16111    ast_cli(a->fd, "\nNetwork Settings:\n");
16112    ast_cli(a->fd, "---------------------------\n");
16113    /* determine if/how SIP address can be remapped */
16114    if (localaddr == NULL)
16115       msg = "Disabled, no localnet list";
16116    else if (externip.sin_addr.s_addr == 0)
16117       msg = "Disabled, externip is 0.0.0.0";
16118    else if (stunaddr.sin_addr.s_addr != 0)
16119       msg = "Enabled using STUN";
16120    else if (!ast_strlen_zero(externhost))
16121       msg = "Enabled using externhost";
16122    else
16123       msg = "Enabled using externip";
16124    ast_cli(a->fd, "  SIP address remapping:  %s\n", msg);
16125    ast_cli(a->fd, "  Externhost:             %s\n", S_OR(externhost, "<none>"));
16126    ast_cli(a->fd, "  Externip:               %s:%d\n", ast_inet_ntoa(externip.sin_addr), ntohs(externip.sin_port));
16127    ast_cli(a->fd, "  Externrefresh:          %d\n", externrefresh);
16128    ast_cli(a->fd, "  Internal IP:            %s:%d\n", ast_inet_ntoa(internip.sin_addr), ntohs(internip.sin_port));
16129    {
16130       struct ast_ha *d;
16131       const char *prefix = "Localnet:";
16132       char buf[INET_ADDRSTRLEN]; /* need to print two addresses */
16133 
16134       for (d = localaddr; d ; prefix = "", d = d->next) {
16135          ast_cli(a->fd, "  %-24s%s/%s\n",
16136              prefix, ast_inet_ntoa(d->netaddr),
16137              inet_ntop(AF_INET, &d->netmask, buf, sizeof(buf)) );
16138       }
16139    }
16140    ast_cli(a->fd, "  STUN server:            %s:%d\n", ast_inet_ntoa(stunaddr.sin_addr), ntohs(stunaddr.sin_port));
16141  
16142    ast_cli(a->fd, "\nGlobal Signalling Settings:\n");
16143    ast_cli(a->fd, "---------------------------\n");
16144    ast_cli(a->fd, "  Codecs:                 ");
16145    ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, global_capability);
16146    ast_cli(a->fd, "%s\n", codec_buf);
16147    ast_cli(a->fd, "  Codec Order:            ");
16148    print_codec_to_cli(a->fd, &default_prefs);
16149    ast_cli(a->fd, "\n");
16150    ast_cli(a->fd, "  Relax DTMF:             %s\n", cli_yesno(global_relaxdtmf));
16151    ast_cli(a->fd, "  RFC2833 Compensation:   %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE)));
16152    ast_cli(a->fd, "  Compact SIP headers:    %s\n", cli_yesno(sip_cfg.compactheaders));
16153    ast_cli(a->fd, "  RTP Keepalive:          %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
16154    ast_cli(a->fd, "  RTP Timeout:            %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
16155    ast_cli(a->fd, "  RTP Hold Timeout:       %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
16156    ast_cli(a->fd, "  MWI NOTIFY mime type:   %s\n", default_notifymime);
16157    ast_cli(a->fd, "  DNS SRV lookup:         %s\n", cli_yesno(sip_cfg.srvlookup));
16158    ast_cli(a->fd, "  Pedantic SIP support:   %s\n", cli_yesno(sip_cfg.pedanticsipchecking));
16159    ast_cli(a->fd, "  Reg. min duration       %d secs\n", min_expiry);
16160    ast_cli(a->fd, "  Reg. max duration:      %d secs\n", max_expiry);
16161    ast_cli(a->fd, "  Reg. default duration:  %d secs\n", default_expiry);
16162    ast_cli(a->fd, "  Outbound reg. timeout:  %d secs\n", global_reg_timeout);
16163    ast_cli(a->fd, "  Outbound reg. attempts: %d\n", global_regattempts_max);
16164    ast_cli(a->fd, "  Notify ringing state:   %s\n", cli_yesno(sip_cfg.notifyringing));
16165    if (sip_cfg.notifyringing) {
16166       ast_cli(a->fd, "    Include CID:          %s%s\n",
16167             cli_yesno(sip_cfg.notifycid),
16168             sip_cfg.notifycid == IGNORE_CONTEXT ? " (Ignoring context)" : "");
16169    }
16170    ast_cli(a->fd, "  Notify hold state:      %s\n", cli_yesno(sip_cfg.notifyhold));
16171    ast_cli(a->fd, "  SIP Transfer mode:      %s\n", transfermode2str(sip_cfg.allowtransfer));
16172    ast_cli(a->fd, "  Max Call Bitrate:       %d kbps\n", default_maxcallbitrate);
16173    ast_cli(a->fd, "  Auto-Framing:           %s\n", cli_yesno(global_autoframing));
16174    ast_cli(a->fd, "  Outb. proxy:            %s %s\n", ast_strlen_zero(sip_cfg.outboundproxy.name) ? "<not set>" : sip_cfg.outboundproxy.name,
16175                      sip_cfg.outboundproxy.force ? "(forced)" : "");
16176    ast_cli(a->fd, "  Session Timers:         %s\n", stmode2str(global_st_mode));
16177    ast_cli(a->fd, "  Session Refresher:      %s\n", strefresher2str (global_st_refresher));
16178    ast_cli(a->fd, "  Session Expires:        %d secs\n", global_max_se);
16179    ast_cli(a->fd, "  Session Min-SE:         %d secs\n", global_min_se);
16180    ast_cli(a->fd, "  Timer T1:               %d\n", global_t1);
16181    ast_cli(a->fd, "  Timer T1 minimum:       %d\n", global_t1min);
16182    ast_cli(a->fd, "  Timer B:                %d\n", global_timer_b);
16183    ast_cli(a->fd, "  No premature media:     %s\n", global_prematuremediafilter ? "Yes" : "No");
16184 
16185    ast_cli(a->fd, "\nDefault Settings:\n");
16186    ast_cli(a->fd, "-----------------\n");
16187    ast_cli(a->fd, "  Allowed transports:     %s\n", get_transport_list(default_transports)); 
16188    ast_cli(a->fd, "  Outbound transport:    %s\n", get_transport(default_primary_transport));
16189    ast_cli(a->fd, "  Context:                %s\n", sip_cfg.default_context);
16190    ast_cli(a->fd, "  Nat:                    %s\n", nat2str(ast_test_flag(&global_flags[0], SIP_NAT)));
16191    ast_cli(a->fd, "  DTMF:                   %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
16192    ast_cli(a->fd, "  Qualify:                %d\n", default_qualify);
16193    ast_cli(a->fd, "  Use ClientCode:         %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_USECLIENTCODE)));
16194    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" );
16195    ast_cli(a->fd, "  Language:               %s\n", default_language);
16196    ast_cli(a->fd, "  MOH Interpret:          %s\n", default_mohinterpret);
16197    ast_cli(a->fd, "  MOH Suggest:            %s\n", default_mohsuggest);
16198    ast_cli(a->fd, "  Voice Mail Extension:   %s\n", default_vmexten);
16199    ast_cli(a->fd, "  Forward Detected Loops: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_FORWARD_LOOP_DETECTED)));
16200    
16201    if (realtimepeers || realtimeregs) {
16202       ast_cli(a->fd, "\nRealtime SIP Settings:\n");
16203       ast_cli(a->fd, "----------------------\n");
16204       ast_cli(a->fd, "  Realtime Peers:         %s\n", cli_yesno(realtimepeers));
16205       ast_cli(a->fd, "  Realtime Regs:          %s\n", cli_yesno(realtimeregs));
16206       ast_cli(a->fd, "  Cache Friends:          %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)));
16207       ast_cli(a->fd, "  Update:                 %s\n", cli_yesno(sip_cfg.peer_rtupdate));
16208       ast_cli(a->fd, "  Ignore Reg. Expire:     %s\n", cli_yesno(sip_cfg.ignore_regexpire));
16209       ast_cli(a->fd, "  Save sys. name:         %s\n", cli_yesno(sip_cfg.rtsave_sysname));
16210       ast_cli(a->fd, "  Auto Clear:             %d\n", sip_cfg.rtautoclear);
16211    }
16212    ast_cli(a->fd, "\n----\n");
16213    return CLI_SUCCESS;
16214 }
16215 
16216 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16217 {
16218 #define FORMAT  "%-30.30s  %-12.12s  %-10.10s  %-10.10s\n"
16219    char host[80];
16220    
16221    switch (cmd) {
16222    case CLI_INIT:
16223       e->command = "sip show mwi";
16224       e->usage =
16225          "Usage: sip show mwi\n"
16226          "       Provides a list of MWI subscriptions and status.\n";
16227       return NULL;
16228    case CLI_GENERATE:
16229       return NULL;
16230    }
16231    
16232    ast_cli(a->fd, FORMAT, "Host", "Username", "Mailbox", "Subscribed");
16233    
16234    ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
16235       ASTOBJ_RDLOCK(iterator);
16236       snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
16237       ast_cli(a->fd, FORMAT, host, iterator->username, iterator->mailbox, iterator->subscribed ? "Yes" : "No");
16238       ASTOBJ_UNLOCK(iterator);
16239    } while(0));
16240 
16241    return CLI_SUCCESS;
16242 #undef FORMAT
16243 }
16244 
16245 
16246 /*! \brief Show subscription type in string format */
16247 static const char *subscription_type2str(enum subscriptiontype subtype)
16248 {
16249    int i;
16250 
16251    for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
16252       if (subscription_types[i].type == subtype) {
16253          return subscription_types[i].text;
16254       }
16255    }
16256    return subscription_types[0].text;
16257 }
16258 
16259 /*! \brief Find subscription type in array */
16260 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
16261 {
16262    int i;
16263 
16264    for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
16265       if (subscription_types[i].type == subtype) {
16266          return &subscription_types[i];
16267       }
16268    }
16269    return &subscription_types[0];
16270 }
16271 
16272 /*
16273  * We try to structure all functions that loop on data structures as
16274  * a handler for individual entries, and a mainloop that iterates
16275  * on the main data structure. This way, moving the code to containers
16276  * that support iteration through callbacks will be a lot easier.
16277  */
16278 
16279 #define FORMAT4 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-13.13s  %-15.15s %-10.10s %-6.6d\n"
16280 #define FORMAT3 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-13.13s  %-15.15s %-10.10s %-6.6s\n"
16281 #define FORMAT2 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-7.7s  %-15.15s %-6.6s\n"
16282 #define FORMAT  "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-3.3s %-3.3s  %-15.15s %-10.10s\n"
16283 
16284 /*! \brief callback for show channel|subscription */
16285 static int show_channels_cb(void *__cur, void *__arg, int flags)
16286 {
16287    struct sip_pvt *cur = __cur;
16288    struct __show_chan_arg *arg = __arg;
16289    const struct sockaddr_in *dst = sip_real_dst(cur);
16290    
16291    /* XXX indentation preserved to reduce diff. Will be fixed later */
16292    if (cur->subscribed == NONE && !arg->subscriptions) {
16293       /* set if SIP transfer in progress */
16294       const char *referstatus = cur->refer ? referstatus2str(cur->refer->status) : "";
16295       char formatbuf[SIPBUFSIZE/2];
16296       
16297       ast_cli(arg->fd, FORMAT, ast_inet_ntoa(dst->sin_addr), 
16298             S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
16299             cur->callid, 
16300             ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0),
16301             cli_yesno(ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD)),
16302             cur->needdestroy ? "(d)" : "",
16303             cur->lastmsg ,
16304             referstatus
16305          );
16306       arg->numchans++;
16307    }
16308    if (cur->subscribed != NONE && arg->subscriptions) {
16309       struct ast_str *mailbox_str = ast_str_alloca(512);
16310       if (cur->subscribed == MWI_NOTIFICATION && cur->relatedpeer)
16311          peer_mailboxes_to_str(&mailbox_str, cur->relatedpeer);
16312       ast_cli(arg->fd, FORMAT4, ast_inet_ntoa(dst->sin_addr),
16313             S_OR(cur->username, S_OR(cur->cid_num, "(None)")), 
16314                cur->callid,
16315             /* the 'complete' exten/context is hidden in the refer_to field for subscriptions */
16316             cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
16317             cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate), 
16318             subscription_type2str(cur->subscribed),
16319             cur->subscribed == MWI_NOTIFICATION ? S_OR(mailbox_str->str, "<none>") : "<none>",
16320             cur->expiry
16321          );
16322       arg->numchans++;
16323    }
16324    return 0;   /* don't care, we scan all channels */
16325 }
16326 
16327 /*! \brief CLI for show channels or subscriptions.
16328  * This is a new-style CLI handler so a single function contains
16329  * the prototype for the function, the 'generator' to produce multiple
16330  * entries in case it is required, and the actual handler for the command.
16331  */
16332 static char *sip_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16333 {
16334    struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
16335 
16336 
16337    if (cmd == CLI_INIT) {
16338       e->command = "sip show {channels|subscriptions}";
16339       e->usage =
16340          "Usage: sip show channels\n"
16341          "       Lists all currently active SIP calls (dialogs).\n"
16342          "Usage: sip show subscriptions\n"
16343          "       Lists active SIP subscriptions.\n";
16344       return NULL;
16345    } else if (cmd == CLI_GENERATE)
16346       return NULL;
16347 
16348    if (a->argc != e->args)
16349       return CLI_SHOWUSAGE;
16350    arg.subscriptions = !strcasecmp(a->argv[e->args - 1], "subscriptions");
16351    if (!arg.subscriptions)
16352       ast_cli(arg.fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Format", "Hold", "Last Message", "Expiry");
16353    else
16354       ast_cli(arg.fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox", "Expiry");
16355 
16356    /* iterate on the container and invoke the callback on each item */
16357    ao2_t_callback(dialogs, OBJ_NODATA, show_channels_cb, &arg, "callback to show channels");
16358    
16359    /* print summary information */
16360    ast_cli(arg.fd, "%d active SIP %s%s\n", arg.numchans,
16361       (arg.subscriptions ? "subscription" : "dialog"),
16362       ESS(arg.numchans));  /* ESS(n) returns an "s" if n>1 */
16363    return CLI_SUCCESS;
16364 #undef FORMAT
16365 #undef FORMAT2
16366 #undef FORMAT3
16367 }
16368 
16369 /*! \brief Support routine for 'sip show channel' and 'sip show history' CLI
16370  * This is in charge of generating all strings that match a prefix in the
16371  * given position. As many functions of this kind, each invokation has
16372  * O(state) time complexity so be careful in using it.
16373  */
16374 static char *complete_sipch(const char *line, const char *word, int pos, int state)
16375 {
16376    int which=0;
16377    struct sip_pvt *cur;
16378    char *c = NULL;
16379    int wordlen = strlen(word);
16380    struct ao2_iterator i;
16381 
16382    if (pos != 3) {
16383       return NULL;
16384    }
16385 
16386    i = ao2_iterator_init(dialogs, 0);
16387    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
16388       sip_pvt_lock(cur);
16389       if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
16390          c = ast_strdup(cur->callid);
16391          sip_pvt_unlock(cur);
16392          dialog_unref(cur, "drop ref in iterator loop break");
16393          break;
16394       }
16395       sip_pvt_unlock(cur);
16396       dialog_unref(cur, "drop ref in iterator loop");
16397    }
16398    ao2_iterator_destroy(&i);
16399    return c;
16400 }
16401 
16402 
16403 /*! \brief Do completion on peer name */
16404 static char *complete_sip_peer(const char *word, int state, int flags2)
16405 {
16406    char *result = NULL;
16407    int wordlen = strlen(word);
16408    int which = 0;
16409    struct ao2_iterator i = ao2_iterator_init(peers, 0);
16410    struct sip_peer *peer;
16411 
16412    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
16413       /* locking of the object is not required because only the name and flags are being compared */
16414       if (!strncasecmp(word, peer->name, wordlen) &&
16415             (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
16416             ++which > state)
16417          result = ast_strdup(peer->name);
16418       unref_peer(peer, "toss iterator peer ptr before break");
16419       if (result) {
16420          break;
16421       }
16422    }
16423    ao2_iterator_destroy(&i);
16424    return result;
16425 }
16426 
16427 /*! \brief Do completion on registered peer name */
16428 static char *complete_sip_registered_peer(const char *word, int state, int flags2)
16429 {
16430        char *result = NULL;
16431        int wordlen = strlen(word);
16432        int which = 0;
16433        struct ao2_iterator i;
16434        struct sip_peer *peer;
16435        
16436        i = ao2_iterator_init(peers, 0);
16437        while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
16438           if (!strncasecmp(word, peer->name, wordlen) &&
16439          (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
16440          ++which > state && peer->expire > 0)
16441              result = ast_strdup(peer->name);
16442           if (result) {
16443              unref_peer(peer, "toss iterator peer ptr before break");
16444              break;
16445           }
16446           unref_peer(peer, "toss iterator peer ptr");
16447        }
16448        ao2_iterator_destroy(&i);
16449        return result;
16450 }
16451 
16452 /*! \brief Support routine for 'sip show history' CLI */
16453 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state)
16454 {
16455    if (pos == 3)
16456       return complete_sipch(line, word, pos, state);
16457 
16458    return NULL;
16459 }
16460 
16461 /*! \brief Support routine for 'sip show peer' CLI */
16462 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
16463 {
16464    if (pos == 3) {
16465       return complete_sip_peer(word, state, 0);
16466    }
16467 
16468    return NULL;
16469 }
16470 
16471 /*! \brief Support routine for 'sip unregister' CLI */
16472 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state)
16473 {
16474        if (pos == 2)
16475                return complete_sip_registered_peer(word, state, 0);
16476 
16477        return NULL;
16478 }
16479 
16480 /*! \brief Support routine for 'sip notify' CLI */
16481 static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
16482 {
16483    char *c = NULL;
16484 
16485    if (pos == 2) {
16486       int which = 0;
16487       char *cat = NULL;
16488       int wordlen = strlen(word);
16489 
16490       /* do completion for notify type */
16491 
16492       if (!notify_types)
16493          return NULL;
16494       
16495       while ( (cat = ast_category_browse(notify_types, cat)) ) {
16496          if (!strncasecmp(word, cat, wordlen) && ++which > state) {
16497             c = ast_strdup(cat);
16498             break;
16499          }
16500       }
16501       return c;
16502    }
16503 
16504    if (pos > 2)
16505       return complete_sip_peer(word, state, 0);
16506 
16507    return NULL;
16508 }
16509 
16510 /*! \brief Show details of one active dialog */
16511 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16512 {
16513    struct sip_pvt *cur;
16514    size_t len;
16515    int found = 0;
16516    struct ao2_iterator i;
16517 
16518    switch (cmd) {
16519    case CLI_INIT:
16520       e->command = "sip show channel";
16521       e->usage =
16522          "Usage: sip show channel <call-id>\n"
16523          "       Provides detailed status on a given SIP dialog (identified by SIP call-id).\n";
16524       return NULL;
16525    case CLI_GENERATE:
16526       return complete_sipch(a->line, a->word, a->pos, a->n);
16527    }
16528 
16529    if (a->argc != 4)
16530       return CLI_SHOWUSAGE;
16531    len = strlen(a->argv[3]);
16532    
16533    i = ao2_iterator_init(dialogs, 0);
16534    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
16535       sip_pvt_lock(cur);
16536 
16537       if (!strncasecmp(cur->callid, a->argv[3], len)) {
16538          char formatbuf[SIPBUFSIZE/2];
16539          ast_cli(a->fd, "\n");
16540          if (cur->subscribed != NONE)
16541             ast_cli(a->fd, "  * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
16542          else
16543             ast_cli(a->fd, "  * SIP Call\n");
16544          ast_cli(a->fd, "  Curr. trans. direction:  %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
16545          ast_cli(a->fd, "  Call-ID:                %s\n", cur->callid);
16546          ast_cli(a->fd, "  Owner channel ID:       %s\n", cur->owner ? cur->owner->name : "<none>");
16547          ast_cli(a->fd, "  Our Codec Capability:   %d\n", cur->capability);
16548          ast_cli(a->fd, "  Non-Codec Capability (DTMF):   %d\n", cur->noncodeccapability);
16549          ast_cli(a->fd, "  Their Codec Capability:   %d\n", cur->peercapability);
16550          ast_cli(a->fd, "  Joint Codec Capability:   %d\n", cur->jointcapability);
16551          ast_cli(a->fd, "  Format:                 %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
16552          ast_cli(a->fd, "  T.38 support            %s\n", cli_yesno(cur->udptl != NULL));
16553          ast_cli(a->fd, "  Video support           %s\n", cli_yesno(cur->vrtp != NULL));
16554          ast_cli(a->fd, "  MaxCallBR:              %d kbps\n", cur->maxcallbitrate);
16555          ast_cli(a->fd, "  Theoretical Address:    %s:%d\n", ast_inet_ntoa(cur->sa.sin_addr), ntohs(cur->sa.sin_port));
16556          ast_cli(a->fd, "  Received Address:       %s:%d\n", ast_inet_ntoa(cur->recv.sin_addr), ntohs(cur->recv.sin_port));
16557          ast_cli(a->fd, "  SIP Transfer mode:      %s\n", transfermode2str(cur->allowtransfer));
16558          ast_cli(a->fd, "  NAT Support:            %s\n", nat2str(ast_test_flag(&cur->flags[0], SIP_NAT)));
16559          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)" );
16560          ast_cli(a->fd, "  Our Tag:                %s\n", cur->tag);
16561          ast_cli(a->fd, "  Their Tag:              %s\n", cur->theirtag);
16562          ast_cli(a->fd, "  SIP User agent:         %s\n", cur->useragent);
16563          if (!ast_strlen_zero(cur->username))
16564             ast_cli(a->fd, "  Username:               %s\n", cur->username);
16565          if (!ast_strlen_zero(cur->peername))
16566             ast_cli(a->fd, "  Peername:               %s\n", cur->peername);
16567          if (!ast_strlen_zero(cur->uri))
16568             ast_cli(a->fd, "  Original uri:           %s\n", cur->uri);
16569          if (!ast_strlen_zero(cur->cid_num))
16570             ast_cli(a->fd, "  Caller-ID:              %s\n", cur->cid_num);
16571          ast_cli(a->fd, "  Need Destroy:           %s\n", cli_yesno(cur->needdestroy));
16572          ast_cli(a->fd, "  Last Message:           %s\n", cur->lastmsg);
16573          ast_cli(a->fd, "  Promiscuous Redir:      %s\n", cli_yesno(ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR)));
16574          ast_cli(a->fd, "  Route:                  %s\n", cur->route ? cur->route->hop : "N/A");
16575          ast_cli(a->fd, "  DTMF Mode:              %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
16576          ast_cli(a->fd, "  SIP Options:            ");
16577          if (cur->sipoptions) {
16578             int x;
16579             for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
16580                if (cur->sipoptions & sip_options[x].id)
16581                   ast_cli(a->fd, "%s ", sip_options[x].text);
16582             }
16583             ast_cli(a->fd, "\n");
16584          } else
16585             ast_cli(a->fd, "(none)\n");
16586 
16587          if (!cur->stimer)
16588             ast_cli(a->fd, "  Session-Timer:          Uninitiallized\n");
16589          else {
16590             ast_cli(a->fd, "  Session-Timer:          %s\n", cur->stimer->st_active ? "Active" : "Inactive");
16591             if (cur->stimer->st_active == TRUE) {
16592                ast_cli(a->fd, "  S-Timer Interval:       %d\n", cur->stimer->st_interval);
16593                ast_cli(a->fd, "  S-Timer Refresher:      %s\n", strefresher2str(cur->stimer->st_ref));
16594                ast_cli(a->fd, "  S-Timer Expirys:        %d\n", cur->stimer->st_expirys);
16595                ast_cli(a->fd, "  S-Timer Sched Id:       %d\n", cur->stimer->st_schedid);
16596                ast_cli(a->fd, "  S-Timer Peer Sts:       %s\n", cur->stimer->st_active_peer_ua ? "Active" : "Inactive");
16597                ast_cli(a->fd, "  S-Timer Cached Min-SE:  %d\n", cur->stimer->st_cached_min_se);
16598                ast_cli(a->fd, "  S-Timer Cached SE:      %d\n", cur->stimer->st_cached_max_se);
16599                ast_cli(a->fd, "  S-Timer Cached Ref:     %s\n", strefresher2str(cur->stimer->st_cached_ref));
16600                ast_cli(a->fd, "  S-Timer Cached Mode:    %s\n", stmode2str(cur->stimer->st_cached_mode));
16601             }
16602          }
16603 
16604          ast_cli(a->fd, "\n\n");
16605 
16606          found++;
16607       }
16608 
16609       sip_pvt_unlock(cur);
16610 
16611       ao2_t_ref(cur, -1, "toss dialog ptr set by iterator_next");
16612    }
16613    ao2_iterator_destroy(&i);
16614 
16615    if (!found) 
16616       ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
16617 
16618    return CLI_SUCCESS;
16619 }
16620 
16621 /*! \brief Show history details of one dialog */
16622 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16623 {
16624    struct sip_pvt *cur;
16625    size_t len;
16626    int found = 0;
16627    struct ao2_iterator i;
16628 
16629    switch (cmd) {
16630    case CLI_INIT:
16631       e->command = "sip show history";
16632       e->usage =
16633          "Usage: sip show history <call-id>\n"
16634          "       Provides detailed dialog history on a given SIP call (specified by call-id).\n";
16635       return NULL;
16636    case CLI_GENERATE:
16637       return complete_sip_show_history(a->line, a->word, a->pos, a->n);
16638    }
16639 
16640    if (a->argc != 4)
16641       return CLI_SHOWUSAGE;
16642 
16643    if (!recordhistory)
16644       ast_cli(a->fd, "\n***Note: History recording is currently DISABLED.  Use 'sip set history on' to ENABLE.\n");
16645 
16646    len = strlen(a->argv[3]);
16647 
16648    i = ao2_iterator_init(dialogs, 0);
16649    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
16650       sip_pvt_lock(cur);
16651       if (!strncasecmp(cur->callid, a->argv[3], len)) {
16652          struct sip_history *hist;
16653          int x = 0;
16654 
16655          ast_cli(a->fd, "\n");
16656          if (cur->subscribed != NONE)
16657             ast_cli(a->fd, "  * Subscription\n");
16658          else
16659             ast_cli(a->fd, "  * SIP Call\n");
16660          if (cur->history)
16661             AST_LIST_TRAVERSE(cur->history, hist, list)
16662                ast_cli(a->fd, "%d. %s\n", ++x, hist->event);
16663          if (x == 0)
16664             ast_cli(a->fd, "Call '%s' has no history\n", cur->callid);
16665          found++;
16666       }
16667       sip_pvt_unlock(cur);
16668       ao2_t_ref(cur, -1, "toss dialog ptr from iterator_next");
16669    }
16670    ao2_iterator_destroy(&i);
16671 
16672    if (!found) 
16673       ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
16674 
16675    return CLI_SUCCESS;
16676 }
16677 
16678 /*! \brief Dump SIP history to debug log file at end of lifespan for SIP dialog */
16679 static void sip_dump_history(struct sip_pvt *dialog)
16680 {
16681    int x = 0;
16682    struct sip_history *hist;
16683    static int errmsg = 0;
16684 
16685    if (!dialog)
16686       return;
16687 
16688    if (!option_debug && !sipdebug) {
16689       if (!errmsg) {
16690          ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
16691          errmsg = 1;
16692       }
16693       return;
16694    }
16695 
16696    ast_debug(1, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
16697    if (dialog->subscribed)
16698       ast_debug(1, "  * Subscription\n");
16699    else
16700       ast_debug(1, "  * SIP Call\n");
16701    if (dialog->history)
16702       AST_LIST_TRAVERSE(dialog->history, hist, list)
16703          ast_debug(1, "  %-3.3d. %s\n", ++x, hist->event);
16704    if (!x)
16705       ast_debug(1, "Call '%s' has no history\n", dialog->callid);
16706    ast_debug(1, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
16707 }
16708 
16709 
16710 /*! \brief  Receive SIP INFO Message */
16711 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
16712 {
16713    char buf[1024];
16714    unsigned int event;
16715    const char *c = get_header(req, "Content-Type");
16716 
16717    /* Need to check the media/type */
16718    if (!strcasecmp(c, "application/dtmf-relay") ||
16719        !strcasecmp(c, "application/vnd.nortelnetworks.digits")) {
16720       unsigned int duration = 0;
16721 
16722       if (!p->owner) {  /* not a PBX call */
16723          transmit_response(p, "481 Call leg/transaction does not exist", req);
16724          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16725          return;
16726       }
16727 
16728       /* Try getting the "signal=" part */
16729       if (ast_strlen_zero(c = get_body(req, "Signal", '=')) && ast_strlen_zero(c = get_body(req, "d", '='))) {
16730          ast_log(LOG_WARNING, "Unable to retrieve DTMF signal from INFO message from %s\n", p->callid);
16731          transmit_response(p, "200 OK", req); /* Should return error */
16732          return;
16733       } else {
16734          ast_copy_string(buf, c, sizeof(buf));
16735       }
16736 
16737       if (!ast_strlen_zero((c = get_body(req, "Duration", '='))))
16738          duration = atoi(c);
16739       if (!duration)
16740          duration = 100; /* 100 ms */
16741 
16742 
16743       if (ast_strlen_zero(buf)) {
16744          transmit_response(p, "200 OK", req);
16745          return;
16746       }
16747 
16748       if (buf[0] == '*')
16749          event = 10;
16750       else if (buf[0] == '#')
16751          event = 11;
16752       else if ((buf[0] >= 'A') && (buf[0] <= 'D'))
16753          event = 12 + buf[0] - 'A';
16754       else if (buf[0] == '!')
16755          event = 16;
16756       else
16757          event = atoi(buf);
16758       if (event == 16) {
16759          /* send a FLASH event */
16760          struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
16761          ast_queue_frame(p->owner, &f);
16762          if (sipdebug)
16763             ast_verbose("* DTMF-relay event received: FLASH\n");
16764       } else {
16765          /* send a DTMF event */
16766          struct ast_frame f = { AST_FRAME_DTMF, };
16767          if (event < 10) {
16768             f.subclass = '0' + event;
16769          } else if (event < 11) {
16770             f.subclass = '*';
16771          } else if (event < 12) {
16772             f.subclass = '#';
16773          } else if (event < 16) {
16774             f.subclass = 'A' + (event - 12);
16775          }
16776          f.len = duration;
16777          ast_queue_frame(p->owner, &f);
16778          if (sipdebug)
16779             ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
16780       }
16781       transmit_response(p, "200 OK", req);
16782       return;
16783    } else if (!strcasecmp(c, "application/dtmf")) {
16784       /*! \todo Note: Doesn't read the duration of the DTMF. Should be fixed. */
16785       unsigned int duration = 0;
16786 
16787       if (!p->owner) {  /* not a PBX call */
16788          transmit_response(p, "481 Call leg/transaction does not exist", req);
16789          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16790          return;
16791       }
16792 
16793       get_msg_text(buf, sizeof(buf), req, TRUE);
16794       duration = 100; /* 100 ms */
16795 
16796       if (ast_strlen_zero(buf)) {
16797          transmit_response(p, "200 OK", req);
16798          return;
16799       }
16800       event = atoi(buf);
16801       if (event == 16) {
16802          /* send a FLASH event */
16803          struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
16804          ast_queue_frame(p->owner, &f);
16805          if (sipdebug)
16806             ast_verbose("* DTMF-relay event received: FLASH\n");
16807       } else {
16808          /* send a DTMF event */
16809          struct ast_frame f = { AST_FRAME_DTMF, };
16810          if (event < 10) {
16811             f.subclass = '0' + event;
16812          } else if (event < 11) {
16813             f.subclass = '*';
16814          } else if (event < 12) {
16815             f.subclass = '#';
16816          } else if (event < 16) {
16817             f.subclass = 'A' + (event - 12);
16818          }
16819          f.len = duration;
16820          ast_queue_frame(p->owner, &f);
16821          if (sipdebug)
16822             ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
16823       }
16824       transmit_response(p, "200 OK", req);
16825       return;
16826 
16827    } else if (!strcasecmp(c, "application/media_control+xml")) {
16828       /* Eh, we'll just assume it's a fast picture update for now */
16829       if (p->owner)
16830          ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
16831       transmit_response(p, "200 OK", req);
16832       return;
16833    } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
16834       /* Client code (from SNOM phone) */
16835       if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
16836          if (p->owner && p->owner->cdr)
16837             ast_cdr_setuserfield(p->owner, c);
16838          if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
16839             ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
16840          transmit_response(p, "200 OK", req);
16841       } else {
16842          transmit_response(p, "403 Forbidden", req);
16843       }
16844       return;
16845    } else if (!ast_strlen_zero(c = get_header(req, "Record"))) {
16846       /* INFO messages generated by some phones to start/stop recording
16847          on phone calls. 
16848          OEJ: I think this should be something that is enabled/disabled
16849          per device. I don't want incoming callers to record calls in my
16850          pbx.
16851       */
16852       /* first, get the feature string, if it exists */
16853       struct ast_call_feature *feat;
16854       int j;
16855       struct ast_frame f = { AST_FRAME_DTMF, };
16856 
16857       ast_rdlock_call_features();
16858       feat = ast_find_call_feature("automon");
16859       if (!feat || ast_strlen_zero(feat->exten)) {
16860          ast_log(LOG_WARNING, "Recording requested, but no One Touch Monitor registered. (See features.conf)\n");
16861          /* 403 means that we don't support this feature, so don't request it again */
16862          transmit_response(p, "403 Forbidden", req);
16863          ast_unlock_call_features();
16864          return;
16865       } 
16866       /* Send the feature code to the PBX as DTMF, just like the handset had sent it */
16867       f.len = 100;
16868       for (j=0; j < strlen(feat->exten); j++) {
16869          f.subclass = feat->exten[j];
16870          ast_queue_frame(p->owner, &f);
16871          if (sipdebug)
16872             ast_verbose("* DTMF-relay event faked: %c\n", f.subclass);
16873       }
16874       ast_unlock_call_features();
16875 
16876       ast_debug(1, "Got a Request to Record the channel, state %s\n", c);
16877       transmit_response(p, "200 OK", req);
16878       return;
16879    } else if (ast_strlen_zero(c = get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
16880       /* This is probably just a packet making sure the signalling is still up, just send back a 200 OK */
16881       transmit_response(p, "200 OK", req);
16882       return;
16883    }
16884 
16885    /* Other type of INFO message, not really understood by Asterisk */
16886    /* if (get_msg_text(buf, sizeof(buf), req)) { */
16887 
16888    ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
16889    transmit_response(p, "415 Unsupported media type", req);
16890    return;
16891 }
16892 
16893 /*! \brief Enable SIP Debugging for a single IP */
16894 static char *sip_do_debug_ip(int fd, char *arg)
16895 {
16896    struct hostent *hp;
16897    struct ast_hostent ahp;
16898    int port = 0;
16899    char *p;
16900 
16901    p = arg;
16902    strsep(&p, ":");
16903    if (p)
16904       port = atoi(p);
16905    hp = ast_gethostbyname(arg, &ahp);
16906    if (hp == NULL)
16907       return CLI_SHOWUSAGE;
16908 
16909    debugaddr.sin_family = AF_INET;
16910    memcpy(&debugaddr.sin_addr, hp->h_addr, sizeof(debugaddr.sin_addr));
16911    debugaddr.sin_port = htons(port);
16912    if (port == 0)
16913       ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_inet_ntoa(debugaddr.sin_addr));
16914    else
16915       ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), port);
16916 
16917    sipdebug |= sip_debug_console;
16918 
16919    return CLI_SUCCESS;
16920 }
16921 
16922 /*! \brief  Turn on SIP debugging for a given peer */
16923 static char *sip_do_debug_peer(int fd, char *arg)
16924 {
16925    struct sip_peer *peer = find_peer(arg, NULL, TRUE, FINDPEERS, FALSE, 0);
16926    if (!peer)
16927       ast_cli(fd, "No such peer '%s'\n", arg);
16928    else if (peer->addr.sin_addr.s_addr == 0)
16929       ast_cli(fd, "Unable to get IP address of peer '%s'\n", arg);
16930    else {
16931       debugaddr.sin_family = AF_INET;
16932       debugaddr.sin_addr = peer->addr.sin_addr;
16933       debugaddr.sin_port = peer->addr.sin_port;
16934       ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n",
16935          ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
16936       sipdebug |= sip_debug_console;
16937    }
16938    if (peer)
16939       unref_peer(peer, "sip_do_debug_peer: unref_peer, from find_peer call");
16940    return CLI_SUCCESS;
16941 }
16942 
16943 /*! \brief Turn on SIP debugging (CLI command) */
16944 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16945 {
16946    int oldsipdebug = sipdebug & sip_debug_console;
16947    char *what;
16948 
16949    if (cmd == CLI_INIT) {
16950       e->command = "sip set debug {on|off|ip|peer}";
16951       e->usage =
16952          "Usage: sip set debug {off|on|ip addr[:port]|peer peername}\n"
16953          "       Globally disables dumping of SIP packets,\n"
16954          "       or enables it either globally or for a (single)\n"
16955          "       IP address or registered peer.\n";
16956       return NULL;
16957    } else if (cmd == CLI_GENERATE) {
16958       if (a->pos == 4 && !strcasecmp(a->argv[3], "peer")) 
16959          return complete_sip_peer(a->word, a->n, 0);
16960       return NULL;
16961         }
16962 
16963    what = a->argv[e->args-1];      /* guaranteed to exist */
16964    if (a->argc == e->args) {       /* on/off */
16965       if (!strcasecmp(what, "on")) {
16966          sipdebug |= sip_debug_console;
16967          sipdebug_text = 1;   /*! \note this can be a special debug command - "sip debug text" or something */
16968          memset(&debugaddr, 0, sizeof(debugaddr));
16969          ast_cli(a->fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
16970          return CLI_SUCCESS;
16971       } else if (!strcasecmp(what, "off")) {
16972          sipdebug &= ~sip_debug_console;
16973          sipdebug_text = 0;
16974          ast_cli(a->fd, "SIP Debugging Disabled\n");
16975          return CLI_SUCCESS;
16976       }
16977    } else if (a->argc == e->args +1) {/* ip/peer */
16978       if (!strcasecmp(what, "ip"))
16979          return sip_do_debug_ip(a->fd, a->argv[e->args]);
16980       else if (!strcasecmp(what, "peer"))
16981          return sip_do_debug_peer(a->fd, a->argv[e->args]);
16982    }
16983    return CLI_SHOWUSAGE;   /* default, failure */
16984 }
16985 
16986 /*! \brief Cli command to send SIP notify to peer */
16987 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16988 {
16989    struct ast_variable *varlist;
16990    int i;
16991 
16992    switch (cmd) {
16993    case CLI_INIT:
16994       e->command = "sip notify";
16995       e->usage =
16996          "Usage: sip notify <type> <peer> [<peer>...]\n"
16997          "       Send a NOTIFY message to a SIP peer or peers\n"
16998          "       Message types are defined in sip_notify.conf\n";
16999       return NULL;
17000    case CLI_GENERATE:
17001       return complete_sipnotify(a->line, a->word, a->pos, a->n);
17002    }
17003 
17004    if (a->argc < 4)
17005       return CLI_SHOWUSAGE;
17006 
17007    if (!notify_types) {
17008       ast_cli(a->fd, "No %s file found, or no types listed there\n", notify_config);
17009       return CLI_FAILURE;
17010    }
17011 
17012    varlist = ast_variable_browse(notify_types, a->argv[2]);
17013 
17014    if (!varlist) {
17015       ast_cli(a->fd, "Unable to find notify type '%s'\n", a->argv[2]);
17016       return CLI_FAILURE;
17017    }
17018 
17019    for (i = 3; i < a->argc; i++) {
17020       struct sip_pvt *p;
17021 
17022       if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
17023          ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
17024          return CLI_FAILURE;
17025       }
17026 
17027       if (create_addr(p, a->argv[i], NULL, 1)) {
17028          /* Maybe they're not registered, etc. */
17029          dialog_unlink_all(p, TRUE, TRUE);
17030          dialog_unref(p, "unref dialog inside for loop" );
17031          /* sip_destroy(p); */
17032          ast_cli(a->fd, "Could not create address for '%s'\n", a->argv[i]);
17033          continue;
17034       }
17035 
17036       /* Notify is outgoing call */
17037       ast_set_flag(&p->flags[0], SIP_OUTGOING);
17038 
17039       /* Recalculate our side, and recalculate Call ID */
17040       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
17041       build_via(p);
17042       ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
17043       build_callid_pvt(p);
17044       ao2_t_link(dialogs, p, "Linking in new name");
17045       ast_cli(a->fd, "Sending NOTIFY of type '%s' to '%s'\n", a->argv[2], a->argv[i]);
17046       dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
17047       sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
17048       transmit_notify_custom(p, varlist);
17049    }
17050 
17051    return CLI_SUCCESS;
17052 }
17053 
17054 /*! \brief Enable/Disable SIP History logging (CLI) */
17055 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17056 {
17057    switch (cmd) {
17058    case CLI_INIT:
17059       e->command = "sip set history {on|off}";
17060       e->usage =
17061          "Usage: sip set history {on|off}\n"
17062          "       Enables/Disables recording of SIP dialog history for debugging purposes.\n"
17063          "       Use 'sip show history' to view the history of a call number.\n";
17064       return NULL;
17065    case CLI_GENERATE:
17066       return NULL;
17067    }
17068 
17069    if (a->argc != e->args)
17070       return CLI_SHOWUSAGE;
17071 
17072    if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
17073       recordhistory = TRUE;
17074       ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
17075    } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
17076       recordhistory = FALSE;
17077       ast_cli(a->fd, "SIP History Recording Disabled\n");
17078    } else {
17079       return CLI_SHOWUSAGE;
17080    }
17081    return CLI_SUCCESS;
17082 }
17083 
17084 /*! \brief Authenticate for outbound registration */
17085 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code)
17086 {
17087    char *header, *respheader;
17088    char digest[1024];
17089 
17090    p->authtries++;
17091    auth_headers(code, &header, &respheader);
17092    memset(digest, 0, sizeof(digest));
17093    if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
17094       /* There's nothing to use for authentication */
17095       /* No digest challenge in request */
17096       if (sip_debug_test_pvt(p) && p->registry)
17097          ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
17098          /* No old challenge */
17099       return -1;
17100    }
17101    if (p->do_history)
17102       append_history(p, "RegistryAuth", "Try: %d", p->authtries);
17103    if (sip_debug_test_pvt(p) && p->registry)
17104       ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
17105    return transmit_register(p->registry, SIP_REGISTER, digest, respheader); 
17106 }
17107 
17108 /*! \brief Add authentication on outbound SIP packet */
17109 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code, int sipmethod, int init)
17110 {
17111    char *header, *respheader;
17112    char digest[1024];
17113 
17114    if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
17115       return -2;
17116 
17117    p->authtries++;
17118    auth_headers(code, &header, &respheader);
17119    ast_debug(2, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
17120    memset(digest, 0, sizeof(digest));
17121    if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
17122       /* No way to authenticate */
17123       return -1;
17124    }
17125    /* Now we have a reply digest */
17126    p->options->auth = digest;
17127    p->options->authheader = respheader;
17128    return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init); 
17129 }
17130 
17131 /*! \brief  reply to authentication for outbound registrations
17132 \return  Returns -1 if we have no auth 
17133 \note This is used for register= servers in sip.conf, SIP proxies we register
17134    with  for receiving calls from.  */
17135 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod,  char *digest, int digest_len)
17136 {
17137    char tmp[512];
17138    char *c;
17139    char oldnonce[256];
17140 
17141    /* table of recognised keywords, and places where they should be copied */
17142    const struct x {
17143       const char *key;
17144       const ast_string_field *field;
17145    } *i, keys[] = {
17146       { "realm=", &p->realm },
17147       { "nonce=", &p->nonce },
17148       { "opaque=", &p->opaque },
17149       { "qop=", &p->qop },
17150       { "domain=", &p->domain },
17151       { NULL, 0 },
17152    };
17153 
17154    ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
17155    if (ast_strlen_zero(tmp)) 
17156       return -1;
17157    if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
17158       ast_log(LOG_WARNING, "missing Digest.\n");
17159       return -1;
17160    }
17161    c = tmp + strlen("Digest ");
17162    ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
17163    while (c && *(c = ast_skip_blanks(c))) {  /* lookup for keys */
17164       for (i = keys; i->key != NULL; i++) {
17165          char *src, *separator;
17166          if (strncasecmp(c, i->key, strlen(i->key)) != 0)
17167             continue;
17168          /* Found. Skip keyword, take text in quotes or up to the separator. */
17169          c += strlen(i->key);
17170          if (*c == '"') {
17171             src = ++c;
17172             separator = "\"";
17173          } else {
17174             src = c;
17175             separator = ",";
17176          }
17177          strsep(&c, separator); /* clear separator and move ptr */
17178          ast_string_field_ptr_set(p, i->field, src);
17179          break;
17180       }
17181       if (i->key == NULL) /* not found, try ',' */
17182          strsep(&c, ",");
17183    }
17184    /* Reset nonce count */
17185    if (strcmp(p->nonce, oldnonce)) 
17186       p->noncecount = 0;
17187 
17188    /* Save auth data for following registrations */
17189    if (p->registry) {
17190       struct sip_registry *r = p->registry;
17191 
17192       if (strcmp(r->nonce, p->nonce)) {
17193          ast_string_field_set(r, realm, p->realm);
17194          ast_string_field_set(r, nonce, p->nonce);
17195          ast_string_field_set(r, domain, p->domain);
17196          ast_string_field_set(r, opaque, p->opaque);
17197          ast_string_field_set(r, qop, p->qop);
17198          r->noncecount = 0;
17199       }
17200    }
17201    return build_reply_digest(p, sipmethod, digest, digest_len); 
17202 }
17203 
17204 /*! \brief  Build reply digest 
17205 \return  Returns -1 if we have no auth 
17206 \note Build digest challenge for authentication of registrations and calls
17207    Also used for authentication of BYE 
17208 */
17209 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
17210 {
17211    char a1[256];
17212    char a2[256];
17213    char a1_hash[256];
17214    char a2_hash[256];
17215    char resp[256];
17216    char resp_hash[256];
17217    char uri[256];
17218    char opaque[256] = "";
17219    char cnonce[80];
17220    const char *username;
17221    const char *secret;
17222    const char *md5secret;
17223    struct sip_auth *auth = NULL; /* Realm authentication */
17224 
17225    if (!ast_strlen_zero(p->domain))
17226       ast_copy_string(uri, p->domain, sizeof(uri));
17227    else if (!ast_strlen_zero(p->uri))
17228       ast_copy_string(uri, p->uri, sizeof(uri));
17229    else
17230       snprintf(uri, sizeof(uri), "sip:%s@%s", p->username, ast_inet_ntoa(p->sa.sin_addr));
17231 
17232    snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
17233 
17234    /* Check if we have separate auth credentials */
17235    if(!(auth = find_realm_authentication(p->peerauth, p->realm))) /* Start with peer list */
17236       auth = find_realm_authentication(authl, p->realm); /* If not, global list */
17237 
17238    if (auth) {
17239       ast_debug(3, "use realm [%s] from peer [%s][%s]\n", auth->username, p->peername, p->username);
17240       username = auth->username;
17241       secret = auth->secret;
17242       md5secret = auth->md5secret;
17243       if (sipdebug)
17244          ast_debug(1, "Using realm %s authentication for call %s\n", p->realm, p->callid);
17245    } else {
17246       /* No authentication, use peer or register= config */
17247       username = p->authname;
17248       secret =  p->peersecret;
17249       md5secret = p->peermd5secret;
17250    }
17251    if (ast_strlen_zero(username))   /* We have no authentication */
17252       return -1;
17253 
17254    /* Calculate SIP digest response */
17255    snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
17256    snprintf(a2, sizeof(a2), "%s:%s", sip_methods[method].text, uri);
17257    if (!ast_strlen_zero(md5secret))
17258       ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
17259    else
17260       ast_md5_hash(a1_hash, a1);
17261    ast_md5_hash(a2_hash, a2);
17262 
17263    p->noncecount++;
17264    if (!ast_strlen_zero(p->qop))
17265       snprintf(resp, sizeof(resp), "%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
17266    else
17267       snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, p->nonce, a2_hash);
17268    ast_md5_hash(resp_hash, resp);
17269 
17270    /* only include the opaque string if it's set */
17271    if (!ast_strlen_zero(p->opaque)) {
17272      snprintf(opaque, sizeof(opaque), ", opaque=\"%s\"", p->opaque);
17273    }
17274 
17275    /* XXX We hard code our qop to "auth" for now.  XXX */
17276    if (!ast_strlen_zero(p->qop))
17277       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);
17278    else
17279       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);
17280 
17281    append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
17282 
17283    return 0;
17284 }
17285    
17286 /*! \brief Read SIP header (dialplan function) */
17287 static int func_header_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len) 
17288 {
17289    struct sip_pvt *p;
17290    const char *content = NULL;
17291    AST_DECLARE_APP_ARGS(args,
17292       AST_APP_ARG(header);
17293       AST_APP_ARG(number);
17294    );
17295    int i, number, start = 0;
17296 
17297    if (ast_strlen_zero(data)) {
17298       ast_log(LOG_WARNING, "This function requires a header name.\n");
17299       return -1;
17300    }
17301 
17302    ast_channel_lock(chan);
17303    if (!IS_SIP_TECH(chan->tech)) {
17304       ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
17305       ast_channel_unlock(chan);
17306       return -1;
17307    }
17308 
17309    AST_STANDARD_APP_ARGS(args, data);
17310    if (!args.number) {
17311       number = 1;
17312    } else {
17313       sscanf(args.number, "%30d", &number);
17314       if (number < 1)
17315          number = 1;
17316    }
17317 
17318    p = chan->tech_pvt;
17319 
17320    /* If there is no private structure, this channel is no longer alive */
17321    if (!p) {
17322       ast_channel_unlock(chan);
17323       return -1;
17324    }
17325 
17326    for (i = 0; i < number; i++)
17327       content = __get_header(&p->initreq, args.header, &start);
17328 
17329    if (ast_strlen_zero(content)) {
17330       ast_channel_unlock(chan);
17331       return -1;
17332    }
17333 
17334    ast_copy_string(buf, content, len);
17335    ast_channel_unlock(chan);
17336 
17337    return 0;
17338 }
17339 
17340 static struct ast_custom_function sip_header_function = {
17341    .name = "SIP_HEADER",
17342    .read = func_header_read,
17343 };
17344 
17345 /*! \brief  Dial plan function to check if domain is local */
17346 static int func_check_sipdomain(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
17347 {
17348    if (ast_strlen_zero(data)) {
17349       ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
17350       return -1;
17351    }
17352    if (check_sip_domain(data, NULL, 0))
17353       ast_copy_string(buf, data, len);
17354    else
17355       buf[0] = '\0';
17356    return 0;
17357 }
17358 
17359 static struct ast_custom_function checksipdomain_function = {
17360    .name = "CHECKSIPDOMAIN",
17361    .read = func_check_sipdomain,
17362 };
17363 
17364 /*! \brief  ${SIPPEER()} Dialplan function - reads peer data */
17365 static int function_sippeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
17366 {
17367    struct sip_peer *peer;
17368    char *colname;
17369 
17370    if ((colname = strchr(data, ':'))) {   /*! \todo Will be deprecated after 1.4 */
17371       static int deprecation_warning = 0;
17372       *colname++ = '\0';
17373       if (deprecation_warning++ % 10 == 0)
17374          ast_log(LOG_WARNING, "SIPPEER(): usage of ':' to separate arguments is deprecated.  Please use ',' instead.\n");
17375    } else if ((colname = strchr(data, ',')))
17376       *colname++ = '\0';
17377    else
17378       colname = "ip";
17379 
17380    if (!(peer = find_peer(data, NULL, TRUE, FINDPEERS, FALSE, 0)))
17381       return -1;
17382 
17383    if (!strcasecmp(colname, "ip")) {
17384       ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len);
17385    } else  if (!strcasecmp(colname, "port")) {
17386       snprintf(buf, len, "%d", ntohs(peer->addr.sin_port));
17387    } else  if (!strcasecmp(colname, "status")) {
17388       peer_status(peer, buf, len);
17389    } else  if (!strcasecmp(colname, "language")) {
17390       ast_copy_string(buf, peer->language, len);
17391    } else  if (!strcasecmp(colname, "regexten")) {
17392       ast_copy_string(buf, peer->regexten, len);
17393    } else  if (!strcasecmp(colname, "limit")) {
17394       snprintf(buf, len, "%d", peer->call_limit);
17395    } else  if (!strcasecmp(colname, "busylevel")) {
17396       snprintf(buf, len, "%d", peer->busy_level);
17397    } else  if (!strcasecmp(colname, "curcalls")) {
17398       snprintf(buf, len, "%d", peer->inUse);
17399    } else  if (!strcasecmp(colname, "accountcode")) {
17400       ast_copy_string(buf, peer->accountcode, len);
17401    } else  if (!strcasecmp(colname, "callgroup")) {
17402       ast_print_group(buf, len, peer->callgroup);
17403    } else  if (!strcasecmp(colname, "pickupgroup")) {
17404       ast_print_group(buf, len, peer->pickupgroup);
17405    } else  if (!strcasecmp(colname, "useragent")) {
17406       ast_copy_string(buf, peer->useragent, len);
17407    } else  if (!strcasecmp(colname, "mailbox")) {
17408       struct ast_str *mailbox_str = ast_str_alloca(512);
17409       peer_mailboxes_to_str(&mailbox_str, peer);
17410       ast_copy_string(buf, mailbox_str->str, len);
17411    } else  if (!strcasecmp(colname, "context")) {
17412       ast_copy_string(buf, peer->context, len);
17413    } else  if (!strcasecmp(colname, "expire")) {
17414       snprintf(buf, len, "%d", peer->expire);
17415    } else  if (!strcasecmp(colname, "dynamic")) {
17416       ast_copy_string(buf, peer->host_dynamic ? "yes" : "no", len);
17417    } else  if (!strcasecmp(colname, "callerid_name")) {
17418       ast_copy_string(buf, peer->cid_name, len);
17419    } else  if (!strcasecmp(colname, "callerid_num")) {
17420       ast_copy_string(buf, peer->cid_num, len);
17421    } else  if (!strcasecmp(colname, "codecs")) {
17422       ast_getformatname_multiple(buf, len -1, peer->capability);
17423    } else  if (!strncasecmp(colname, "chanvar[", 8)) {
17424       char *chanvar=colname + 8;
17425       struct ast_variable *v;
17426    
17427       chanvar = strsep(&chanvar, "]");
17428       for (v = peer->chanvars ; v ; v = v->next) {
17429          if (!strcasecmp(v->name, chanvar)) {
17430             ast_copy_string(buf, v->value, len);
17431          }
17432       }
17433    } else  if (!strncasecmp(colname, "codec[", 6)) {
17434       char *codecnum;
17435       int codec = 0;
17436       
17437       codecnum = colname + 6; /* move past the '[' */
17438       codecnum = strsep(&codecnum, "]"); /* trim trailing ']' if any */
17439       if((codec = ast_codec_pref_index(&peer->prefs, atoi(codecnum)))) {
17440          ast_copy_string(buf, ast_getformatname(codec), len);
17441       } else {
17442          buf[0] = '\0';
17443       }
17444    } else {
17445       buf[0] = '\0';
17446    }
17447 
17448    unref_peer(peer, "unref_peer from function_sippeer, just before return");
17449 
17450    return 0;
17451 }
17452 
17453 /*! \brief Structure to declare a dialplan function: SIPPEER */
17454 static struct ast_custom_function sippeer_function = {
17455    .name = "SIPPEER",
17456    .read = function_sippeer,
17457 };
17458 
17459 /*! \brief ${SIPCHANINFO()} Dialplan function - reads sip channel data */
17460 static int function_sipchaninfo_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
17461 {
17462    struct sip_pvt *p;
17463    static int deprecated = 0;
17464 
17465    *buf = 0;
17466    
17467    if (!data) {
17468       ast_log(LOG_WARNING, "This function requires a parameter name.\n");
17469       return -1;
17470    }
17471 
17472    ast_channel_lock(chan);
17473    if (!IS_SIP_TECH(chan->tech)) {
17474       ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
17475       ast_channel_unlock(chan);
17476       return -1;
17477    }
17478 
17479    if (deprecated++ % 20 == 0) {
17480       /* Deprecated in 1.6.1 */
17481       ast_log(LOG_WARNING, "SIPCHANINFO() is deprecated.  Please transition to using CHANNEL().\n");
17482    }
17483 
17484    p = chan->tech_pvt;
17485 
17486    /* If there is no private structure, this channel is no longer alive */
17487    if (!p) {
17488       ast_channel_unlock(chan);
17489       return -1;
17490    }
17491 
17492    if (!strcasecmp(data, "peerip")) {
17493       ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", len);
17494    } else  if (!strcasecmp(data, "recvip")) {
17495       ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", len);
17496    } else  if (!strcasecmp(data, "from")) {
17497       ast_copy_string(buf, p->from, len);
17498    } else  if (!strcasecmp(data, "uri")) {
17499       ast_copy_string(buf, p->uri, len);
17500    } else  if (!strcasecmp(data, "useragent")) {
17501       ast_copy_string(buf, p->useragent, len);
17502    } else  if (!strcasecmp(data, "peername")) {
17503       ast_copy_string(buf, p->peername, len);
17504    } else if (!strcasecmp(data, "t38passthrough")) {
17505       if (p->t38.state == T38_DISABLED) {
17506          ast_copy_string(buf, "0", len);
17507       } else { /* T38 is offered or enabled in this call */
17508          ast_copy_string(buf, "1", len);
17509       }
17510    } else {
17511       ast_channel_unlock(chan);
17512       return -1;
17513    }
17514    ast_channel_unlock(chan);
17515 
17516    return 0;
17517 }
17518 
17519 /*! \brief Structure to declare a dialplan function: SIPCHANINFO */
17520 static struct ast_custom_function sipchaninfo_function = {
17521    .name = "SIPCHANINFO",
17522    .read = function_sipchaninfo_read,
17523 };
17524 
17525 /*! \brief Parse 302 Moved temporalily response 
17526    \todo XXX Doesn't redirect over TLS on sips: uri's.
17527       If we get a redirect to a SIPS: uri, this needs to be going back to the
17528       dialplan (this is a request for a secure signalling path).
17529       Note that transport=tls is deprecated, but we need to support it on incoming requests.
17530 */
17531 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req)
17532 {
17533    char tmp[SIPBUFSIZE];
17534    char *s, *e, *t, *trans;
17535    char *domain;
17536    enum sip_transport transport = SIP_TRANSPORT_UDP;
17537 
17538    ast_copy_string(tmp, get_header(req, "Contact"), sizeof(tmp));
17539    if ((t = strchr(tmp, ',')))
17540       *t = '\0';
17541 
17542    s = get_in_brackets(tmp);
17543    if ((trans = strcasestr(s, ";transport="))) do {
17544       trans += 11;
17545 
17546       if ((e = strchr(trans, ';')))
17547          *e = '\0';
17548 
17549       if (!strncasecmp(trans, "tcp", 3))
17550          transport = SIP_TRANSPORT_TCP;
17551       else if (!strncasecmp(trans, "tls", 3))
17552          transport = SIP_TRANSPORT_TLS;
17553       else {
17554          if (strncasecmp(trans, "udp", 3))
17555             ast_debug(1, "received contact with an invalid transport, '%s'\n", s);
17556          /* This will assume UDP for all unknown transports */
17557          transport = SIP_TRANSPORT_UDP;
17558       }
17559    } while(0);
17560    s = remove_uri_parameters(s);
17561 
17562    if (p->socket.tcptls_session) {
17563       ao2_ref(p->socket.tcptls_session, -1);
17564       p->socket.tcptls_session = NULL;
17565    }
17566 
17567    set_socket_transport(&p->socket, transport);
17568 
17569    if (ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
17570       char *host = NULL;
17571       if (!strncasecmp(s, "sip:", 4))
17572          s += 4;
17573       else if (!strncasecmp(s, "sips:", 5))
17574          s += 5;
17575       e = strchr(s, '/');
17576       if (e)
17577          *e = '\0';
17578       if ((host = strchr(s, '@'))) {
17579          *host++ = '\0';
17580          ast_debug(2, "Found promiscuous redirection to 'SIP/%s::::%s@%s'\n", s, get_transport(transport), host);
17581          if (p->owner)
17582             ast_string_field_build(p->owner, call_forward, "SIP/%s::::%s@%s", s, get_transport(transport), host);
17583       } else {
17584          ast_debug(2, "Found promiscuous redirection to 'SIP/::::%s@%s'\n", get_transport(transport), s);
17585          if (p->owner)
17586             ast_string_field_build(p->owner, call_forward, "SIP/::::%s@%s", get_transport(transport), s);
17587       }
17588    } else {
17589       e = strchr(tmp, '@');
17590       if (e) {
17591          *e++ = '\0';
17592          domain = e;
17593       } else {
17594          /* No username part */
17595          domain = tmp;
17596       }
17597       e = strchr(tmp, '/');   /* WHEN do we hae a forward slash in the URI? */
17598       if (e)
17599          *e = '\0';
17600 
17601       if (!strncasecmp(s, "sip:", 4))
17602          s += 4;
17603       else if (!strncasecmp(s, "sips:", 5))
17604          s += 5;
17605       e = strchr(s, ';');  /* And username ; parameters? */
17606       if (e)
17607          *e = '\0';  
17608       ast_uri_decode(s);
17609       ast_debug(2, "Received 302 Redirect to extension '%s' (domain %s)\n", s, domain);
17610       if (p->owner) {
17611          pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
17612          ast_string_field_set(p->owner, call_forward, s);
17613       }
17614    }
17615 }
17616 
17617 /*! \brief Check pending actions on SIP call */
17618 static void check_pendings(struct sip_pvt *p)
17619 {
17620    if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
17621       /* if we can't BYE, then this is really a pending CANCEL */
17622       if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA)
17623          transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
17624          /* Actually don't destroy us yet, wait for the 487 on our original 
17625             INVITE, but do set an autodestruct just in case we never get it. */
17626       else {
17627          /* We have a pending outbound invite, don't send something
17628             new in-transaction */
17629          if (p->pendinginvite)
17630             return;
17631 
17632          /* Perhaps there is an SD change INVITE outstanding */
17633          transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
17634       }
17635       ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);   
17636       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17637    } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
17638       /* if we can't REINVITE, hold it for later */
17639       if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
17640          ast_debug(2, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
17641       } else {
17642          ast_debug(2, "Sending pending reinvite on '%s'\n", p->callid);
17643          /* Didn't get to reinvite yet, so do it now */
17644          transmit_reinvite_with_sdp(p, (p->t38.state == T38_LOCAL_REINVITE ? TRUE : FALSE), FALSE);
17645          ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE); 
17646       }
17647    }
17648 }
17649 
17650 /*! \brief Reset the NEEDREINVITE flag after waiting when we get 491 on a Re-invite
17651    to avoid race conditions between asterisk servers.
17652    Called from the scheduler.
17653 */
17654 static int sip_reinvite_retry(const void *data)
17655 {
17656    struct sip_pvt *p = (struct sip_pvt *) data;
17657 
17658    sip_pvt_lock(p); /* called from schedule thread which requires a lock */
17659    ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
17660    p->waitid = -1;
17661    check_pendings(p);
17662    sip_pvt_unlock(p);
17663    dialog_unref(p, "unref the dialog ptr from sip_reinvite_retry, because it held a dialog ptr");
17664    return 0;
17665 }
17666 
17667 
17668 /*! \brief Handle SIP response to INVITE dialogue */
17669 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
17670 {
17671    int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
17672    int res = 0;
17673    int xmitres = 0;
17674    int reinvite = (p->owner && p->owner->_state == AST_STATE_UP);
17675    char *p_hdrval;
17676    int rtn;
17677 
17678    if (reinvite)
17679       ast_debug(4, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
17680    else
17681       ast_debug(4, "SIP response %d to standard invite\n", resp);
17682 
17683    if (p->alreadygone) { /* This call is already gone */
17684       ast_debug(1, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
17685       return;
17686    }
17687 
17688    /* Acknowledge sequence number - This only happens on INVITE from SIP-call */
17689    /* Don't auto congest anymore since we've gotten something useful back */
17690    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"));
17691 
17692    /* RFC3261 says we must treat every 1xx response (but not 100)
17693       that we don't recognize as if it was 183.
17694    */
17695    if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 182 && resp != 183)
17696       resp = 183;
17697 
17698    /* Any response between 100 and 199 is PROCEEDING */
17699    if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING)
17700       p->invitestate = INV_PROCEEDING;
17701  
17702    /* Final response, not 200 ? */
17703    if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA ))
17704       p->invitestate = INV_COMPLETED;
17705    
17706    /* Final response, clear out pending invite */
17707    if ((resp == 200 || resp >= 300) && p->pendinginvite && seqno == p->pendinginvite)
17708       p->pendinginvite = 0;
17709 
17710    switch (resp) {
17711    case 100:   /* Trying */
17712    case 101:   /* Dialog establishment */
17713       if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
17714          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
17715       check_pendings(p);
17716       break;
17717 
17718    case 180:   /* 180 Ringing */
17719    case 182:       /* 182 Queued */
17720       if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
17721          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
17722       if (!req->ignore && p->owner) {
17723          ast_queue_control(p->owner, AST_CONTROL_RINGING);
17724          if (p->owner->_state != AST_STATE_UP) {
17725             ast_setstate(p->owner, AST_STATE_RINGING);
17726          }
17727       }
17728       if (find_sdp(req)) {
17729          if (p->invitestate != INV_CANCELLED)
17730             p->invitestate = INV_EARLY_MEDIA;
17731          res = process_sdp(p, req, SDP_T38_NONE);
17732          if (!req->ignore && p->owner) {
17733             /* Queue a progress frame only if we have SDP in 180 or 182 */
17734             ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
17735          }
17736       }
17737       check_pendings(p);
17738       break;
17739 
17740    case 183:   /* Session progress */
17741       if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
17742          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
17743       if (find_sdp(req)) {
17744          if (p->invitestate != INV_CANCELLED)
17745             p->invitestate = INV_EARLY_MEDIA;
17746          res = process_sdp(p, req, SDP_T38_NONE);
17747          if (!req->ignore && p->owner) {
17748             /* Queue a progress frame */
17749             ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
17750          }
17751       } else {
17752          /* Alcatel PBXs are known to send 183s with no SDP after sending
17753           * a 100 Trying response. We're just going to treat this sort of thing
17754           * the same as we would treat a 180 Ringing
17755           */
17756          if (!req->ignore && p->owner) {
17757             ast_queue_control(p->owner, AST_CONTROL_RINGING);
17758          }
17759       }
17760       check_pendings(p);
17761       break;
17762 
17763    case 200:   /* 200 OK on invite - someone's answering our call */
17764       if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
17765          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
17766       p->authtries = 0;
17767       if (find_sdp(req)) {
17768          if ((res = process_sdp(p, req, SDP_T38_ACCEPT)) && !req->ignore)
17769             if (!reinvite)
17770                /* This 200 OK's SDP is not acceptable, so we need to ack, then hangup */
17771                /* For re-invites, we try to recover */
17772                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
17773       }
17774 
17775       /* Parse contact header for continued conversation */
17776       /* When we get 200 OK, we know which device (and IP) to contact for this call */
17777       /* This is important when we have a SIP proxy between us and the phone */
17778       if (outgoing) {
17779          update_call_counter(p, DEC_CALL_RINGING);
17780          parse_ok_contact(p, req);
17781          /* Save Record-Route for any later requests we make on this dialogue */
17782          if (!reinvite)
17783             build_route(p, req, 1);
17784 
17785          if(set_address_from_contact(p)) {
17786             /* Bad contact - we don't know how to reach this device */
17787             /* We need to ACK, but then send a bye */
17788             if (!p->route && !req->ignore)
17789                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
17790          } 
17791 
17792       }
17793 
17794       if (!req->ignore && p->owner) {
17795          if (!reinvite) {
17796             ast_queue_control(p->owner, AST_CONTROL_ANSWER);
17797             if (sip_cfg.callevents)
17798                manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
17799                   "Channel: %s\r\nChanneltype: %s\r\nUniqueid: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
17800                   p->owner->name, "SIP", p->owner->uniqueid, p->callid, p->fullcontact, p->peername);
17801          } else { /* RE-invite */
17802             ast_queue_frame(p->owner, &ast_null_frame);
17803          }
17804       } else {
17805           /* It's possible we're getting an 200 OK after we've tried to disconnect
17806               by sending CANCEL */
17807          /* First send ACK, then send bye */
17808          if (!req->ignore)
17809             ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
17810       }
17811 
17812       /* Check for Session-Timers related headers */
17813       if (st_get_mode(p) != SESSION_TIMER_MODE_REFUSE && p->outgoing_call == TRUE && !reinvite) {
17814          p_hdrval = (char*)get_header(req, "Session-Expires");
17815             if (!ast_strlen_zero(p_hdrval)) {
17816             /* UAS supports Session-Timers */
17817             enum st_refresher tmp_st_ref = SESSION_TIMER_REFRESHER_AUTO;
17818             int tmp_st_interval = 0;
17819             rtn = parse_session_expires(p_hdrval, &tmp_st_interval, &tmp_st_ref);
17820             if (rtn != 0) {
17821                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
17822             }
17823             if (tmp_st_ref == SESSION_TIMER_REFRESHER_UAC || 
17824                tmp_st_ref == SESSION_TIMER_REFRESHER_UAS) {
17825                p->stimer->st_ref = tmp_st_ref;
17826             } 
17827             if (tmp_st_interval) {
17828                p->stimer->st_interval = tmp_st_interval;
17829             }
17830             p->stimer->st_active = TRUE;
17831             p->stimer->st_active_peer_ua = TRUE;
17832             start_session_timer(p);
17833          } else {
17834             /* UAS doesn't support Session-Timers */
17835             if (st_get_mode(p) == SESSION_TIMER_MODE_ORIGINATE) {
17836                p->stimer->st_ref = SESSION_TIMER_REFRESHER_UAC;
17837                p->stimer->st_active_peer_ua = FALSE;
17838                start_session_timer(p);
17839             }
17840          }
17841       }
17842 
17843 
17844       /* If I understand this right, the branch is different for a non-200 ACK only */
17845       p->invitestate = INV_TERMINATED;
17846       ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
17847       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
17848       check_pendings(p);
17849       break;
17850 
17851    case 407: /* Proxy authentication */
17852    case 401: /* Www auth */
17853       /* First we ACK */
17854       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17855       if (p->options)
17856          p->options->auth_type = resp;
17857 
17858       /* Then we AUTH */
17859       ast_string_field_set(p, theirtag, NULL);  /* forget their old tag, so we don't match tags when getting response */
17860       if (!req->ignore) {
17861          if (p->authtries < MAX_AUTHTRIES)
17862             p->invitestate = INV_CALLING;
17863          if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, SIP_INVITE, 1)) {
17864             ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
17865             pvt_set_needdestroy(p, "failed to authenticate on INVITE");
17866             sip_alreadygone(p);
17867             if (p->owner)
17868                ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17869          }
17870       }
17871       break;
17872 
17873    case 403: /* Forbidden */
17874       /* First we ACK */
17875       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17876       ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
17877       if (!req->ignore && p->owner)
17878          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17879       pvt_set_needdestroy(p, "received 403 response");
17880       sip_alreadygone(p);
17881       break;
17882 
17883    case 404: /* Not found */
17884       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17885       if (p->owner && !req->ignore)
17886          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17887       sip_alreadygone(p);
17888       break;
17889 
17890    case 408: /* Request timeout */
17891    case 481: /* Call leg does not exist */
17892       /* Could be REFER caused INVITE with replaces */
17893       ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
17894       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17895       if (p->owner)
17896          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17897       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17898       break;
17899 
17900    case 422: /* Session-Timers: Session interval too small */
17901       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17902       ast_string_field_set(p, theirtag, NULL);
17903       proc_422_rsp(p, req);
17904       break;
17905 
17906    case 428: /* Use identity header - rfc 4474 - not supported by Asterisk yet */
17907       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17908       append_history(p, "Identity", "SIP identity is required. Not supported by Asterisk.");
17909       ast_log(LOG_WARNING, "SIP identity required by proxy. SIP dialog '%s'. Giving up.\n", p->callid);
17910       if (p->owner)
17911          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17912       break;
17913 
17914       
17915 
17916    case 487: /* Cancelled transaction */
17917       /* We have sent CANCEL on an outbound INVITE 
17918          This transaction is already scheduled to be killed by sip_hangup().
17919       */
17920       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17921       if (p->owner && !req->ignore) {
17922          ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_CLEARING);
17923          append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
17924       } else if (!req->ignore) {
17925          update_call_counter(p, DEC_CALL_LIMIT);
17926          append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
17927          pvt_set_needdestroy(p, "received 487 response");
17928          sip_alreadygone(p);
17929       }
17930       break;
17931    case 415: /* Unsupported media type */
17932    case 488: /* Not acceptable here */
17933    case 606: /* Not Acceptable */
17934       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17935       if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
17936          change_t38_state(p, T38_DISABLED);
17937          /* Try to reset RTP timers */
17938          ast_rtp_set_rtptimers_onhold(p->rtp);
17939 
17940          /* Trigger a reinvite back to audio */
17941          transmit_reinvite_with_sdp(p, FALSE, FALSE);
17942       } else {
17943          /* We can't set up this call, so give up */
17944          if (p->owner && !req->ignore)
17945             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17946          pvt_set_needdestroy(p, "received 488 response");
17947          /* If there's no dialog to end, then mark p as already gone */
17948          if (!reinvite)
17949             sip_alreadygone(p);
17950       }
17951       break;
17952    case 491: /* Pending */
17953       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17954       if (p->owner && !req->ignore) {
17955          if (p->owner->_state != AST_STATE_UP) {
17956             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17957             pvt_set_needdestroy(p, "received 491 response");
17958          } else {
17959             /* This is a re-invite that failed. */
17960             /* Reset the flag after a while 
17961              */
17962             int wait;
17963             /* RFC 3261, if owner of call, wait between 2.1 to 4 seconds,
17964              * if not owner of call, wait 0 to 2 seconds */
17965             if (p->outgoing_call) {
17966                wait = 2100 + ast_random() % 2000;
17967             } else {
17968                wait = ast_random() % 2000;
17969             }
17970             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."));
17971             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);
17972             ast_debug(2, "Reinvite race. Waiting %d secs before retry\n", wait);
17973          }
17974       }
17975       break;
17976 
17977    case 501: /* Not implemented */
17978       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17979       if (p->owner)
17980          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17981       break;
17982    }
17983    if (xmitres == XMIT_ERROR)
17984       ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
17985 }
17986 
17987 /* \brief Handle SIP response in NOTIFY transaction
17988        We've sent a NOTIFY, now handle responses to it
17989   */
17990 static void handle_response_notify(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
17991 {
17992    switch (resp) {
17993    case 200:   /* Notify accepted */
17994       /* They got the notify, this is the end */
17995       if (p->owner) {
17996          if (!p->refer) {
17997             ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
17998             ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_UNSPECIFIED);
17999          } else {
18000             ast_debug(4, "Got OK on REFER Notify message\n");
18001          }
18002       } else {
18003          if (p->subscribed == NONE) {
18004             ast_debug(4, "Got 200 accepted on NOTIFY\n");
18005             pvt_set_needdestroy(p, "received 200 response");
18006          }
18007          if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
18008             /* Ready to send the next state we have on queue */
18009             ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
18010             cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
18011          }
18012       }
18013       break;
18014    case 401:   /* Not www-authorized on SIP method */
18015    case 407:   /* Proxy auth */
18016       if (!p->notify_headers) {
18017          break; /* Only device notify can use NOTIFY auth */
18018       }
18019       ast_string_field_set(p, theirtag, NULL);
18020       if (ast_strlen_zero(p->authname)) {
18021          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));
18022          pvt_set_needdestroy(p, "unable to authenticate NOTIFY");
18023       }
18024       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_NOTIFY, 0)) {
18025          ast_log(LOG_NOTICE, "Failed to authenticate on NOTIFY to '%s'\n", get_header(&p->initreq, "From"));
18026          pvt_set_needdestroy(p, "failed to authenticate NOTIFY");
18027       }
18028       break;
18029    }
18030 }
18031 
18032 /* \brief Handle SIP response in SUBSCRIBE transaction */
18033 static void handle_response_subscribe(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18034 {
18035    if (!p->mwi) {
18036       return;
18037    }
18038 
18039    switch (resp) {
18040    case 200: /* Subscription accepted */
18041       ast_debug(3, "Got 200 OK on subscription for MWI\n");
18042       if (p->options) {
18043          ast_free(p->options);
18044          p->options = NULL;
18045       }
18046       p->mwi->subscribed = 1;
18047       if ((p->mwi->resub = ast_sched_add(sched, mwi_expiry * 1000, sip_subscribe_mwi_do, ASTOBJ_REF(p->mwi))) < 0) {
18048          ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18049       }
18050       break;
18051    case 401:
18052    case 407:
18053       ast_string_field_set(p, theirtag, NULL);
18054       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_SUBSCRIBE, 0)) {
18055          ast_log(LOG_NOTICE, "Failed to authenticate on SUBSCRIBE to '%s'\n", get_header(&p->initreq, "From"));
18056          p->mwi->call = NULL;
18057          ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18058          pvt_set_needdestroy(p, "failed to authenticate SUBSCRIBE");
18059       }
18060       break;
18061    case 403:
18062       transmit_response_with_date(p, "200 OK", req);
18063       ast_log(LOG_WARNING, "Authentication failed while trying to subscribe for MWI.\n");
18064       p->mwi->call = NULL;
18065       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18066       pvt_set_needdestroy(p, "received 403 response");
18067       sip_alreadygone(p);
18068       break;
18069    case 404:
18070       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that a mailbox may not have been configured.\n");
18071       p->mwi->call = NULL;
18072       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18073       pvt_set_needdestroy(p, "received 404 response");
18074       break;
18075    case 481:
18076       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that our dialog did not exist.\n");
18077       p->mwi->call = NULL;
18078       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18079       pvt_set_needdestroy(p, "received 481 response");
18080       break;
18081    case 500:
18082    case 501:
18083       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side may have suffered a heart attack.\n");
18084       p->mwi->call = NULL;
18085       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18086       pvt_set_needdestroy(p, "received 500/501 response");
18087       break;
18088    }
18089 }
18090 
18091 /* \brief Handle SIP response in REFER transaction
18092    We've sent a REFER, now handle responses to it 
18093   */
18094 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18095 {
18096    /* If no refer structure exists, then do nothing */
18097    if (!p->refer)
18098       return;
18099 
18100    switch (resp) {
18101    case 202:   /* Transfer accepted */
18102       /* We need  to do something here */
18103       /* The transferee is now sending INVITE to target */
18104       p->refer->status = REFER_ACCEPTED;
18105       /* Now wait for next message */
18106       ast_debug(3, "Got 202 accepted on transfer\n");
18107       /* We should hang along, waiting for NOTIFY's here */
18108       break;
18109 
18110    case 401:   /* Not www-authorized on SIP method */
18111    case 407:   /* Proxy auth */
18112       if (ast_strlen_zero(p->authname)) {
18113          ast_log(LOG_WARNING, "Asked to authenticate REFER to %s:%d but we have no matching peer or realm auth!\n",
18114             ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
18115          pvt_set_needdestroy(p, "unable to authenticate REFER");
18116       }
18117       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_REFER, 0)) {
18118          ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
18119          p->refer->status = REFER_NOAUTH;
18120          pvt_set_needdestroy(p, "failed to authenticat REFER");
18121       }
18122       break;
18123    case 481: /* Call leg does not exist */
18124 
18125       /* A transfer with Replaces did not work */
18126       /* OEJ: We should Set flag, cancel the REFER, go back
18127       to original call - but right now we can't */
18128       ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
18129       if (p->owner)
18130          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18131       pvt_set_needdestroy(p, "received 481 response");
18132       break;
18133 
18134    case 500:   /* Server error */
18135    case 501:   /* Method not implemented */
18136       /* Return to the current call onhold */
18137       /* Status flag needed to be reset */
18138       ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
18139       pvt_set_needdestroy(p, "received 500/501 response");
18140       p->refer->status = REFER_FAILED;
18141       break;
18142    case 603:   /* Transfer declined */
18143       ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
18144       p->refer->status = REFER_FAILED;
18145       pvt_set_needdestroy(p, "received 603 response");
18146       break;
18147    }
18148 }
18149 
18150 /*! \brief Handle responses on REGISTER to services */
18151 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18152 {
18153    int expires, expires_ms;
18154    struct sip_registry *r;
18155    r=p->registry;
18156    
18157    switch (resp) {
18158    case 401:   /* Unauthorized */
18159       if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
18160          ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
18161          pvt_set_needdestroy(p, "failed to authenticate REGISTER");
18162       }
18163       break;
18164    case 403:   /* Forbidden */
18165       ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
18166       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 403"));
18167       r->regstate = REG_STATE_NOAUTH;
18168       pvt_set_needdestroy(p, "received 403 response");
18169       break;
18170    case 404:   /* Not found */
18171       ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username, p->registry->hostname);
18172       pvt_set_needdestroy(p, "received 404 response");
18173       if (r->call)
18174          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 404");
18175       r->regstate = REG_STATE_REJECTED;
18176       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 404"));
18177       break;
18178    case 407:   /* Proxy auth */
18179       if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
18180          ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
18181          pvt_set_needdestroy(p, "failed to authenticate REGISTER");
18182       }
18183       break;
18184    case 408:   /* Request timeout */
18185       /* Got a timeout response, so reset the counter of failed responses */
18186       if (r) {
18187          r->regattempts = 0;
18188       } else {
18189          ast_log(LOG_WARNING, "Got a 408 response to our REGISTER on call %s after we had destroyed the registry object\n", p->callid);
18190       }
18191       break;
18192    case 423:   /* Interval too brief */
18193       r->expiry = atoi(get_header(req, "Min-Expires"));
18194       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);
18195       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 423"));
18196       if (r->call) {
18197          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 423");
18198          pvt_set_needdestroy(p, "received 423 response");
18199       }
18200       if (r->expiry > max_expiry) {
18201          ast_log(LOG_WARNING, "Required expiration time from %s@%s is too high, giving up\n", p->registry->username, p->registry->hostname);
18202          r->expiry = r->configured_expiry;
18203          r->regstate = REG_STATE_REJECTED;
18204       } else {
18205          r->regstate = REG_STATE_UNREGISTERED;
18206          transmit_register(r, SIP_REGISTER, NULL, NULL);
18207       }
18208       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));
18209       break;
18210    case 479:   /* SER: Not able to process the URI - address is wrong in register*/
18211       ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username, p->registry->hostname);
18212       pvt_set_needdestroy(p, "received 479 response");
18213       if (r->call)
18214          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 479");
18215       r->regstate = REG_STATE_REJECTED;
18216       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 479"));
18217       break;
18218    case 200:   /* 200 OK */
18219       if (!r) {
18220          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));
18221          pvt_set_needdestroy(p, "received erroneous 200 response");
18222          return 0;
18223       }
18224       
18225       r->regstate = REG_STATE_REGISTERED;
18226       r->regtime = ast_tvnow();     /* Reset time of last succesful registration */
18227       manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
18228       r->regattempts = 0;
18229       ast_debug(1, "Registration successful\n");
18230       if (r->timeout > -1) {
18231          ast_debug(1, "Cancelling timeout %d\n", r->timeout);
18232       }
18233       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 200"));
18234       if (r->call)
18235          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 200");
18236       p->registry = registry_unref(p->registry, "unref registry entry p->registry");
18237       /* Let this one hang around until we have all the responses */
18238       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18239       /* p->needdestroy = 1; */
18240       
18241       /* set us up for re-registering
18242        * figure out how long we got registered for
18243        * according to section 6.13 of RFC, contact headers override
18244        * expires headers, so check those first */
18245       expires = 0;
18246 
18247       /* XXX todo: try to save the extra call */
18248       if (!ast_strlen_zero(get_header(req, "Contact"))) {
18249          const char *contact = NULL;
18250          const char *tmptmp = NULL;
18251          int start = 0;
18252          for(;;) {
18253             contact = __get_header(req, "Contact", &start);
18254             /* this loop ensures we get a contact header about our register request */
18255             if(!ast_strlen_zero(contact)) {
18256                if( (tmptmp=strstr(contact, p->our_contact))) {
18257                   contact=tmptmp;
18258                   break;
18259                }
18260             } else
18261                break;
18262          }
18263          tmptmp = strcasestr(contact, "expires=");
18264          if (tmptmp) {
18265             if (sscanf(tmptmp + 8, "%30d;", &expires) != 1)
18266                expires = 0;
18267          }
18268          
18269       }
18270       if (!expires) 
18271          expires=atoi(get_header(req, "expires"));
18272       if (!expires)
18273          expires=default_expiry;
18274       
18275       expires_ms = expires * 1000;
18276       if (expires <= EXPIRY_GUARD_LIMIT)
18277          expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT), EXPIRY_GUARD_MIN);
18278       else
18279          expires_ms -= EXPIRY_GUARD_SECS * 1000;
18280       if (sipdebug)
18281          ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000); 
18282       
18283       r->refresh= (int) expires_ms / 1000;
18284       
18285       /* Schedule re-registration before we expire */
18286       AST_SCHED_REPLACE_UNREF(r->expire, sched, expires_ms, sip_reregister, r, 
18287                         registry_unref(_data,"unref in REPLACE del fail"), 
18288                         registry_unref(r,"unref in REPLACE add fail"), 
18289                         registry_addref(r,"The Addition side of REPLACE")); 
18290    }
18291    return 1;
18292 }
18293 
18294 /*! \brief Handle qualification responses (OPTIONS) */
18295 static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
18296 {
18297    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! */
18298    int statechanged, is_reachable, was_reachable;
18299    int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
18300 
18301    /*
18302     * Compute the response time to a ping (goes in peer->lastms.)
18303     * -1 means did not respond, 0 means unknown,
18304     * 1..maxms is a valid response, >maxms means late response.
18305     */
18306    if (pingtime < 1) /* zero = unknown, so round up to 1 */
18307       pingtime = 1;
18308 
18309    /* Now determine new state and whether it has changed.
18310     * Use some helper variables to simplify the writing
18311     * of the expressions.
18312     */
18313    was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
18314    is_reachable = pingtime <= peer->maxms;
18315    statechanged = peer->lastms == 0 /* yes, unknown before */
18316       || was_reachable != is_reachable;
18317 
18318    peer->lastms = pingtime;
18319    peer->call = dialog_unref(peer->call, "unref dialog peer->call");
18320    if (statechanged) {
18321       const char *s = is_reachable ? "Reachable" : "Lagged";
18322       char str_lastms[20];
18323       snprintf(str_lastms, sizeof(str_lastms), "%d", pingtime);
18324 
18325       ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
18326          peer->name, s, pingtime, peer->maxms);
18327       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
18328       if (sip_cfg.peer_rtupdate) {
18329          ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", str_lastms, SENTINEL);
18330       }
18331       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
18332          "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
18333          peer->name, s, pingtime);
18334       if (is_reachable && sip_cfg.regextenonqualify)
18335          register_peer_exten(peer, TRUE);
18336    }
18337 
18338    pvt_set_needdestroy(p, "got OPTIONS response");
18339 
18340    /* Try again eventually */
18341    AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
18342          is_reachable ? peer->qualifyfreq : DEFAULT_FREQ_NOTOK,
18343          sip_poke_peer_s, peer,
18344          unref_peer(_data, "removing poke peer ref"),
18345          unref_peer(peer, "removing poke peer ref"),
18346          ref_peer(peer, "adding poke peer ref"));
18347 }
18348 
18349 /*! \brief Immediately stop RTP, VRTP and UDPTL as applicable */
18350 static void stop_media_flows(struct sip_pvt *p)
18351 {
18352    /* Immediately stop RTP, VRTP and UDPTL as applicable */
18353    if (p->rtp)
18354       ast_rtp_stop(p->rtp);
18355    if (p->vrtp)
18356       ast_rtp_stop(p->vrtp);
18357    if (p->trtp)
18358       ast_rtp_stop(p->trtp);
18359    if (p->udptl)
18360       ast_udptl_stop(p->udptl);
18361 }
18362 
18363 /*! \brief Handle SIP response in dialogue
18364    \note only called by handle_incoming */
18365 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18366 {
18367    struct ast_channel *owner;
18368    int sipmethod;
18369    int res = 1;
18370    const char *c = get_header(req, "Cseq");
18371    /* 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 */
18372    char *c_copy = ast_strdupa(c);
18373    /* Skip the Cseq and its subsequent spaces */
18374    const char *msg = ast_skip_blanks(ast_skip_nonblanks(c_copy));
18375 
18376    if (!msg)
18377       msg = "";
18378 
18379    sipmethod = find_sip_method(msg);
18380 
18381    owner = p->owner;
18382    if (owner) 
18383       owner->hangupcause = hangup_sip2cause(resp);
18384 
18385    if (p->socket.type == SIP_TRANSPORT_UDP) {
18386       int ack_res;
18387 
18388       /* Acknowledge whatever it is destined for */
18389       if ((resp >= 100) && (resp <= 199)) {
18390          ack_res = __sip_semi_ack(p, seqno, 0, sipmethod);
18391       } else {
18392          ack_res = __sip_ack(p, seqno, 0, sipmethod);
18393       }
18394 
18395       if (ack_res == FALSE) {
18396          append_history(p, "Ignore", "Ignoring this retransmit\n");
18397          return;
18398       }
18399    }
18400 
18401    /* If this is a NOTIFY for a subscription clear the flag that indicates that we have a NOTIFY pending */
18402    if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite) 
18403       p->pendinginvite = 0;
18404 
18405    /* Get their tag if we haven't already */
18406    if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
18407       char tag[128];
18408 
18409       gettag(req, "To", tag, sizeof(tag));
18410       ast_string_field_set(p, theirtag, tag);
18411    }
18412    /* This needs to be configurable on a channel/peer level,
18413       not mandatory for all communication. Sadly enough, NAT implementations
18414       are not so stable so we can always rely on these headers. 
18415       Temporarily disabled, while waiting for fix.
18416       Fix assigned to Rizzo :-)
18417    */
18418    /* check_via_response(p, req); */
18419 
18420    /* RFC 3261 Section 15 specifies that if we receive a 408 or 481
18421     * in response to a BYE, then we should end the current dialog
18422     * and session.  It is known that at least one phone manufacturer
18423     * potentially will send a 404 in response to a BYE, so we'll be
18424     * liberal in what we accept and end the dialog and session if we
18425     * receive any of those responses to a BYE.
18426     */
18427    if ((resp == 404 || resp == 408 || resp == 481) && sipmethod == SIP_BYE) {
18428       pvt_set_needdestroy(p, "received 4XX response to a BYE");
18429       return;
18430    }
18431 
18432    if (p->relatedpeer && p->method == SIP_OPTIONS) {
18433       /* We don't really care what the response is, just that it replied back. 
18434          Well, as long as it's not a 100 response...  since we might
18435          need to hang around for something more "definitive" */
18436       if (resp != 100)
18437          handle_response_peerpoke(p, resp, req);
18438    } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
18439       switch(resp) {
18440       case 100:   /* 100 Trying */
18441       case 101:   /* 101 Dialog establishment */
18442       case 183:   /* 183 Session Progress */
18443       case 180:   /* 180 Ringing */
18444       case 182:   /* 182 Queued */
18445          if (sipmethod == SIP_INVITE)
18446             handle_response_invite(p, resp, rest, req, seqno);
18447          break;
18448       case 200:   /* 200 OK */
18449          p->authtries = 0; /* Reset authentication counter */
18450          if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
18451             /* We successfully transmitted a message 
18452                or a video update request in INFO */
18453             /* Nothing happens here - the message is inside a dialog */
18454          } else if (sipmethod == SIP_INVITE) {
18455             handle_response_invite(p, resp, rest, req, seqno);
18456          } else if (sipmethod == SIP_NOTIFY) {
18457             handle_response_notify(p, resp, rest, req, seqno);
18458          } else if (sipmethod == SIP_REGISTER) {
18459             res = handle_response_register(p, resp, rest, req, seqno);
18460          } else if (sipmethod == SIP_SUBSCRIBE) {
18461             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
18462             handle_response_subscribe(p, resp, rest, req, seqno);
18463          } else if (sipmethod == SIP_BYE) {     /* Ok, we're ready to go */
18464             pvt_set_needdestroy(p, "received 200 response");
18465             ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
18466          }
18467          break;
18468       case 202:   /* Transfer accepted */
18469          if (sipmethod == SIP_REFER) 
18470             handle_response_refer(p, resp, rest, req, seqno);
18471          break;
18472       case 401: /* Not www-authorized on SIP method */
18473       case 407: /* Proxy auth required */
18474          if (sipmethod == SIP_INVITE)
18475             handle_response_invite(p, resp, rest, req, seqno);
18476          else if (sipmethod == SIP_NOTIFY)
18477             handle_response_notify(p, resp, rest, req, seqno);
18478          else if (sipmethod == SIP_REFER)
18479             handle_response_refer(p, resp, rest, req, seqno);
18480          else if (sipmethod == SIP_SUBSCRIBE)
18481             handle_response_subscribe(p, resp, rest, req, seqno);
18482          else if (p->registry && sipmethod == SIP_REGISTER)
18483             res = handle_response_register(p, resp, rest, req, seqno);
18484          else if (sipmethod == SIP_BYE) {
18485             if (p->options)
18486                p->options->auth_type = resp;
18487             if (ast_strlen_zero(p->authname)) {
18488                ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
18489                      msg, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
18490                pvt_set_needdestroy(p, "unable to authenticate BYE");
18491             } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp,  sipmethod, 0)) {
18492                ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
18493                pvt_set_needdestroy(p, "failed to authenticate BYE");
18494             }
18495          } else {
18496             ast_log(LOG_WARNING, "Got authentication request (%d) on %s to '%s'\n", resp, sip_methods[sipmethod].text, get_header(req, "To"));
18497             pvt_set_needdestroy(p, "received 407 response");
18498          }
18499          break;
18500       case 403: /* Forbidden - we failed authentication */
18501          if (sipmethod == SIP_INVITE)
18502             handle_response_invite(p, resp, rest, req, seqno);
18503          else if (sipmethod == SIP_SUBSCRIBE)
18504             handle_response_subscribe(p, resp, rest, req, seqno);
18505          else if (p->registry && sipmethod == SIP_REGISTER) 
18506             res = handle_response_register(p, resp, rest, req, seqno);
18507          else {
18508             ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
18509             pvt_set_needdestroy(p, "received 403 response");
18510          }
18511          break;
18512       case 404: /* Not found */
18513          if (p->registry && sipmethod == SIP_REGISTER)
18514             res = handle_response_register(p, resp, rest, req, seqno);
18515          else if (sipmethod == SIP_INVITE)
18516             handle_response_invite(p, resp, rest, req, seqno);
18517          else if (sipmethod == SIP_SUBSCRIBE)
18518             handle_response_subscribe(p, resp, rest, req, seqno);
18519          else if (owner)
18520             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18521          break;
18522       case 423: /* Interval too brief */
18523          if (sipmethod == SIP_REGISTER)
18524             res = handle_response_register(p, resp, rest, req, seqno);
18525          break;
18526       case 408: /* Request timeout - terminate dialog */
18527          if (sipmethod == SIP_INVITE)
18528             handle_response_invite(p, resp, rest, req, seqno);
18529          else if (sipmethod == SIP_REGISTER) 
18530             res = handle_response_register(p, resp, rest, req, seqno);
18531          else if (sipmethod == SIP_BYE) {
18532             pvt_set_needdestroy(p, "received 408 response");
18533             ast_debug(4, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
18534          } else {
18535             if (owner)
18536                ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18537             pvt_set_needdestroy(p, "received 408 response");
18538          }
18539          break;
18540 
18541       case 422: /* Session-Timers: Session Interval Too Small */
18542          if (sipmethod == SIP_INVITE) {
18543             handle_response_invite(p, resp, rest, req, seqno);
18544          }
18545          break;
18546 
18547       case 481: /* Call leg does not exist */
18548          if (sipmethod == SIP_INVITE) {
18549             handle_response_invite(p, resp, rest, req, seqno);
18550          } else if (sipmethod == SIP_REFER) {
18551             handle_response_refer(p, resp, rest, req, seqno);
18552          } else if (sipmethod == SIP_SUBSCRIBE) {
18553             handle_response_subscribe(p, resp, rest, req, seqno);
18554          } else if (sipmethod == SIP_BYE) {
18555             /* The other side has no transaction to bye,
18556             just assume it's all right then */
18557             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
18558          } else if (sipmethod == SIP_CANCEL) {
18559             /* The other side has no transaction to cancel,
18560             just assume it's all right then */
18561             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
18562          } else {
18563             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
18564             /* Guessing that this is not an important request */
18565          }
18566          break;
18567       case 487:
18568          if (sipmethod == SIP_INVITE)
18569             handle_response_invite(p, resp, rest, req, seqno);
18570          break;
18571       case 415: /* Unsupported media type */
18572       case 488: /* Not acceptable here - codec error */
18573       case 606: /* Not Acceptable */
18574          if (sipmethod == SIP_INVITE)
18575             handle_response_invite(p, resp, rest, req, seqno);
18576          break;
18577       case 491: /* Pending */
18578          if (sipmethod == SIP_INVITE)
18579             handle_response_invite(p, resp, rest, req, seqno);
18580          else {
18581             ast_debug(1, "Got 491 on %s, unsupported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
18582             pvt_set_needdestroy(p, "received 491 response");
18583          }
18584          break;
18585       case 501: /* Not Implemented */
18586          if (sipmethod == SIP_INVITE)
18587             handle_response_invite(p, resp, rest, req, seqno);
18588          else if (sipmethod == SIP_REFER)
18589             handle_response_refer(p, resp, rest, req, seqno);
18590          else
18591             ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_inet_ntoa(p->sa.sin_addr), msg);
18592          break;
18593       case 603:   /* Declined transfer */
18594          if (sipmethod == SIP_REFER) {
18595             handle_response_refer(p, resp, rest, req, seqno);
18596             break;
18597          }
18598          /* Fallthrough */
18599       default:
18600          if ((resp >= 300) && (resp < 700)) {
18601             /* Fatal response */
18602             if ((resp != 487))
18603                ast_verb(3, "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
18604    
18605             if (sipmethod == SIP_INVITE)
18606                stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
18607 
18608             /* XXX Locking issues?? XXX */
18609             switch(resp) {
18610             case 300: /* Multiple Choices */
18611             case 301: /* Moved permanently */
18612             case 302: /* Moved temporarily */
18613             case 305: /* Use Proxy */
18614                parse_moved_contact(p, req);
18615                /* Fall through */
18616             case 486: /* Busy here */
18617             case 600: /* Busy everywhere */
18618             case 603: /* Decline */
18619                if (p->owner)
18620                   ast_queue_control(p->owner, AST_CONTROL_BUSY);
18621                break;
18622             case 482: /* Loop Detected */
18623                /*
18624                   \note Asterisk has historically tried to do a call forward when it
18625                   gets a 482, but that behavior isn't necessarily the best course of
18626                   action. Go ahead and do it anyway by default, but allow the option
18627                   to immediately pass to the next line in the dialplan. */
18628                if (p->owner && ast_test_flag(&p->flags[1], SIP_PAGE2_FORWARD_LOOP_DETECTED)) {
18629                      ast_debug(1, "Hairpin detected, setting up call forward for what it's worth\n");
18630                      ast_string_field_build(p->owner, call_forward,
18631                            "Local/%s@%s", p->username, p->context);
18632                }
18633                /* Fall through */
18634             case 480: /* Temporarily Unavailable */
18635             case 404: /* Not Found */
18636             case 410: /* Gone */
18637             case 400: /* Bad Request */
18638             case 500: /* Server error */
18639                if (sipmethod == SIP_REFER) {
18640                   handle_response_refer(p, resp, rest, req, seqno);
18641                   break;
18642                } else if (sipmethod == SIP_SUBSCRIBE) {
18643                   handle_response_subscribe(p, resp, rest, req, seqno);
18644                   break;
18645                }
18646                /* Fall through */
18647             case 502: /* Bad gateway */
18648             case 503: /* Service Unavailable */
18649             case 504: /* Server Timeout */
18650                if (owner)
18651                   ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18652                break;
18653             default:
18654                /* Send hangup */ 
18655                if (owner && sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO && sipmethod != SIP_BYE)
18656                   ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
18657                break;
18658             }
18659             /* ACK on invite */
18660             if (sipmethod == SIP_INVITE) 
18661                transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18662             if (sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO) 
18663                sip_alreadygone(p);
18664             if (!p->owner) {
18665                pvt_set_needdestroy(p, "transaction completed");
18666             }
18667          } else if ((resp >= 100) && (resp < 200)) {
18668             if (sipmethod == SIP_INVITE) {
18669                if (!req->ignore && sip_cancel_destroy(p))
18670                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
18671                if (find_sdp(req))
18672                   process_sdp(p, req, SDP_T38_NONE);
18673                if (p->owner) {
18674                   /* Queue a progress frame */
18675                   ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
18676                }
18677             }
18678          } else
18679             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));
18680       }
18681    } else { 
18682       /* Responses to OUTGOING SIP requests on INCOMING calls 
18683          get handled here. As well as out-of-call message responses */
18684       if (req->debug)
18685          ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
18686 
18687       if (sipmethod == SIP_INVITE && resp == 200) {
18688          /* Tags in early session is replaced by the tag in 200 OK, which is 
18689          the final reply to our INVITE */
18690          char tag[128];
18691 
18692          gettag(req, "To", tag, sizeof(tag));
18693          ast_string_field_set(p, theirtag, tag);
18694       }
18695 
18696       switch(resp) {
18697       case 200:
18698          if (sipmethod == SIP_INVITE) {
18699             handle_response_invite(p, resp, rest, req, seqno);
18700          } else if (sipmethod == SIP_CANCEL) {
18701             ast_debug(1, "Got 200 OK on CANCEL\n");
18702 
18703             /* Wait for 487, then destroy */
18704          } else if (sipmethod == SIP_NOTIFY) {
18705             /* They got the notify, this is the end */
18706             if (p->owner) {
18707                if (p->refer) {
18708                   ast_debug(1, "Got 200 OK on NOTIFY for transfer\n");
18709                } else
18710                   ast_log(LOG_WARNING, "Notify answer on an owned channel?\n");
18711                /* ast_queue_hangup(p->owner); Disabled */
18712             } else {
18713                if (!p->subscribed && !p->refer) {
18714                   pvt_set_needdestroy(p, "transaction completed");
18715                }
18716                if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
18717                   /* Ready to send the next state we have on queue */
18718                   ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
18719                   cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
18720                }
18721             }
18722          } else if (sipmethod == SIP_BYE) {
18723             pvt_set_needdestroy(p, "transaction completed");
18724          } else if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
18725             /* We successfully transmitted a message or
18726                a video update request in INFO */
18727             ;
18728          }
18729          break;
18730       case 202:   /* Transfer accepted */
18731          if (sipmethod == SIP_REFER) 
18732             handle_response_refer(p, resp, rest, req, seqno);
18733          break;
18734       case 401:   /* www-auth */
18735       case 407:
18736          if (sipmethod == SIP_REFER)
18737             handle_response_refer(p, resp, rest, req, seqno);
18738          else if (sipmethod == SIP_INVITE) 
18739             handle_response_invite(p, resp, rest, req, seqno);
18740          else if (sipmethod == SIP_BYE) {
18741             if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, sipmethod, 0)) {
18742                ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
18743                pvt_set_needdestroy(p, "failed to authenticate BYE");
18744             }
18745          }
18746          break;
18747       case 481:   /* Call leg does not exist */
18748          if (sipmethod == SIP_INVITE) {
18749             /* Re-invite failed */
18750             handle_response_invite(p, resp, rest, req, seqno);
18751          } else if (sipmethod == SIP_BYE) {
18752             pvt_set_needdestroy(p, "received 481 response");
18753          } else if (sipdebug) {
18754             ast_debug(1, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
18755          }
18756          break;
18757       case 501: /* Not Implemented */
18758          if (sipmethod == SIP_INVITE) 
18759             handle_response_invite(p, resp, rest, req, seqno);
18760          else if (sipmethod == SIP_REFER) 
18761             handle_response_refer(p, resp, rest, req, seqno);
18762          break;
18763       case 603:   /* Declined transfer */
18764          if (sipmethod == SIP_REFER) {
18765             handle_response_refer(p, resp, rest, req, seqno);
18766             break;
18767          }
18768          /* Fallthrough */
18769       default: /* Errors without handlers */
18770          if ((resp >= 100) && (resp < 200)) {
18771             if (sipmethod == SIP_INVITE) {   /* re-invite */
18772                if (!req->ignore && sip_cancel_destroy(p))
18773                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
18774             }
18775          }
18776          if ((resp >= 300) && (resp < 700)) {
18777             if ((resp != 487))
18778                ast_verb(3, "Incoming call: Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
18779             switch(resp) {
18780             case 415: /* Unsupported media type */
18781             case 488: /* Not acceptable here - codec error */
18782             case 603: /* Decline */
18783             case 500: /* Server error */
18784             case 502: /* Bad gateway */
18785             case 503: /* Service Unavailable */
18786             case 504: /* Server timeout */
18787 
18788                /* re-invite failed */
18789                if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
18790                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
18791                break;
18792             }
18793          }
18794          break;
18795       }
18796    }
18797 }
18798 
18799 
18800 /*! \brief Park SIP call support function 
18801    Starts in a new thread, then parks the call
18802    XXX Should we add a wait period after streaming audio and before hangup?? Sometimes the
18803       audio can't be heard before hangup
18804 */
18805 static void *sip_park_thread(void *stuff)
18806 {
18807    struct ast_channel *transferee, *transferer; /* Chan1: The transferee, Chan2: The transferer */
18808    struct sip_dual *d;
18809    struct sip_request req = {0,};
18810    int ext;
18811    int res;
18812 
18813    d = stuff;
18814    transferee = d->chan1;
18815    transferer = d->chan2;
18816    copy_request(&req, &d->req);
18817 
18818    if (!transferee || !transferer) {
18819       ast_log(LOG_ERROR, "Missing channels for parking! Transferer %s Transferee %s\n", transferer ? "<available>" : "<missing>", transferee ? "<available>" : "<missing>" );
18820       deinit_req(&d->req);
18821       free(d);
18822       return NULL;
18823    }
18824    ast_debug(4, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);
18825 
18826    ast_channel_lock(transferee);
18827    if (ast_do_masquerade(transferee)) {
18828       ast_log(LOG_WARNING, "Masquerade failed.\n");
18829       transmit_response(transferer->tech_pvt, "503 Internal error", &req);
18830       ast_channel_unlock(transferee);
18831       deinit_req(&d->req);
18832       free(d);
18833       return NULL;
18834    } 
18835    ast_channel_unlock(transferee);
18836 
18837    res = ast_park_call(transferee, transferer, 0, &ext);
18838    
18839 
18840 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
18841    if (!res) {
18842       transmit_message_with_text(transferer->tech_pvt, "Unable to park call.\n");
18843    } else {
18844       /* Then tell the transferer what happened */
18845       sprintf(buf, "Call parked on extension '%d'", ext);
18846       transmit_message_with_text(transferer->tech_pvt, buf);
18847    }
18848 #endif
18849 
18850    /* Any way back to the current call??? */
18851    /* Transmit response to the REFER request */
18852    transmit_response(transferer->tech_pvt, "202 Accepted", &req);
18853    if (!res)   {
18854       /* Transfer succeeded */
18855       append_history(transferer->tech_pvt, "SIPpark", "Parked call on %d", ext);
18856       transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "200 OK", TRUE);
18857       transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
18858       ast_hangup(transferer); /* This will cause a BYE */
18859       ast_debug(1, "SIP Call parked on extension '%d'\n", ext);
18860    } else {
18861       transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "503 Service Unavailable", TRUE);
18862       append_history(transferer->tech_pvt, "SIPpark", "Parking failed\n");
18863       ast_debug(1, "SIP Call parked failed \n");
18864       /* Do not hangup call */
18865    }
18866    deinit_req(&d->req);
18867    free(d);
18868    return NULL;
18869 }
18870 
18871 /*! \brief Park a call using the subsystem in res_features.c 
18872    This is executed in a separate thread
18873 */
18874 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno)
18875 {
18876    struct sip_dual *d;
18877    struct ast_channel *transferee, *transferer;
18878       /* Chan2m: The transferer, chan1m: The transferee */
18879    pthread_t th;
18880 
18881    transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan1->accountcode, chan1->exten, chan1->context, chan1->amaflags, "Parking/%s", chan1->name);
18882    transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->amaflags, "SIPPeer/%s", chan2->name);
18883    if ((!transferer) || (!transferee)) {
18884       if (transferee) {
18885          transferee->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
18886          ast_hangup(transferee);
18887       }
18888       if (transferer) {
18889          transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
18890          ast_hangup(transferer);
18891       }
18892       return -1;
18893    }
18894 
18895    /* Make formats okay */
18896    transferee->readformat = chan1->readformat;
18897    transferee->writeformat = chan1->writeformat;
18898 
18899    /* Prepare for taking over the channel */
18900    ast_channel_masquerade(transferee, chan1);
18901 
18902    /* Setup the extensions and such */
18903    ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
18904    ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
18905    transferee->priority = chan1->priority;
18906       
18907    /* We make a clone of the peer channel too, so we can play
18908       back the announcement */
18909 
18910    /* Make formats okay */
18911    transferer->readformat = chan2->readformat;
18912    transferer->writeformat = chan2->writeformat;
18913    if (!ast_strlen_zero(chan2->parkinglot))
18914       ast_string_field_set(transferer, parkinglot, chan2->parkinglot);
18915 
18916    /* Prepare for taking over the channel.  Go ahead and grab this channel
18917     * lock here to avoid a deadlock with callbacks into the channel driver
18918     * that hold the channel lock and want the pvt lock.  */
18919    while (ast_channel_trylock(chan2)) {
18920       struct sip_pvt *pvt = chan2->tech_pvt;
18921       sip_pvt_unlock(pvt);
18922       usleep(1);
18923       sip_pvt_lock(pvt);
18924    }
18925    ast_channel_masquerade(transferer, chan2);
18926    ast_channel_unlock(chan2);
18927 
18928    /* Setup the extensions and such */
18929    ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
18930    ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
18931    transferer->priority = chan2->priority;
18932 
18933    ast_channel_lock(transferer);
18934    if (ast_do_masquerade(transferer)) {
18935       ast_log(LOG_WARNING, "Masquerade failed :(\n");
18936       ast_channel_unlock(transferer);
18937       transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
18938       ast_hangup(transferer);
18939       return -1;
18940    }
18941    ast_channel_unlock(transferer);
18942    if (!transferer || !transferee) {
18943       if (!transferer) { 
18944          ast_debug(1, "No transferer channel, giving up parking\n");
18945       }
18946       if (!transferee) {
18947          ast_debug(1, "No transferee channel, giving up parking\n");
18948       }
18949       return -1;
18950    }
18951    if ((d = ast_calloc(1, sizeof(*d)))) {
18952 
18953       /* Save original request for followup */
18954       copy_request(&d->req, req);
18955       d->chan1 = transferee;  /* Transferee */
18956       d->chan2 = transferer;  /* Transferer */
18957       d->seqno = seqno;
18958       if (ast_pthread_create_detached_background(&th, NULL, sip_park_thread, d) < 0) {
18959          /* Could not start thread */
18960          deinit_req(&d->req);
18961          ast_free(d);   /* We don't need it anymore. If thread is created, d will be free'd
18962                   by sip_park_thread() */
18963          return 0;
18964       }
18965    } 
18966    return -1;
18967 }
18968 
18969 /*! \brief Turn off generator data 
18970    XXX Does this function belong in the SIP channel?
18971 */
18972 static void ast_quiet_chan(struct ast_channel *chan) 
18973 {
18974    if (chan && chan->_state == AST_STATE_UP) {
18975       if (ast_test_flag(chan, AST_FLAG_MOH))
18976          ast_moh_stop(chan);
18977       else if (chan->generatordata)
18978          ast_deactivate_generator(chan);
18979    }
18980 }
18981 
18982 /*! \brief Attempt transfer of SIP call 
18983    This fix for attended transfers on a local PBX */
18984 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
18985 {
18986    int res = 0;
18987    struct ast_channel *peera = NULL,   
18988       *peerb = NULL,
18989       *peerc = NULL,
18990       *peerd = NULL;
18991 
18992 
18993    /* We will try to connect the transferee with the target and hangup
18994       all channels to the transferer */   
18995    ast_debug(4, "Sip transfer:--------------------\n");
18996    if (transferer->chan1)
18997       ast_debug(4, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
18998    else
18999       ast_debug(4, "-- No transferer first channel - odd??? \n");
19000    if (target->chan1)
19001       ast_debug(4, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
19002    else
19003       ast_debug(4, "-- No target first channel ---\n");
19004    if (transferer->chan2)
19005       ast_debug(4, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
19006    else
19007       ast_debug(4, "-- No bridged call to transferee\n");
19008    if (target->chan2)
19009       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)");
19010    else
19011       ast_debug(4, "-- No target second channel ---\n");
19012    ast_debug(4, "-- END Sip transfer:--------------------\n");
19013    if (transferer->chan2) { /* We have a bridge on the transferer's channel */
19014       peera = transferer->chan1; /* Transferer - PBX -> transferee channel * the one we hangup */
19015       peerb = target->chan1;     /* Transferer - PBX -> target channel - This will get lost in masq */
19016       peerc = transferer->chan2; /* Asterisk to Transferee */
19017       peerd = target->chan2;     /* Asterisk to Target */
19018       ast_debug(3, "SIP transfer: Four channels to handle\n");
19019    } else if (target->chan2) {   /* Transferer has no bridge (IVR), but transferee */
19020       peera = target->chan1;     /* Transferer to PBX -> target channel */
19021       peerb = transferer->chan1; /* Transferer to IVR*/
19022       peerc = target->chan2;     /* Asterisk to Target */
19023       peerd = transferer->chan2; /* Nothing */
19024       ast_debug(3, "SIP transfer: Three channels to handle\n");
19025    }
19026 
19027    if (peera && peerb && peerc && (peerb != peerc)) {
19028       ast_quiet_chan(peera);     /* Stop generators */
19029       ast_quiet_chan(peerb);  
19030       ast_quiet_chan(peerc);
19031       if (peerd)
19032          ast_quiet_chan(peerd);
19033 
19034       ast_debug(4, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
19035       if (ast_channel_masquerade(peerb, peerc)) {
19036          ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
19037          res = -1;
19038       } else
19039          ast_debug(4, "SIP transfer: Succeeded to masquerade channels.\n");
19040       return res;
19041    } else {
19042       ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
19043       if (transferer->chan1)
19044          ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
19045       if (target->chan1)
19046          ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
19047       return -1;
19048    }
19049    return 0;
19050 }
19051 
19052 /*! \brief Get tag from packet 
19053  *
19054  * \return Returns the pointer to the provided tag buffer,
19055  *         or NULL if the tag was not found.
19056  */
19057 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
19058 {
19059    const char *thetag;
19060 
19061    if (!tagbuf)
19062       return NULL;
19063    tagbuf[0] = '\0';    /* reset the buffer */
19064    thetag = get_header(req, header);
19065    thetag = strcasestr(thetag, ";tag=");
19066    if (thetag) {
19067       thetag += 5;
19068       ast_copy_string(tagbuf, thetag, tagbufsize);
19069       return strsep(&tagbuf, ";");
19070    }
19071    return NULL;
19072 }
19073 
19074 /*! \brief Handle incoming notifications */
19075 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
19076 {
19077    /* This is mostly a skeleton for future improvements */
19078    /* Mostly created to return proper answers on notifications on outbound REFER's */
19079    int res = 0;
19080    const char *event = get_header(req, "Event");
19081    char *eventid = NULL;
19082    char *sep;
19083 
19084    if( (sep = strchr(event, ';')) ) {  /* XXX bug here - overwriting string ? */
19085       *sep++ = '\0';
19086       eventid = sep;
19087    }
19088    
19089    if (sipdebug)
19090       ast_debug(2, "Got NOTIFY Event: %s\n", event);
19091 
19092    if (!strcmp(event, "refer")) {
19093       /* Save nesting depth for now, since there might be other events we will
19094          support in the future */
19095 
19096       /* Handle REFER notifications */
19097 
19098       char buf[1024];
19099       char *cmd, *code;
19100       int respcode;
19101       int success = TRUE;
19102 
19103       /* EventID for each transfer... EventID is basically the REFER cseq 
19104 
19105        We are getting notifications on a call that we transfered
19106        We should hangup when we are getting a 200 OK in a sipfrag
19107        Check if we have an owner of this event */
19108       
19109       /* Check the content type */
19110       if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
19111          /* We need a sipfrag */
19112          transmit_response(p, "400 Bad request", req);
19113          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19114          return -1;
19115       }
19116 
19117       /* Get the text of the attachment */
19118       if (get_msg_text(buf, sizeof(buf), req, TRUE)) {
19119          ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
19120          transmit_response(p, "400 Bad request", req);
19121          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19122          return -1;
19123       }
19124 
19125       /*
19126       From the RFC...
19127       A minimal, but complete, implementation can respond with a single
19128       NOTIFY containing either the body:
19129          SIP/2.0 100 Trying
19130       
19131       if the subscription is pending, the body:
19132          SIP/2.0 200 OK
19133       if the reference was successful, the body:
19134          SIP/2.0 503 Service Unavailable
19135       if the reference failed, or the body:
19136          SIP/2.0 603 Declined
19137 
19138       if the REFER request was accepted before approval to follow the
19139       reference could be obtained and that approval was subsequently denied
19140       (see Section 2.4.7).
19141       
19142       If there are several REFERs in the same dialog, we need to
19143       match the ID of the event header...
19144       */
19145       ast_debug(3, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
19146       cmd = ast_skip_blanks(buf);
19147       code = cmd;
19148       /* We are at SIP/2.0 */
19149       while(*code && (*code > 32)) {   /* Search white space */
19150          code++;
19151       }
19152       *code++ = '\0';
19153       code = ast_skip_blanks(code);
19154       sep = code;
19155       sep++;
19156       while(*sep && (*sep > 32)) {  /* Search white space */
19157          sep++;
19158       }
19159       *sep++ = '\0';       /* Response string */
19160       respcode = atoi(code);
19161       switch (respcode) {
19162       case 100:   /* Trying: */
19163       case 101:   /* dialog establishment */
19164          /* Don't do anything yet */
19165          break;
19166       case 183:   /* Ringing: */
19167          /* Don't do anything yet */
19168          break;
19169       case 200:   /* OK: The new call is up, hangup this call */
19170          /* Hangup the call that we are replacing */
19171          break;
19172       case 301: /* Moved permenantly */
19173       case 302: /* Moved temporarily */
19174          /* Do we get the header in the packet in this case? */
19175          success = FALSE;
19176          break;
19177       case 503:   /* Service Unavailable: The new call failed */
19178             /* Cancel transfer, continue the call */
19179          success = FALSE;
19180          break;
19181       case 603:   /* Declined: Not accepted */
19182             /* Cancel transfer, continue the current call */
19183          success = FALSE;
19184          break;
19185       }
19186       if (!success) {
19187          ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
19188       }
19189       
19190       /* Confirm that we received this packet */
19191       transmit_response(p, "200 OK", req);
19192    } else if (p->mwi && !strcmp(event, "message-summary")) {
19193       char *c = ast_strdupa(get_body(req, "Voice-Message", ':'));
19194 
19195       if (!ast_strlen_zero(c)) {
19196          char *old = strsep(&c, " ");
19197          char *new = strsep(&old, "/");
19198          struct ast_event *event;
19199 
19200          if ((event = ast_event_new(AST_EVENT_MWI,
19201                      AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, p->mwi->mailbox,
19202                      AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, "SIP_Remote",
19203                      AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(new),
19204                      AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(old),
19205                      AST_EVENT_IE_END))) {
19206             ast_event_queue_and_cache(event);
19207          }
19208       }
19209 
19210       transmit_response(p, "200 OK", req);
19211    } else if (!strcmp(event, "keep-alive")) {
19212        /* Used by Sipura/Linksys for NAT pinhole,
19213         * just confirm that we recieved the packet. */
19214       transmit_response(p, "200 OK", req);
19215    } else {
19216       /* We don't understand this event. */
19217       transmit_response(p, "489 Bad event", req);
19218       res = -1;
19219    }
19220 
19221    if (!p->lastinvite)
19222       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19223 
19224    return res;
19225 }
19226 
19227 /*! \brief Handle incoming OPTIONS request 
19228    An OPTIONS request should be answered like an INVITE from the same UA, including SDP
19229 */
19230 static int handle_request_options(struct sip_pvt *p, struct sip_request *req)
19231 {
19232    int res;
19233 
19234    /*! XXX get_destination assumes we're already authenticated. This means that a request from
19235       a known device (peer) will end up in the wrong context if this is out-of-dialog.
19236       However, we want to handle OPTIONS as light as possible, so we might want to have
19237       a configuration option whether we care or not. Some devices use this for testing
19238       capabilities, which means that we need to match device to answer with proper 
19239       capabilities (including SDP).
19240       \todo Fix handle_request_options device handling with optional authentication
19241          (this needs to be fixed in 1.4 as well)
19242    */
19243 
19244    if (p->lastinvite) {
19245       /* if this is a request in an active dialog, just confirm that the dialog exists. */
19246       transmit_response_with_allow(p, "200 OK", req, 0);
19247       return 0;
19248    }
19249 
19250    res = get_destination(p, req);
19251    build_contact(p);
19252 
19253    if (ast_strlen_zero(p->context))
19254       ast_string_field_set(p, context, sip_cfg.default_context);
19255 
19256    if (ast_shutting_down())
19257       transmit_response_with_allow(p, "503 Unavailable", req, 0);
19258    else if (res < 0)
19259       transmit_response_with_allow(p, "404 Not Found", req, 0);
19260    else 
19261       transmit_response_with_allow(p, "200 OK", req, 0);
19262 
19263    /* Destroy if this OPTIONS was the opening request, but not if
19264       it's in the middle of a normal call flow. */
19265    sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19266 
19267    return res;
19268 }
19269 
19270 /*! \brief Handle the transfer part of INVITE with a replaces: header, 
19271     meaning a target pickup or an attended transfer.
19272     Used only once.
19273    XXX 'ignore' is unused.
19274 
19275    \note this function is called by handle_request_invite(). Four locks
19276    held at the beginning of this function, p, p->owner, p->refer->refer_call->owner...
19277    only p's lock should remain at the end of this function.  p's lock is held by sipsock_read()
19278  */
19279 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *nounlock)
19280 {
19281    int earlyreplace = 0;
19282    int oneleggedreplace = 0;     /* Call with no bridge, propably IVR or voice message */
19283    struct ast_channel *c = p->owner;   /* Our incoming call */
19284    struct ast_channel *replacecall = p->refer->refer_call->owner; /* The channel we're about to take over */
19285    struct ast_channel *targetcall;     /* The bridge to the take-over target */
19286 
19287    struct ast_channel *test;
19288 
19289    /* Check if we're in ring state */
19290    if (replacecall->_state == AST_STATE_RING)
19291       earlyreplace = 1;
19292 
19293    /* Check if we have a bridge */
19294    if (!(targetcall = ast_bridged_channel(replacecall))) {
19295       /* We have no bridge */
19296       if (!earlyreplace) {
19297          ast_debug(2, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
19298          oneleggedreplace = 1;
19299       }
19300    } 
19301    if (targetcall && targetcall->_state == AST_STATE_RINGING)
19302       ast_debug(4, "SIP transfer: Target channel is in ringing state\n");
19303 
19304    if (targetcall) 
19305       ast_debug(4, "SIP transfer: Invite Replace incoming channel should bridge to channel %s while hanging up channel %s\n", targetcall->name, replacecall->name); 
19306    else
19307       ast_debug(4, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name); 
19308 
19309    if (req->ignore) {
19310       ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
19311       /* We should answer something here. If we are here, the
19312          call we are replacing exists, so an accepted 
19313          can't harm */
19314       transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE);
19315       /* Do something more clever here */
19316       if (c) {
19317          *nounlock = 1;
19318          ast_channel_unlock(c);
19319       }
19320       ast_channel_unlock(replacecall);
19321       sip_pvt_unlock(p->refer->refer_call);
19322       return 1;
19323    } 
19324    if (!c) {
19325       /* What to do if no channel ??? */
19326       ast_log(LOG_ERROR, "Unable to create new channel.  Invite/replace failed.\n");
19327       transmit_response_reliable(p, "503 Service Unavailable", req);
19328       append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
19329       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19330       ast_channel_unlock(replacecall);
19331       sip_pvt_unlock(p->refer->refer_call);
19332       return 1;
19333    }
19334    append_history(p, "Xfer", "INVITE/Replace received");
19335    /* We have three channels to play with
19336       channel c: New incoming call
19337       targetcall: Call from PBX to target
19338       p->refer->refer_call: SIP pvt dialog from transferer to pbx.
19339       replacecall: The owner of the previous
19340       We need to masq C into refer_call to connect to 
19341       targetcall;
19342       If we are talking to internal audio stream, target call is null.
19343    */
19344 
19345    /* Fake call progress */
19346    transmit_response(p, "100 Trying", req);
19347    ast_setstate(c, AST_STATE_RING);
19348 
19349    /* Masquerade the new call into the referred call to connect to target call 
19350       Targetcall is not touched by the masq */
19351 
19352    /* Answer the incoming call and set channel to UP state */
19353    transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE);
19354       
19355    ast_setstate(c, AST_STATE_UP);
19356    
19357    /* Stop music on hold and other generators */
19358    ast_quiet_chan(replacecall);
19359    ast_quiet_chan(targetcall);
19360    ast_debug(4, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);
19361 
19362    /* Make sure that the masq does not free our PVT for the old call */
19363    if (! earlyreplace && ! oneleggedreplace )
19364       ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER);  /* Delay hangup */
19365 
19366    /* Prepare the masquerade - if this does not happen, we will be gone */
19367    if(ast_channel_masquerade(replacecall, c))
19368       ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
19369    else
19370       ast_debug(4, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);
19371 
19372    /* C should now be in place of replacecall */
19373    if (ast_do_masquerade(replacecall)) {
19374       ast_log(LOG_WARNING, "Failed to perform masquerade with INVITE replaces\n");
19375    }
19376 
19377    if (earlyreplace || oneleggedreplace ) {
19378       c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
19379    }
19380 
19381    ast_setstate(c, AST_STATE_DOWN);
19382    ast_debug(4, "After transfer:----------------------------\n");
19383    ast_debug(4, " -- C:        %s State %s\n", c->name, ast_state2str(c->_state));
19384    if (replacecall)
19385       ast_debug(4, " -- replacecall:        %s State %s\n", replacecall->name, ast_state2str(replacecall->_state));
19386    if (p->owner) {
19387       ast_debug(4, " -- P->owner: %s State %s\n", p->owner->name, ast_state2str(p->owner->_state));
19388       test = ast_bridged_channel(p->owner);
19389       if (test)
19390          ast_debug(4, " -- Call bridged to P->owner: %s State %s\n", test->name, ast_state2str(test->_state));
19391       else
19392          ast_debug(4, " -- No call bridged to C->owner \n");
19393    } else 
19394       ast_debug(4, " -- No channel yet \n");
19395    ast_debug(4, "End After transfer:----------------------------\n");
19396 
19397    /* unlock sip pvt and owner so hangup can do its thing */
19398    ast_channel_unlock(replacecall);
19399    ast_channel_unlock(c);
19400    sip_pvt_unlock(p->refer->refer_call);
19401    sip_pvt_unlock(p);
19402    *nounlock = 1;
19403 
19404    /* The call should be down with no ast_channel, so hang it up */
19405    c->tech_pvt = dialog_unref(c->tech_pvt, "unref dialog c->tech_pvt");
19406    ast_hangup(c);
19407    sip_pvt_lock(p); /* lock PVT structure again after hangup */
19408 
19409    return 0;
19410 }
19411 
19412 /*! \brief helper routine for sip_uri_cmp
19413  *
19414  * This takes the parameters from two SIP URIs and determines
19415  * if the URIs match. The rules for parameters *suck*. Here's a breakdown
19416  * 1. If a parameter appears in both URIs, then they must have the same value
19417  *    in order for the URIs to match
19418  * 2. If one URI has a user, maddr, ttl, or method parameter, then the other
19419  *    URI must also have that parameter and must have the same value
19420  *    in order for the URIs to match
19421  * 3. All other headers appearing in only one URI are not considered when
19422  *    determining if URIs match
19423  *
19424  * \param input1 Parameters from URI 1
19425  * \param input2 Parameters from URI 2
19426  * \return Return 0 if the URIs' parameters match, 1 if they do not
19427  */
19428 static int sip_uri_params_cmp(const char *input1, const char *input2) 
19429 {
19430    char *params1 = NULL;
19431    char *params2 = NULL;
19432    char *pos1;
19433    char *pos2;
19434    int zerolength1 = 0;
19435    int zerolength2 = 0;
19436    int maddrmatch = 0;
19437    int ttlmatch = 0;
19438    int usermatch = 0;
19439    int methodmatch = 0;
19440 
19441    if (ast_strlen_zero(input1)) {
19442       zerolength1 = 1;
19443    } else {
19444       params1 = ast_strdupa(input1);
19445    }
19446    if (ast_strlen_zero(input2)) {
19447       zerolength2 = 1;
19448    } else {
19449       params2 = ast_strdupa(input2);
19450    }
19451 
19452    /*Quick optimization. If both params are zero-length, then
19453     * they match
19454     */
19455    if (zerolength1 && zerolength2) {
19456       return 0;
19457    }
19458 
19459    pos1 = params1;
19460    while (!ast_strlen_zero(pos1)) {
19461       char *name1 = pos1;
19462       char *value1 = strchr(pos1, '=');
19463       char *semicolon1 = strchr(pos1, ';');
19464       int matched = 0;
19465       if (semicolon1) {
19466          *semicolon1++ = '\0';
19467       }
19468       if (!value1) {
19469          goto fail;
19470       }
19471       *value1++ = '\0';
19472       /* Checkpoint reached. We have the name and value parsed for param1 
19473        * We have to duplicate params2 each time through the second loop
19474        * or else we can't search and replace the semicolons with \0 each
19475        * time
19476        */
19477       pos2 = ast_strdupa(params2);
19478       while (!ast_strlen_zero(pos2)) {
19479          char *name2 = pos2;
19480          char *value2 = strchr(pos2, '=');
19481          char *semicolon2 = strchr(pos2, ';');
19482          if (semicolon2) {
19483             *semicolon2++ = '\0';
19484          }
19485          if (!value2) {
19486             goto fail;
19487          }
19488          *value2++ = '\0';
19489          if (!strcasecmp(name1, name2)) {
19490             if (strcasecmp(value1, value2)) {
19491                goto fail;
19492             } else {
19493                matched = 1;
19494                break;
19495             }
19496          }
19497          pos2 = semicolon2;
19498       }
19499       /* Need to see if the parameter we're looking at is one of the 'must-match' parameters */
19500       if (!strcasecmp(name1, "maddr")) {
19501          if (matched) {
19502             maddrmatch = 1;
19503          } else {
19504             goto fail;
19505          }
19506       } else if (!strcasecmp(name1, "ttl")) {
19507          if (matched) {
19508             ttlmatch = 1;
19509          } else {
19510             goto fail;
19511          }
19512       } else if (!strcasecmp(name1, "user")) {
19513          if (matched) {
19514             usermatch = 1;
19515          } else {
19516             goto fail;
19517          }
19518       } else if (!strcasecmp(name1, "method")) {
19519          if (matched) {
19520             methodmatch = 1;
19521          } else {
19522             goto fail;
19523          }
19524       }
19525       pos1 = semicolon1;
19526    }
19527 
19528    /* We've made it out of that horrible O(m*n) construct and there are no
19529     * failures yet. We're not done yet, though, because params2 could have
19530     * an maddr, ttl, user, or method header and params1 did not.
19531     */
19532    pos2 = params2;
19533    while (!ast_strlen_zero(pos2)) {
19534       char *name2 = pos2;
19535       char *value2 = strchr(pos2, '=');
19536       char *semicolon2 = strchr(pos2, ';');
19537       if (semicolon2) {
19538          *semicolon2++ = '\0';
19539       }
19540       if (!value2) {
19541          goto fail;
19542       }
19543       *value2++ = '\0';
19544       if ((!strcasecmp(name2, "maddr") && !maddrmatch) ||
19545             (!strcasecmp(name2, "ttl") && !ttlmatch) ||
19546             (!strcasecmp(name2, "user") && !usermatch) ||
19547             (!strcasecmp(name2, "method") && !methodmatch)) {
19548          goto fail;
19549       }
19550    }
19551    return 0;
19552 
19553 fail:
19554    return 1;
19555 }
19556 
19557 /*! \brief helper routine for sip_uri_cmp
19558  *
19559  * This takes the "headers" from two SIP URIs and determines
19560  * if the URIs match. The rules for headers is simple. If a header
19561  * appears in one URI, then it must also appear in the other URI. The
19562  * order in which the headers appear does not matter.
19563  *
19564  * \param input1 Headers from URI 1
19565  * \param input2 Headers from URI 2
19566  * \return Return 0 if the URIs' headers match, 1 if they do not
19567  */
19568 static int sip_uri_headers_cmp(const char *input1, const char *input2)
19569 {
19570    char *headers1 = NULL;
19571    char *headers2 = NULL;
19572    int zerolength1 = 0;
19573    int zerolength2 = 0;
19574    int different = 0;
19575    char *header1;
19576 
19577    if (ast_strlen_zero(input1)) {
19578       zerolength1 = 1;
19579    } else {
19580       headers1 = ast_strdupa(input1);
19581    }
19582    
19583    if (ast_strlen_zero(input2)) {
19584       zerolength2 = 1;
19585    } else {
19586       headers2 = ast_strdupa(input2);
19587    }
19588 
19589    if ((zerolength1 && !zerolength2) ||
19590          (zerolength2 && !zerolength1))
19591       return 1;
19592 
19593    if (zerolength1 && zerolength2)
19594       return 0;
19595 
19596    /* At this point, we can definitively state that both inputs are
19597     * not zero-length. First, one more optimization. If the length
19598     * of the headers is not equal, then we definitely have no match
19599     */
19600    if (strlen(headers1) != strlen(headers2)) {
19601       return 1;
19602    }
19603 
19604    for (header1 = strsep(&headers1, "&"); header1; header1 = strsep(&headers1, "&")) {
19605       if (!strcasestr(headers2, header1)) {
19606          different = 1;
19607          break;
19608       }
19609    }
19610 
19611    return different;
19612 }
19613 
19614 static int sip_uri_cmp(const char *input1, const char *input2)
19615 {
19616    char *uri1 = ast_strdupa(input1);
19617    char *uri2 = ast_strdupa(input2);
19618    char *host1;
19619    char *host2;
19620    char *params1;
19621    char *params2;
19622    char *headers1;
19623    char *headers2;
19624 
19625    /* Strip off "sip:" from the URI. We know this is present
19626     * because it was checked back in parse_request()
19627     */
19628    strsep(&uri1, ":");
19629    strsep(&uri2, ":");
19630 
19631    if ((host1 = strchr(uri1, '@'))) {
19632       *host1++ = '\0';
19633    }
19634    if ((host2 = strchr(uri2, '@'))) {
19635       *host2++ = '\0';
19636    }
19637 
19638    /* Check for mismatched username and passwords. This is the
19639     * only case-sensitive comparison of a SIP URI
19640     */
19641    if ((host1 && !host2) ||
19642          (host2 && !host1) ||
19643          (host1 && host2 && strcmp(uri1, uri2))) {
19644       return 1;
19645    }
19646 
19647    if (!host1)
19648       host1 = uri1;
19649    if (!host2)
19650       host2 = uri2;
19651 
19652    /* Strip off the parameters and headers so we can compare
19653     * host and port
19654     */
19655 
19656    if ((params1 = strchr(host1, ';'))) {
19657       *params1++ = '\0';
19658    }
19659    if ((params2 = strchr(host2, ';'))) {
19660       *params2++ = '\0';
19661    }
19662 
19663    /* Headers come after parameters, but there may be headers without
19664     * parameters, thus the S_OR
19665     */
19666    if ((headers1 = strchr(S_OR(params1, host1), '?'))) {
19667       *headers1++ = '\0';
19668    }
19669    if ((headers2 = strchr(S_OR(params2, host2), '?'))) {
19670       *headers2++ = '\0';
19671    }
19672 
19673    /* Now the host/port are properly isolated. We can get by with a string comparison
19674     * because the SIP URI checking rules have some interesting exceptions that make
19675     * this possible. I will note 2 in particular
19676     * 1. hostnames which resolve to the same IP address as well as a hostname and its
19677     *    IP address are not considered a match with SIP URI's.
19678     * 2. If one URI specifies a port and the other does not, then the URIs do not match.
19679     *    This includes if one URI explicitly contains port 5060 and the other implies it
19680     *    by not having a port specified.
19681     */
19682 
19683    if (strcasecmp(host1, host2)) {
19684       return 1;
19685    }
19686 
19687    /* Headers have easier rules to follow, so do those first */
19688    if (sip_uri_headers_cmp(headers1, headers2)) {
19689       return 1;
19690    }
19691 
19692    /* And now the parameters. Ugh */
19693    return sip_uri_params_cmp(params1, params2);
19694 }
19695 
19696 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context)
19697 {
19698    struct ast_str *str = ast_str_alloca(AST_MAX_EXTENSION + AST_MAX_CONTEXT + 2);
19699    struct ast_app *pickup = pbx_findapp("Pickup");
19700 
19701    if (!pickup) {
19702       ast_log(LOG_ERROR, "Unable to perform pickup: Application 'Pickup' not loaded (app_directed_pickup.so).\n");
19703       return -1;
19704    }
19705 
19706    ast_str_set(&str, 0, "%s@%s", extension, sip_cfg.notifycid == IGNORE_CONTEXT ? "PICKUPMARK" : context);
19707 
19708    ast_debug(2, "About to call Pickup(%s)\n", str->str);
19709 
19710    /* There is no point in capturing the return value since pickup_exec
19711       doesn't return anything meaningful unless the passed data is an empty
19712       string (which in our case it will not be) */
19713    pbx_exec(channel, pickup, str->str);
19714 
19715    return 0;
19716 }
19717 
19718 /*! \brief Called to deny a T38 reinvite if the core does not respond to our request */
19719 static int sip_t38_abort(const void *data)
19720 {
19721    struct sip_pvt *p = (struct sip_pvt *) data;
19722 
19723    sip_pvt_lock(p);
19724    /* an application may have taken ownership of the T.38 negotiation on this
19725     * channel while we were waiting to grab the lock... if it did, the scheduler
19726     * id will have been reset to -1, which is our indication that we do *not*
19727     * want to abort the negotiation process
19728     */
19729    if (p->t38id != -1) {
19730       change_t38_state(p, T38_DISABLED);
19731       transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
19732       p->t38id = -1;
19733       dialog_unref(p, "unref the dialog ptr from sip_t38_abort, because it held a dialog ptr");
19734    }
19735    sip_pvt_unlock(p);
19736    return 0;
19737 }
19738 
19739 /*! \brief Handle incoming INVITE request
19740 \note    If the INVITE has a Replaces header, it is part of an
19741  * attended transfer. If so, we do not go through the dial
19742  * plan but tries to find the active call and masquerade
19743  * into it 
19744  */
19745 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)
19746 {
19747    int res = 1;
19748    int gotdest;
19749    const char *p_replaces;
19750    char *replace_id = NULL;
19751    int refer_locked = 0;
19752    const char *required;
19753    unsigned int required_profile = 0;
19754    struct ast_channel *c = NULL;    /* New channel */
19755    int reinvite = 0;
19756    int rtn;
19757 
19758    const char *p_uac_se_hdr;       /* UAC's Session-Expires header string                      */
19759    const char *p_uac_min_se;       /* UAC's requested Min-SE interval (char string)            */
19760    int uac_max_se = -1;            /* UAC's Session-Expires in integer format                  */
19761    int uac_min_se = -1;            /* UAC's Min-SE in integer format                           */
19762    int st_active = FALSE;          /* Session-Timer on/off boolean                             */
19763    int st_interval = 0;            /* Session-Timer negotiated refresh interval                */
19764    enum st_refresher st_ref;       /* Session-Timer session refresher                          */
19765    int dlg_min_se = -1;
19766    struct {
19767       char exten[AST_MAX_EXTENSION];
19768       char context[AST_MAX_CONTEXT];
19769    } pickup = {
19770       .exten = "",
19771    };
19772    st_ref = SESSION_TIMER_REFRESHER_AUTO;
19773 
19774    /* Find out what they support */
19775    if (!p->sipoptions) {
19776       const char *supported = get_header(req, "Supported");
19777       if (!ast_strlen_zero(supported))
19778          parse_sip_options(p, supported);
19779    }
19780 
19781    /* Find out what they require */
19782    required = get_header(req, "Require");
19783    if (!ast_strlen_zero(required)) {
19784       required_profile = parse_sip_options(NULL, required);
19785       if (required_profile && !(required_profile & (SIP_OPT_REPLACES | SIP_OPT_TIMER))) {
19786          /* At this point we only support REPLACES and Session-Timer */
19787          transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, required);
19788          ast_log(LOG_WARNING, "Received SIP INVITE with unsupported required extension: %s\n", required);
19789          p->invitestate = INV_COMPLETED;
19790          if (!p->lastinvite)
19791             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19792          res = -1;
19793          goto request_invite_cleanup;
19794       }
19795    }
19796 
19797    /* The option tags may be present in Supported: or Require: headers.
19798    Include the Require: option tags for further processing as well */
19799    p->sipoptions |= required_profile;
19800    p->reqsipoptions = required_profile;
19801 
19802    /* Check if this is a loop */
19803    if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && p->owner && (p->invitestate != INV_TERMINATED && p->invitestate != INV_CONFIRMED)) {
19804       /* This is a call to ourself.  Send ourselves an error code and stop
19805          processing immediately, as SIP really has no good mechanism for
19806          being able to call yourself */
19807       /* If pedantic is on, we need to check the tags. If they're different, this is
19808          in fact a forked call through a SIP proxy somewhere. */
19809       int different;
19810       char *initial_rlPart2 = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
19811       char *this_rlPart2 = REQ_OFFSET_TO_STR(req, rlPart2);
19812       if (sip_cfg.pedanticsipchecking)
19813          different = sip_uri_cmp(initial_rlPart2, this_rlPart2);
19814       else
19815          different = strcmp(initial_rlPart2, this_rlPart2);
19816       if (!different) {
19817          transmit_response(p, "482 Loop Detected", req);
19818          p->invitestate = INV_COMPLETED;
19819          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19820          res = 0;
19821          goto request_invite_cleanup;
19822       } else {
19823          /*! This is a spiral. What we need to do is to just change the outgoing INVITE
19824           * so that it now routes to the new Request URI. Since we created the INVITE ourselves
19825           * that should be all we need to do.
19826           * 
19827           * \todo XXX This needs to be reviewed.  YOu don't change the request URI really, you route the packet
19828           * correctly instead...
19829           */
19830          char *uri = ast_strdupa(this_rlPart2);
19831          char *at = strchr(uri, '@');
19832          char *peerorhost;
19833          ast_debug(2, "Potential spiral detected. Original RURI was %s, new RURI is %s\n", initial_rlPart2, this_rlPart2);
19834          transmit_response(p, "100 Trying", req);
19835          if (at) {
19836             *at = '\0';
19837          }
19838          /* Parse out "sip:" */
19839          if ((peerorhost = strchr(uri, ':'))) {
19840             *peerorhost++ = '\0';
19841          }
19842          ast_string_field_set(p, theirtag, NULL);
19843          /* Treat this as if there were a call forward instead...
19844           */
19845          ast_string_field_set(p->owner, call_forward, peerorhost);
19846          ast_queue_control(p->owner, AST_CONTROL_BUSY);
19847          res = 0;
19848          goto request_invite_cleanup;
19849       }
19850    }
19851 
19852    if (!req->ignore && p->pendinginvite) {
19853       if (!ast_test_flag(&p->flags[0], SIP_OUTGOING) && (p->invitestate == INV_COMPLETED || p->invitestate == INV_TERMINATED)) {
19854          /* What do these circumstances mean? We have received an INVITE for an "incoming" dialog for which we
19855           * have sent a final response. We have not yet received an ACK, though (which is why p->pendinginvite is non-zero).
19856           * We also know that the INVITE is not a retransmission, because otherwise the "ignore" flag would be set.
19857           * This means that either we are receiving a reinvite for a terminated dialog, or we are receiving an INVITE with
19858           * credentials based on one we challenged earlier.
19859           *
19860           * The action to take in either case is to treat the INVITE as though it contains an implicit ACK for the previous
19861           * transaction. Calling __sip_ack will take care of this by clearing the p->pendinginvite and removing the response
19862           * from the previous transaction from the list of outstanding packets.
19863           */
19864          __sip_ack(p, p->pendinginvite, 1, 0);
19865       } else {
19866          /* We already have a pending invite. Sorry. You are on hold. */
19867          p->glareinvite = seqno;     /* must hold on to this seqno to process ack and retransmit correctly */
19868          if (p->rtp && find_sdp(req)) {
19869             struct sockaddr_in sin;
19870             if (get_ip_and_port_from_sdp(req, SDP_AUDIO, &sin)) {
19871                ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Audio may not work properly on this call.\n");
19872             } else {
19873                ast_rtp_set_alt_peer(p->rtp, &sin);
19874             }
19875             if (p->vrtp) {
19876                if (get_ip_and_port_from_sdp(req, SDP_VIDEO, &sin)) {
19877                   ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Video may not work properly on this call.\n");
19878                } else {
19879                   ast_rtp_set_alt_peer(p->vrtp, &sin);
19880                }
19881             }
19882          }
19883          transmit_response_reliable(p, "491 Request Pending", req);
19884          ast_debug(1, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
19885          /* Don't destroy dialog here */
19886          res = 0;
19887          goto request_invite_cleanup;
19888       }
19889    }
19890 
19891    p_replaces = get_header(req, "Replaces");
19892    if (!ast_strlen_zero(p_replaces)) {
19893       /* We have a replaces header */
19894       char *ptr;
19895       char *fromtag = NULL;
19896       char *totag = NULL;
19897       char *start, *to;
19898       int error = 0;
19899 
19900       if (p->owner) {
19901          ast_debug(3, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
19902          transmit_response_reliable(p, "400 Bad request", req);   /* The best way to not not accept the transfer */
19903          /* Do not destroy existing call */
19904          res = -1;
19905          goto request_invite_cleanup;
19906       }
19907 
19908       if (sipdebug)
19909          ast_debug(3, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
19910       /* Create a buffer we can manipulate */
19911       replace_id = ast_strdupa(p_replaces);
19912       ast_uri_decode(replace_id);
19913 
19914       if (!p->refer && !sip_refer_allocate(p)) {
19915          transmit_response_reliable(p, "500 Server Internal Error", req);
19916          append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
19917          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19918          p->invitestate = INV_COMPLETED;
19919          res = -1;
19920          goto request_invite_cleanup;
19921       }
19922 
19923       /*  Todo: (When we find phones that support this)
19924          if the replaces header contains ";early-only"
19925          we can only replace the call in early
19926          stage, not after it's up.
19927 
19928          If it's not in early mode, 486 Busy.
19929       */
19930 
19931       /* Skip leading whitespace */
19932       replace_id = ast_skip_blanks(replace_id);
19933 
19934       start = replace_id;
19935       while ( (ptr = strsep(&start, ";")) ) {
19936          ptr = ast_skip_blanks(ptr); /* XXX maybe unnecessary ? */
19937          if ( (to = strcasestr(ptr, "to-tag=") ) )
19938             totag = to + 7;   /* skip the keyword */
19939          else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
19940             fromtag = to + 9; /* skip the keyword */
19941             fromtag = strsep(&fromtag, "&"); /* trim what ? */
19942          }
19943       }
19944 
19945       if (sipdebug)
19946          ast_debug(4, "Invite/replaces: Will use Replace-Call-ID : %s Fromtag: %s Totag: %s\n",
19947                  replace_id,
19948                  fromtag ? fromtag : "<no from tag>",
19949                  totag ? totag : "<no to tag>");
19950 
19951       /* Try to find call that we are replacing.
19952          If we have a Replaces header, we need to cancel that call if we succeed with this call.
19953          First we cheat a little and look for a magic call-id from phones that support
19954          dialog-info+xml so we can do technology independent pickup... */
19955       if (strncmp(replace_id, "pickup-", 7) == 0) {
19956          struct sip_pvt *subscription = NULL;
19957          replace_id += 7; /* Worst case we are looking at \0 */
19958 
19959          if ((subscription = get_sip_pvt_byid_locked(replace_id, NULL, NULL)) == NULL) {
19960             ast_log(LOG_NOTICE, "Unable to find subscription with call-id: %s\n", replace_id);
19961             transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
19962             error = 1;
19963          } else {
19964             ast_log(LOG_NOTICE, "Trying to pick up %s@%s\n", subscription->exten, subscription->context);
19965             ast_copy_string(pickup.exten, subscription->exten, sizeof(pickup.exten));
19966             ast_copy_string(pickup.context, subscription->context, sizeof(pickup.context));
19967             sip_pvt_unlock(subscription);
19968             if (subscription->owner) {
19969                ast_channel_unlock(subscription->owner);
19970             }
19971          }
19972       }
19973 
19974       /* This locks both refer_call pvt and refer_call pvt's owner!!!*/
19975       if (!error && ast_strlen_zero(pickup.exten) && (p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
19976          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
19977          transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
19978          error = 1;
19979       } else {
19980          refer_locked = 1;
19981       }
19982 
19983       /* The matched call is the call from the transferer to Asterisk .
19984          We want to bridge the bridged part of the call to the 
19985          incoming invite, thus taking over the refered call */
19986 
19987       if (p->refer->refer_call == p) {
19988          ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
19989          p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
19990          transmit_response_reliable(p, "400 Bad request", req);   /* The best way to not not accept the transfer */
19991          error = 1;
19992       }
19993 
19994       if (!error && ast_strlen_zero(pickup.exten) && !p->refer->refer_call->owner) {
19995          /* Oops, someting wrong anyway, no owner, no call */
19996          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
19997          /* Check for better return code */
19998          transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replace)", req);
19999          error = 1;
20000       }
20001 
20002       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) {
20003          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
20004          transmit_response_reliable(p, "603 Declined (Replaces)", req);
20005          error = 1;
20006       }
20007 
20008       if (error) {   /* Give up this dialog */
20009          append_history(p, "Xfer", "INVITE/Replace Failed.");
20010          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20011          sip_pvt_unlock(p);
20012          if (p->refer->refer_call) {
20013             sip_pvt_unlock(p->refer->refer_call);
20014             if (p->refer->refer_call->owner) {
20015                ast_channel_unlock(p->refer->refer_call->owner);
20016             }
20017          }
20018          refer_locked = 0;
20019          p->invitestate = INV_COMPLETED;
20020          res = -1;
20021          goto request_invite_cleanup;
20022       }
20023    }
20024 
20025    /* Check if this is an INVITE that sets up a new dialog or
20026       a re-invite in an existing dialog */
20027 
20028    if (!req->ignore) {
20029       int newcall = (p->initreq.headers ? TRUE : FALSE);
20030 
20031       if (sip_cancel_destroy(p))
20032          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
20033       /* This also counts as a pending invite */
20034       p->pendinginvite = seqno;
20035       check_via(p, req);
20036 
20037       copy_request(&p->initreq, req);     /* Save this INVITE as the transaction basis */
20038       if (sipdebug)
20039          ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
20040       if (!p->owner) {  /* Not a re-invite */
20041          if (debug)
20042             ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
20043          if (newcall)
20044             append_history(p, "Invite", "New call: %s", p->callid);
20045          parse_ok_contact(p, req);
20046       } else { /* Re-invite on existing call */
20047          ast_clear_flag(&p->flags[0], SIP_OUTGOING);  /* This is now an inbound dialog */
20048          /* Handle SDP here if we already have an owner */
20049          if (find_sdp(req)) {
20050             if (process_sdp(p, req, SDP_T38_INITIATE)) {
20051                transmit_response_reliable(p, "488 Not acceptable here", req);
20052                if (!p->lastinvite)
20053                   sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20054                res = -1;
20055                goto request_invite_cleanup;
20056             }
20057             ast_queue_control(p->owner, AST_CONTROL_SRCUPDATE);
20058          } else {
20059             p->jointcapability = p->capability;
20060             ast_debug(1, "Hm....  No sdp for the moment\n");
20061          }
20062          if (p->do_history) /* This is a response, note what it was for */
20063             append_history(p, "ReInv", "Re-invite received");
20064       }
20065    } else if (debug)
20066       ast_verbose("Ignoring this INVITE request\n");
20067 
20068    if (!p->lastinvite && !req->ignore && !p->owner) {
20069       /* This is a new invite */
20070       /* Handle authentication if this is our first invite */
20071       res = check_user(p, req, SIP_INVITE, e, XMIT_RELIABLE, sin);
20072       if (res == AUTH_CHALLENGE_SENT) {
20073          p->invitestate = INV_COMPLETED;     /* Needs to restart in another INVITE transaction */
20074          res = 0;
20075          goto request_invite_cleanup;
20076       }
20077       if (res < 0) { /* Something failed in authentication */
20078          if (res == AUTH_FAKE_AUTH) {
20079             ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
20080             transmit_fake_auth_response(p, SIP_INVITE, req, XMIT_RELIABLE);
20081          } else {
20082             ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
20083             transmit_response_reliable(p, "403 Forbidden", req);
20084          }
20085          p->invitestate = INV_COMPLETED;
20086          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20087          ast_string_field_set(p, theirtag, NULL);
20088          res = 0;
20089          goto request_invite_cleanup;
20090       }
20091 
20092       /* If T38 is needed but not present, then make it magically appear */
20093       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && !p->udptl) {
20094          if ((p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr))) {
20095             p->t38_maxdatagram = global_t38_maxdatagram;
20096             set_t38_capabilities(p);
20097          } else {
20098             /* udptl creation failed, T38 can not be supported on this dialog */
20099             ast_debug(1, "UDPTL creation failed on dialog.\n");
20100             ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
20101          }
20102       }
20103 
20104       /* We have a succesful authentication, process the SDP portion if there is one */
20105       if (find_sdp(req)) {
20106          if (process_sdp(p, req, SDP_T38_INITIATE)) {
20107             /* Unacceptable codecs */
20108             transmit_response_reliable(p, "488 Not acceptable here", req);
20109             p->invitestate = INV_COMPLETED;
20110             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20111             ast_debug(1, "No compatible codecs for this SIP call.\n");
20112             res = -1;
20113             goto request_invite_cleanup;
20114          }
20115       } else { /* No SDP in invite, call control session */
20116          p->jointcapability = p->capability;
20117          ast_debug(2, "No SDP in Invite, third party call control\n");
20118       }
20119 
20120       /* Queue NULL frame to prod ast_rtp_bridge if appropriate */
20121       /* This seems redundant ... see !p-owner above */
20122       if (p->owner)
20123          ast_queue_frame(p->owner, &ast_null_frame);
20124 
20125 
20126       /* Initialize the context if it hasn't been already */
20127       if (ast_strlen_zero(p->context))
20128          ast_string_field_set(p, context, sip_cfg.default_context);
20129 
20130 
20131       /* Check number of concurrent calls -vs- incoming limit HERE */
20132       ast_debug(1, "Checking SIP call limits for device %s\n", p->username);
20133       if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
20134          if (res < 0) {
20135             ast_log(LOG_NOTICE, "Failed to place call for device %s, too many calls\n", p->username);
20136             transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
20137             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20138             p->invitestate = INV_COMPLETED;
20139          }
20140          res = 0;
20141          goto request_invite_cleanup;
20142       }
20143       gotdest = get_destination(p, NULL); /* Get destination right away */
20144       get_rdnis(p, NULL);        /* Get redirect information */
20145       extract_uri(p, req);       /* Get the Contact URI */
20146       build_contact(p);       /* Build our contact header */
20147 
20148       if (p->rtp) {
20149          ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
20150          ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
20151       }
20152 
20153       if (!replace_id && gotdest) { /* No matching extension found */
20154          if (gotdest == 1 && ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP))
20155             transmit_response_reliable(p, "484 Address Incomplete", req);
20156          else {
20157             char *decoded_exten = ast_strdupa(p->exten);
20158 
20159             transmit_response_reliable(p, "404 Not Found", req);
20160             ast_uri_decode(decoded_exten);
20161             ast_log(LOG_NOTICE, "Call from '%s' to extension"
20162                " '%s' rejected because extension not found in context '%s'.\n",
20163                S_OR(p->username, p->peername), decoded_exten, p->context);
20164          }
20165          p->invitestate = INV_COMPLETED;
20166          update_call_counter(p, DEC_CALL_LIMIT);
20167          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20168          res = 0;
20169          goto request_invite_cleanup;
20170       } else {
20171 
20172          /* If no extension was specified, use the s one */
20173          /* Basically for calling to IP/Host name only */
20174          if (ast_strlen_zero(p->exten))
20175             ast_string_field_set(p, exten, "s");
20176          /* Initialize our tag */
20177 
20178          make_our_tag(p->tag, sizeof(p->tag));
20179          /* First invitation - create the channel */
20180          c = sip_new(p, AST_STATE_DOWN, S_OR(p->peername, NULL));
20181          *recount = 1;
20182 
20183          /* Save Record-Route for any later requests we make on this dialogue */
20184          build_route(p, req, 0);
20185 
20186          if (c) {
20187             /* Pre-lock the call */
20188             ast_channel_lock(c);
20189          }
20190       }
20191    } else {
20192       if (sipdebug) {
20193          if (!req->ignore)
20194             ast_debug(2, "Got a SIP re-invite for call %s\n", p->callid);
20195          else
20196             ast_debug(2, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
20197       }
20198       if (!req->ignore)
20199          reinvite = 1;
20200       c = p->owner;
20201    }
20202 
20203    /* Session-Timers */
20204    if (p->sipoptions & SIP_OPT_TIMER) {
20205       /* The UAC has requested session-timers for this session. Negotiate
20206       the session refresh interval and who will be the refresher */
20207       ast_debug(2, "Incoming INVITE with 'timer' option enabled\n");
20208 
20209       /* Allocate Session-Timers struct w/in the dialog */
20210       if (!p->stimer)
20211          sip_st_alloc(p);
20212 
20213       /* Parse the Session-Expires header */
20214       p_uac_se_hdr = get_header(req, "Session-Expires");
20215       if (!ast_strlen_zero(p_uac_se_hdr)) {
20216          rtn = parse_session_expires(p_uac_se_hdr, &uac_max_se, &st_ref);
20217          if (rtn != 0) {
20218             transmit_response_reliable(p, "400 Session-Expires Invalid Syntax", req);
20219             p->invitestate = INV_COMPLETED;
20220             if (!p->lastinvite) {
20221                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20222             }
20223             res = -1;
20224             goto request_invite_cleanup;
20225          }
20226       }
20227 
20228       /* Parse the Min-SE header */
20229       p_uac_min_se = get_header(req, "Min-SE");
20230       if (!ast_strlen_zero(p_uac_min_se)) {
20231          rtn = parse_minse(p_uac_min_se, &uac_min_se); 
20232          if (rtn != 0) {
20233             transmit_response_reliable(p, "400 Min-SE Invalid Syntax", req);
20234             p->invitestate = INV_COMPLETED;
20235             if (!p->lastinvite) {
20236                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20237             }
20238             res = -1;
20239             goto request_invite_cleanup;
20240          }
20241       }
20242 
20243       dlg_min_se = st_get_se(p, FALSE);
20244       switch (st_get_mode(p)) {
20245       case SESSION_TIMER_MODE_ACCEPT:
20246       case SESSION_TIMER_MODE_ORIGINATE:
20247          if (uac_max_se > 0 && uac_max_se < dlg_min_se) {
20248             transmit_response_with_minse(p, "422 Session Interval Too Small", req, dlg_min_se);
20249             p->invitestate = INV_COMPLETED;
20250             if (!p->lastinvite) {
20251                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20252             }
20253             res = -1;
20254             goto request_invite_cleanup;
20255          }
20256 
20257          p->stimer->st_active_peer_ua = TRUE;
20258          st_active = TRUE;
20259          if (st_ref == SESSION_TIMER_REFRESHER_AUTO) {
20260             st_ref = st_get_refresher(p);
20261          }
20262 
20263          if (uac_max_se > 0) {
20264             int dlg_max_se = st_get_se(p, TRUE);
20265             if (dlg_max_se >= uac_min_se) {
20266                st_interval = (uac_max_se < dlg_max_se) ? uac_max_se : dlg_max_se;
20267             } else {
20268                st_interval = uac_max_se;
20269             }
20270          } else {
20271             /* Set to default max value */
20272             st_interval = global_max_se;
20273          }
20274          break;
20275 
20276       case SESSION_TIMER_MODE_REFUSE:
20277          if (p->reqsipoptions & SIP_OPT_TIMER) {
20278             transmit_response_with_unsupported(p, "420 Option Disabled", req, required);
20279             ast_log(LOG_WARNING, "Received SIP INVITE with supported but disabled option: %s\n", required);
20280             p->invitestate = INV_COMPLETED;
20281             if (!p->lastinvite) {
20282                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20283             }
20284             res = -1;
20285             goto request_invite_cleanup;
20286          }
20287          break;
20288 
20289       default:
20290          ast_log(LOG_ERROR, "Internal Error %d at %s:%d\n", st_get_mode(p), __FILE__, __LINE__);
20291          break;
20292       }
20293    } else {
20294       /* The UAC did not request session-timers.  Asterisk (UAS), will now decide
20295       (based on session-timer-mode in sip.conf) whether to run session-timers for
20296       this session or not. */
20297       switch (st_get_mode(p)) {
20298       case SESSION_TIMER_MODE_ORIGINATE:
20299          st_active = TRUE;
20300          st_interval = st_get_se(p, TRUE);
20301          st_ref = SESSION_TIMER_REFRESHER_UAS;
20302          p->stimer->st_active_peer_ua = FALSE;
20303          break;
20304 
20305       default:
20306          break;
20307       }
20308    }
20309 
20310    if (reinvite == 0) {
20311       /* Session-Timers: Start session refresh timer based on negotiation/config */
20312       if (st_active == TRUE) {
20313          p->stimer->st_active   = TRUE;
20314          p->stimer->st_interval = st_interval;
20315          p->stimer->st_ref      = st_ref;
20316          start_session_timer(p);
20317       }
20318    } else {
20319       if (p->stimer->st_active == TRUE) {
20320          /* Session-Timers:  A re-invite request sent within a dialog will serve as 
20321          a refresh request, no matter whether the re-invite was sent for refreshing 
20322          the session or modifying it.*/
20323          ast_debug (2, "Restarting session-timers on a refresh - %s\n", p->callid);
20324 
20325          /* The UAC may be adjusting the session-timers mid-session */
20326          if (st_interval > 0) {
20327             p->stimer->st_interval = st_interval;
20328             p->stimer->st_ref      = st_ref;
20329          }
20330 
20331          restart_session_timer(p);
20332          if (p->stimer->st_expirys > 0) {
20333             p->stimer->st_expirys--;
20334          }
20335       }
20336    }
20337 
20338    if (!req->ignore && p)
20339       p->lastinvite = seqno;
20340 
20341    if (replace_id) { /* Attended transfer or call pickup - we're the target */
20342       if (!ast_strlen_zero(pickup.exten)) {
20343          append_history(p, "Xfer", "INVITE/Replace received");
20344 
20345          /* Let the caller know we're giving it a shot */
20346          transmit_response(p, "100 Trying", req);
20347          p->invitestate = INV_PROCEEDING;
20348          ast_setstate(c, AST_STATE_RING);
20349 
20350          /* Do the pickup itself */
20351          ast_channel_unlock(c);
20352          *nounlock = 1;
20353          do_magic_pickup(c, pickup.exten, pickup.context);
20354 
20355          /* Now we're either masqueraded or we failed to pickup, in either case we... */
20356          sip_pvt_unlock(p);
20357          ast_hangup(c);
20358          sip_pvt_lock(p);
20359 
20360          res = 0;
20361          goto request_invite_cleanup;
20362       } else {
20363          /* Go and take over the target call */
20364          if (sipdebug)
20365             ast_debug(4, "Sending this call to the invite/replcaes handler %s\n", p->callid);
20366          res = handle_invite_replaces(p, req, debug, seqno, sin, nounlock);
20367          refer_locked = 0;
20368          goto request_invite_cleanup;
20369       }
20370    }
20371 
20372 
20373    if (c) { /* We have a call  -either a new call or an old one (RE-INVITE) */
20374       enum ast_channel_state c_state = c->_state;
20375 
20376       if (c_state != AST_STATE_UP && reinvite &&
20377          (p->invitestate == INV_TERMINATED || p->invitestate == INV_CONFIRMED)) {
20378          /* If these conditions are true, and the channel is still in the 'ringing'
20379           * state, then this likely means that we have a situation where the initial
20380           * INVITE transaction has completed *but* the channel's state has not yet been
20381           * changed to UP. The reason this could happen is if the reinvite is received
20382           * on the SIP socket prior to an application calling ast_read on this channel
20383           * to read the answer frame we earlier queued on it. In this case, the reinvite
20384           * is completely legitimate so we need to handle this the same as if the channel 
20385           * were already UP. Thus we are purposely falling through to the AST_STATE_UP case.
20386           */
20387          c_state = AST_STATE_UP;
20388       }
20389 
20390       switch(c_state) {
20391       case AST_STATE_DOWN:
20392          ast_debug(2, "%s: New call is still down.... Trying... \n", c->name);
20393          transmit_provisional_response(p, "100 Trying", req, 0);
20394          p->invitestate = INV_PROCEEDING;
20395          ast_setstate(c, AST_STATE_RING);
20396          if (strcmp(p->exten, ast_pickup_ext())) { /* Call to extension -start pbx on this call */
20397             enum ast_pbx_result result;
20398 
20399             result = ast_pbx_start(c);
20400 
20401             switch(result) {
20402             case AST_PBX_FAILED:
20403                ast_log(LOG_WARNING, "Failed to start PBX :(\n");
20404                p->invitestate = INV_COMPLETED;
20405                transmit_response_reliable(p, "503 Unavailable", req);
20406                break;
20407             case AST_PBX_CALL_LIMIT:
20408                ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
20409                p->invitestate = INV_COMPLETED;
20410                transmit_response_reliable(p, "480 Temporarily Unavailable", req);
20411                break;
20412             case AST_PBX_SUCCESS:
20413                /* nothing to do */
20414                break;
20415             }
20416 
20417             if (result) {
20418 
20419                /* Unlock locks so ast_hangup can do its magic */
20420                ast_channel_unlock(c);
20421                sip_pvt_unlock(p);
20422                ast_hangup(c);
20423                sip_pvt_lock(p);
20424                c = NULL;
20425             }
20426          } else { /* Pickup call in call group */
20427             ast_channel_unlock(c);
20428             *nounlock = 1;
20429             if (ast_pickup_call(c)) {
20430                ast_log(LOG_NOTICE, "Nothing to pick up for %s\n", p->callid);
20431                transmit_response_reliable(p, "503 Unavailable", req);
20432                sip_alreadygone(p);
20433                /* Unlock locks so ast_hangup can do its magic */
20434                sip_pvt_unlock(p);
20435                c->hangupcause = AST_CAUSE_CALL_REJECTED;
20436             } else {
20437                sip_pvt_unlock(p);
20438                ast_setstate(c, AST_STATE_DOWN);
20439                c->hangupcause = AST_CAUSE_NORMAL_CLEARING;
20440             }
20441             p->invitestate = INV_COMPLETED;
20442             ast_hangup(c);
20443             sip_pvt_lock(p);
20444             c = NULL;
20445          }
20446          break;
20447       case AST_STATE_RING:
20448          transmit_provisional_response(p, "100 Trying", req, 0);
20449          p->invitestate = INV_PROCEEDING;
20450          break;
20451       case AST_STATE_RINGING:
20452          transmit_provisional_response(p, "180 Ringing", req, 0);
20453          p->invitestate = INV_PROCEEDING;
20454          break;
20455       case AST_STATE_UP:
20456          ast_debug(2, "%s: This call is UP.... \n", c->name);
20457 
20458          transmit_response(p, "100 Trying", req);
20459 
20460          if (p->t38.state == T38_PEER_REINVITE) {
20461             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."));
20462          } else if (p->t38.state == T38_ENABLED) {
20463             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
20464             transmit_response_with_t38_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ?  XMIT_UNRELIABLE : XMIT_CRITICAL)));
20465          } else if (p->t38.state == T38_DISABLED) {
20466             /* If this is not a re-invite or something to ignore - it's critical */
20467             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
20468             transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ?  XMIT_UNRELIABLE : XMIT_CRITICAL)), p->session_modify == TRUE ? FALSE:TRUE); 
20469          }
20470 
20471          p->invitestate = INV_TERMINATED;
20472          break;
20473       default:
20474          ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
20475          transmit_response(p, "100 Trying", req);
20476          break;
20477       }
20478    } else {
20479       if (p && (p->autokillid == -1)) {
20480          const char *msg;
20481 
20482          if (!p->jointcapability)
20483             msg = "488 Not Acceptable Here (codec error)";
20484          else {
20485             ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
20486             msg = "503 Unavailable";
20487          }
20488          transmit_response_reliable(p, msg, req);
20489          p->invitestate = INV_COMPLETED;
20490          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20491       }
20492    }
20493 
20494 request_invite_cleanup:
20495 
20496    if (refer_locked && p->refer && p->refer->refer_call) {
20497       sip_pvt_unlock(p->refer->refer_call);
20498       if (p->refer->refer_call->owner) {
20499          ast_channel_unlock(p->refer->refer_call->owner);
20500       }
20501    }
20502 
20503    return res;
20504 }
20505 
20506 /*! \brief  Find all call legs and bridge transferee with target 
20507  * called from handle_request_refer */
20508 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno)
20509 {
20510    struct sip_dual target;    /* Chan 1: Call from tranferer to Asterisk */
20511                /* Chan 2: Call from Asterisk to target */
20512    int res = 0;
20513    struct sip_pvt *targetcall_pvt;
20514 
20515    /* Check if the call ID of the replaces header does exist locally */
20516    if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag, 
20517       transferer->refer->replaces_callid_fromtag))) {
20518       if (transferer->refer->localtransfer) {
20519          /* We did not find the refered call. Sorry, can't accept then */
20520          transmit_response(transferer, "202 Accepted", req);
20521          /* Let's fake a response from someone else in order
20522             to follow the standard */
20523          transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
20524          append_history(transferer, "Xfer", "Refer failed");
20525          ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);  
20526          transferer->refer->status = REFER_FAILED;
20527          return -1;
20528       }
20529       /* Fall through for remote transfers that we did not find locally */
20530       ast_debug(3, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
20531       return 0;
20532    }
20533 
20534    /* Ok, we can accept this transfer */
20535    transmit_response(transferer, "202 Accepted", req);
20536    append_history(transferer, "Xfer", "Refer accepted");
20537    if (!targetcall_pvt->owner) { /* No active channel */
20538       ast_debug(4, "SIP attended transfer: Error: No owner of target call\n");
20539       /* Cancel transfer */
20540       transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
20541       append_history(transferer, "Xfer", "Refer failed");
20542       ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
20543       transferer->refer->status = REFER_FAILED;
20544       sip_pvt_unlock(targetcall_pvt);
20545       if (targetcall_pvt)
20546          ao2_t_ref(targetcall_pvt, -1, "Drop targetcall_pvt pointer");
20547       return -1;
20548    }
20549 
20550    /* We have a channel, find the bridge */
20551    target.chan1 = targetcall_pvt->owner;           /* Transferer to Asterisk */
20552    target.chan2 = ast_bridged_channel(targetcall_pvt->owner);  /* Asterisk to target */
20553 
20554    if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
20555       /* Wrong state of new channel */
20556       if (target.chan2) 
20557          ast_debug(4, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
20558       else if (target.chan1->_state != AST_STATE_RING)
20559          ast_debug(4, "SIP attended transfer: Error: No target channel\n");
20560       else
20561          ast_debug(4, "SIP attended transfer: Attempting transfer in ringing state\n");
20562    }
20563 
20564    /* Transfer */
20565    if (sipdebug) {
20566       if (current->chan2)  /* We have two bridges */
20567          ast_debug(4, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
20568       else        /* One bridge, propably transfer of IVR/voicemail etc */
20569          ast_debug(4, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
20570    }
20571 
20572    ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);   /* Delay hangup */
20573 
20574    /* Perform the transfer */
20575    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",
20576       transferer->owner->name,
20577       transferer->owner->uniqueid,
20578       transferer->callid,
20579       target.chan1->name,
20580       target.chan1->uniqueid);
20581    res = attempt_transfer(current, &target);
20582    sip_pvt_unlock(targetcall_pvt);
20583    if (res) {
20584       /* Failed transfer */
20585       transmit_notify_with_sipfrag(transferer, seqno, "486 Busy Here", TRUE);
20586       append_history(transferer, "Xfer", "Refer failed");
20587       if (targetcall_pvt->owner)
20588          ast_channel_unlock(targetcall_pvt->owner);
20589       ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
20590    } else {
20591       /* Transfer succeeded! */
20592       const char *xfersound = pbx_builtin_getvar_helper(target.chan1, "ATTENDED_TRANSFER_COMPLETE_SOUND");
20593 
20594       /* Tell transferer that we're done. */
20595       transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
20596       append_history(transferer, "Xfer", "Refer succeeded");
20597       transferer->refer->status = REFER_200OK;
20598       if (target.chan2 && !ast_strlen_zero(xfersound) && ast_streamfile(target.chan2, xfersound, target.chan2->language) >= 0) {
20599          ast_waitstream(target.chan2, "");
20600       }
20601       if (targetcall_pvt->owner) {
20602          ast_debug(1, "SIP attended transfer: Unlocking channel %s\n", targetcall_pvt->owner->name);
20603          ast_channel_unlock(targetcall_pvt->owner);
20604       }
20605    }
20606    if (targetcall_pvt)
20607       ao2_t_ref(targetcall_pvt, -1, "drop targetcall_pvt");
20608    return 1;
20609 }
20610 
20611 
20612 /*! \brief Handle incoming REFER request */
20613 /*! \page SIP_REFER SIP transfer Support (REFER)
20614 
20615    REFER is used for call transfer in SIP. We get a REFER
20616    to place a new call with an INVITE somwhere and then
20617    keep the transferor up-to-date of the transfer. If the
20618    transfer fails, get back on line with the orginal call. 
20619 
20620    - REFER can be sent outside or inside of a dialog.
20621      Asterisk only accepts REFER inside of a dialog.
20622 
20623    - If we get a replaces header, it is an attended transfer
20624 
20625    \par Blind transfers
20626    The transferor provides the transferee
20627    with the transfer targets contact. The signalling between
20628    transferer or transferee should not be cancelled, so the
20629    call is recoverable if the transfer target can not be reached 
20630    by the transferee.
20631 
20632    In this case, Asterisk receives a TRANSFER from
20633    the transferor, thus is the transferee. We should
20634    try to set up a call to the contact provided
20635    and if that fails, re-connect the current session.
20636    If the new call is set up, we issue a hangup.
20637    In this scenario, we are following section 5.2
20638    in the SIP CC Transfer draft. (Transfer without
20639    a GRUU)
20640 
20641    \par Transfer with consultation hold
20642    In this case, the transferor
20643    talks to the transfer target before the transfer takes place.
20644    This is implemented with SIP hold and transfer.
20645    Note: The invite From: string could indicate a transfer.
20646    (Section 6. Transfer with consultation hold)
20647    The transferor places the transferee on hold, starts a call
20648    with the transfer target to alert them to the impending
20649    transfer, terminates the connection with the target, then
20650    proceeds with the transfer (as in Blind transfer above)
20651 
20652    \par Attended transfer
20653    The transferor places the transferee
20654    on hold, calls the transfer target to alert them,
20655    places the target on hold, then proceeds with the transfer
20656    using a Replaces header field in the Refer-to header. This
20657    will force the transfee to send an Invite to the target,
20658    with a replaces header that instructs the target to
20659    hangup the call between the transferor and the target.
20660    In this case, the Refer/to: uses the AOR address. (The same
20661    URI that the transferee used to establish the session with
20662    the transfer target (To: ). The Require: replaces header should
20663    be in the INVITE to avoid the wrong UA in a forked SIP proxy
20664    scenario to answer and have no call to replace with.
20665 
20666    The referred-by header is *NOT* required, but if we get it,
20667    can be copied into the INVITE to the transfer target to 
20668    inform the target about the transferor
20669 
20670    "Any REFER request has to be appropriately authenticated.".
20671    
20672    We can't destroy dialogs, since we want the call to continue.
20673    
20674    */
20675 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock)
20676 {
20677    struct sip_dual current;   /* Chan1: Call between asterisk and transferer */
20678                /* Chan2: Call between asterisk and transferee */
20679 
20680    int res = 0;
20681    current.req.data = NULL;
20682 
20683    if (req->debug)
20684       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");
20685 
20686    if (!p->owner) {
20687       /* This is a REFER outside of an existing SIP dialog */
20688       /* We can't handle that, so decline it */
20689       ast_debug(3, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
20690       transmit_response(p, "603 Declined (No dialog)", req);
20691       if (!req->ignore) {
20692          append_history(p, "Xfer", "Refer failed. Outside of dialog.");
20693          sip_alreadygone(p);
20694          pvt_set_needdestroy(p, "outside of dialog");
20695       }
20696       return 0;
20697    }
20698 
20699 
20700    /* Check if transfer is allowed from this device */
20701    if (p->allowtransfer == TRANSFER_CLOSED ) {
20702       /* Transfer not allowed, decline */
20703       transmit_response(p, "603 Declined (policy)", req);
20704       append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
20705       /* Do not destroy SIP session */
20706       return 0;
20707    }
20708 
20709    if (!req->ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
20710       /* Already have a pending REFER */
20711       transmit_response(p, "491 Request pending", req);
20712       append_history(p, "Xfer", "Refer failed. Request pending.");
20713       return 0;
20714    }
20715 
20716    /* Allocate memory for call transfer data */
20717    if (!p->refer && !sip_refer_allocate(p)) {
20718       transmit_response(p, "500 Internal Server Error", req);
20719       append_history(p, "Xfer", "Refer failed. Memory allocation error.");
20720       return -3;
20721    }
20722 
20723    res = get_refer_info(p, req); /* Extract headers */
20724 
20725    p->refer->status = REFER_SENT;
20726 
20727    if (res != 0) {
20728       switch (res) {
20729       case -2: /* Syntax error */
20730          transmit_response(p, "400 Bad Request (Refer-to missing)", req);
20731          append_history(p, "Xfer", "Refer failed. Refer-to missing.");
20732          if (req->debug)
20733             ast_debug(1, "SIP transfer to black hole can't be handled (no refer-to: )\n");
20734          break;
20735       case -3:
20736          transmit_response(p, "603 Declined (Non sip: uri)", req);
20737          append_history(p, "Xfer", "Refer failed. Non SIP uri");
20738          if (req->debug)
20739             ast_debug(1, "SIP transfer to non-SIP uri denied\n");
20740          break;
20741       default:
20742          /* Refer-to extension not found, fake a failed transfer */
20743          transmit_response(p, "202 Accepted", req);
20744          append_history(p, "Xfer", "Refer failed. Bad extension.");
20745          transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
20746          ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
20747          if (req->debug)
20748             ast_debug(1, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
20749          break;
20750       } 
20751       return 0;
20752    }
20753    if (ast_strlen_zero(p->context))
20754       ast_string_field_set(p, context, sip_cfg.default_context);
20755 
20756    /* If we do not support SIP domains, all transfers are local */
20757    if (sip_cfg.allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
20758       p->refer->localtransfer = 1;
20759       if (sipdebug)
20760          ast_debug(3, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
20761    } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
20762       /* This PBX doesn't bother with SIP domains or domain is local, so this transfer is local */
20763       p->refer->localtransfer = 1;
20764    } else if (sipdebug)
20765          ast_debug(3, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
20766 
20767    /* Is this a repeat of a current request? Ignore it */
20768    /* Don't know what else to do right now. */
20769    if (req->ignore) 
20770       return res;
20771 
20772    /* If this is a blind transfer, we have the following
20773    channels to work with:
20774    - chan1, chan2: The current call between transferer and transferee (2 channels)
20775    - target_channel: A new call from the transferee to the target (1 channel)
20776    We need to stay tuned to what happens in order to be able
20777    to bring back the call to the transferer */
20778 
20779    /* If this is a attended transfer, we should have all call legs within reach:
20780    - chan1, chan2: The call between the transferer and transferee (2 channels)
20781    - target_channel, targetcall_pvt: The call between the transferer and the target (2 channels)
20782    We want to bridge chan2 with targetcall_pvt!
20783    
20784    The replaces call id in the refer message points
20785    to the call leg between Asterisk and the transferer.
20786    So we need to connect the target and the transferee channel
20787    and hangup the two other channels silently 
20788    
20789    If the target is non-local, the call ID could be on a remote
20790    machine and we need to send an INVITE with replaces to the
20791    target. We basically handle this as a blind transfer
20792    and let the sip_call function catch that we need replaces
20793    header in the INVITE.
20794    */
20795 
20796 
20797    /* Get the transferer's channel */
20798    current.chan1 = p->owner;
20799 
20800    /* Find the other part of the bridge (2) - transferee */
20801    current.chan2 = ast_bridged_channel(current.chan1);
20802    
20803    if (sipdebug)
20804       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>");
20805 
20806    if (!current.chan2 && !p->refer->attendedtransfer) {
20807       /* No bridged channel, propably IVR or echo or similar... */
20808       /* Guess we should masquerade or something here */
20809       /* Until we figure it out, refuse transfer of such calls */
20810       if (sipdebug)
20811          ast_debug(3, "Refused SIP transfer on non-bridged channel.\n");
20812       p->refer->status = REFER_FAILED;
20813       append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
20814       transmit_response(p, "603 Declined", req);
20815       return -1;
20816    }
20817 
20818    if (current.chan2) {
20819       if (sipdebug)
20820          ast_debug(4, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);
20821 
20822       ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
20823    }
20824 
20825    ast_set_flag(&p->flags[0], SIP_GOTREFER);
20826 
20827    /* Attended transfer: Find all call legs and bridge transferee with target*/
20828    if (p->refer->attendedtransfer) {
20829       if ((res = local_attended_transfer(p, &current, req, seqno)))
20830          return res; /* We're done with the transfer */
20831       /* Fall through for remote transfers that we did not find locally */
20832       if (sipdebug)
20833          ast_debug(4, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
20834       /* Fallthrough if we can't find the call leg internally */
20835    }
20836 
20837 
20838    /* Parking a call */
20839    if (p->refer->localtransfer && !strcmp(p->refer->refer_to, ast_parking_ext())) {
20840       /* Must release c's lock now, because it will not longer be accessible after the transfer! */
20841       *nounlock = 1;
20842       ast_channel_unlock(current.chan1);
20843       copy_request(&current.req, req);
20844       ast_clear_flag(&p->flags[0], SIP_GOTREFER);
20845       p->refer->status = REFER_200OK;
20846       append_history(p, "Xfer", "REFER to call parking.");
20847       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",
20848          current.chan1->name,
20849          current.chan1->uniqueid,
20850          p->callid,
20851          current.chan2->name,
20852          current.chan2->uniqueid,
20853          p->refer->refer_to);
20854       if (sipdebug)
20855          ast_debug(4, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
20856       sip_park(current.chan2, current.chan1, req, seqno);
20857       return res;
20858    } 
20859 
20860    /* Blind transfers and remote attended xfers */
20861    transmit_response(p, "202 Accepted", req);
20862 
20863    if (current.chan1 && current.chan2) {
20864       ast_debug(3, "chan1->name: %s\n", current.chan1->name);
20865       pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
20866    }
20867    if (current.chan2) {
20868       pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
20869       pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", p->refer->refer_to_domain);
20870       pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
20871       /* One for the new channel */
20872       pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
20873       /* Attended transfer to remote host, prepare headers for the INVITE */
20874       if (p->refer->referred_by) 
20875          pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", p->refer->referred_by);
20876    }
20877    /* Generate a Replaces string to be used in the INVITE during attended transfer */
20878    if (!ast_strlen_zero(p->refer->replaces_callid)) {
20879       char tempheader[SIPBUFSIZE];
20880       snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid, 
20881             p->refer->replaces_callid_totag ? ";to-tag=" : "", 
20882             p->refer->replaces_callid_totag, 
20883             p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
20884             p->refer->replaces_callid_fromtag);
20885       if (current.chan2)
20886          pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
20887    }
20888    /* Must release lock now, because it will not longer
20889       be accessible after the transfer! */
20890    *nounlock = 1;
20891    ast_channel_unlock(current.chan1);
20892 
20893    /* Connect the call */
20894 
20895    /* FAKE ringing if not attended transfer */
20896    if (!p->refer->attendedtransfer)
20897       transmit_notify_with_sipfrag(p, seqno, "183 Ringing", FALSE); 
20898 
20899    /* For blind transfer, this will lead to a new call */
20900    /* For attended transfer to remote host, this will lead to
20901       a new SIP call with a replaces header, if the dial plan allows it 
20902    */
20903    if (!current.chan2) {
20904       /* We have no bridge, so we're talking with Asterisk somehow */
20905       /* We need to masquerade this call */
20906       /* What to do to fix this situation:
20907          * Set up the new call in a new channel 
20908          * Let the new channel masq into this channel
20909          Please add that code here :-)
20910       */
20911       p->refer->status = REFER_FAILED;
20912       transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
20913       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
20914       append_history(p, "Xfer", "Refer failed (only bridged calls).");
20915       return -1;
20916    }
20917    ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);   /* Delay hangup */
20918 
20919 
20920    /* For blind transfers, move the call to the new extensions. For attended transfers on multiple
20921       servers - generate an INVITE with Replaces. Either way, let the dial plan decided  */
20922    res = ast_async_goto(current.chan2, p->refer->refer_to_context, p->refer->refer_to, 1);
20923 
20924    if (!res) {
20925       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",
20926          current.chan1->name,
20927          current.chan1->uniqueid,
20928          p->callid,
20929          current.chan2->name,
20930          current.chan2->uniqueid,
20931          p->refer->refer_to, p->refer->refer_to_context);
20932       /* Success  - we have a new channel */
20933       ast_debug(3, "%s transfer succeeded. Telling transferer.\n", p->refer->attendedtransfer? "Attended" : "Blind");
20934       transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
20935       if (p->refer->localtransfer)
20936          p->refer->status = REFER_200OK;
20937       if (p->owner)
20938          p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
20939       append_history(p, "Xfer", "Refer succeeded.");
20940       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
20941       /* Do not hangup call, the other side do that when we say 200 OK */
20942       /* We could possibly implement a timer here, auto congestion */
20943       res = 0;
20944    } else {
20945       ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Don't delay hangup */
20946       ast_debug(3, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
20947       append_history(p, "Xfer", "Refer failed.");
20948       /* Failure of some kind */
20949       p->refer->status = REFER_FAILED;
20950       transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
20951       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
20952       res = -1;
20953    }
20954    return res;
20955 }
20956 
20957 /*! \brief Handle incoming CANCEL request */
20958 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
20959 {
20960       
20961    check_via(p, req);
20962    sip_alreadygone(p);
20963 
20964    /* At this point, we could have cancelled the invite at the same time
20965       as the other side sends a CANCEL. Our final reply with error code
20966       might not have been received by the other side before the CANCEL
20967       was sent, so let's just give up retransmissions and waiting for
20968       ACK on our error code. The call is hanging up any way. */
20969    if (p->invitestate == INV_TERMINATED)
20970       __sip_pretend_ack(p);
20971    else
20972       p->invitestate = INV_CANCELLED;
20973    
20974    if (p->owner && p->owner->_state == AST_STATE_UP) {
20975       /* This call is up, cancel is ignored, we need a bye */
20976       transmit_response(p, "200 OK", req);
20977       ast_debug(1, "Got CANCEL on an answered call. Ignoring... \n");
20978       return 0;
20979    }
20980 
20981    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) 
20982       update_call_counter(p, DEC_CALL_LIMIT);
20983 
20984    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
20985    if (p->owner)
20986       ast_queue_hangup(p->owner);
20987    else
20988       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20989    if (p->initreq.len > 0) {
20990       struct sip_pkt *pkt, *prev_pkt;
20991       /* If the CANCEL we are receiving is a retransmission, and we already have scheduled
20992        * a reliable 487, then we don't want to schedule another one on top of the previous
20993        * one.
20994        *
20995        * As odd as this may sound, we can't rely on the previously-transmitted "reliable" 
20996        * response in this situation. What if we've sent all of our reliable responses 
20997        * already and now all of a sudden, we get this second CANCEL?
20998        *
20999        * The only way to do this correctly is to cancel our previously-scheduled reliably-
21000        * transmitted response and send a new one in its place.
21001        */
21002       for (pkt = p->packets, prev_pkt = NULL; pkt; prev_pkt = pkt, pkt = pkt->next) {
21003          if (pkt->seqno == p->lastinvite && pkt->response_code == 487) {
21004             AST_SCHED_DEL(sched, pkt->retransid);
21005             UNLINK(pkt, p->packets, prev_pkt);
21006             ast_free(pkt);
21007             break;
21008          }
21009       }
21010       transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
21011       transmit_response(p, "200 OK", req);
21012       return 1;
21013    } else {
21014       transmit_response(p, "481 Call Leg Does Not Exist", req);
21015       return 0;
21016    }
21017 }
21018 
21019 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen)
21020 {
21021    struct sip_pvt *p = chan->tech_pvt;
21022    char *all = "", *parse = ast_strdupa(preparse);
21023    int res = 0;
21024    AST_DECLARE_APP_ARGS(args,
21025       AST_APP_ARG(param);
21026       AST_APP_ARG(type);
21027       AST_APP_ARG(field);
21028    );
21029    AST_STANDARD_APP_ARGS(args, parse);
21030 
21031    /* Sanity check */
21032    if (!IS_SIP_TECH(chan->tech)) {
21033       ast_log(LOG_ERROR, "Cannot call %s on a non-SIP channel\n", funcname);
21034       return 0;
21035    }
21036 
21037    memset(buf, 0, buflen);
21038 
21039    if (p == NULL) {
21040       return -1;
21041    }
21042 
21043    if (!strcasecmp(args.param, "peerip")) {
21044       ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", buflen);
21045    } else if (!strcasecmp(args.param, "recvip")) {
21046       ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", buflen);
21047    } else if (!strcasecmp(args.param, "from")) {
21048       ast_copy_string(buf, p->from, buflen);
21049    } else if (!strcasecmp(args.param, "uri")) {
21050       ast_copy_string(buf, p->uri, buflen);
21051    } else if (!strcasecmp(args.param, "useragent")) {
21052       ast_copy_string(buf, p->useragent, buflen);
21053    } else if (!strcasecmp(args.param, "peername")) {
21054       ast_copy_string(buf, p->peername, buflen);
21055    } else if (!strcasecmp(args.param, "t38passthrough")) {
21056       ast_copy_string(buf, (p->t38.state == T38_DISABLED) ? "0" : "1", buflen);
21057    } else if (!strcasecmp(args.param, "rtpdest")) {
21058       struct sockaddr_in sin;
21059       struct ast_rtp *stream = NULL;
21060 
21061       if (ast_strlen_zero(args.type))
21062          args.type = "audio";
21063 
21064       if (!strcasecmp(args.type, "audio")) {
21065          stream = p->rtp;
21066       } else if (!strcasecmp(args.type, "video")) {
21067          stream = p->vrtp;
21068       } else if (!strcasecmp(args.type, "text")) {
21069          stream = p->trtp;
21070       } else {
21071          return -1;
21072       }
21073 
21074       if (!stream) {
21075          return -1;
21076       }
21077 
21078       ast_rtp_get_peer(stream, &sin);
21079       snprintf(buf, buflen, "%s:%d", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
21080    } else if (!strcasecmp(args.param, "rtpqos")) {
21081       struct ast_rtp_quality qos;
21082       struct ast_rtp *rtp = p->rtp;
21083       
21084       memset(&qos, 0, sizeof(qos));
21085 
21086       if (ast_strlen_zero(args.type))
21087          args.type = "audio";
21088       if (ast_strlen_zero(args.field))
21089          args.field = "all";
21090       
21091       if (!strcasecmp(args.type, "AUDIO")) {
21092          all = ast_rtp_get_quality(rtp = p->rtp, &qos, RTPQOS_SUMMARY);
21093       } else if (!strcasecmp(args.type, "VIDEO")) {
21094          all = ast_rtp_get_quality(rtp = p->vrtp, &qos, RTPQOS_SUMMARY);
21095       } else if (!strcasecmp(args.type, "TEXT")) {
21096          all = ast_rtp_get_quality(rtp = p->trtp, &qos, RTPQOS_SUMMARY);
21097       } else {
21098          return -1;
21099       }
21100       
21101       if (!strcasecmp(args.field, "local_ssrc"))
21102          snprintf(buf, buflen, "%u", qos.local_ssrc);
21103       else if (!strcasecmp(args.field, "local_lostpackets"))
21104          snprintf(buf, buflen, "%u", qos.local_lostpackets);
21105       else if (!strcasecmp(args.field, "local_jitter"))
21106          snprintf(buf, buflen, "%.0f", qos.local_jitter * 1000.0);
21107       else if (!strcasecmp(args.field, "local_count"))
21108          snprintf(buf, buflen, "%u", qos.local_count);
21109       else if (!strcasecmp(args.field, "remote_ssrc"))
21110          snprintf(buf, buflen, "%u", qos.remote_ssrc);
21111       else if (!strcasecmp(args.field, "remote_lostpackets"))
21112          snprintf(buf, buflen, "%u", qos.remote_lostpackets);
21113       else if (!strcasecmp(args.field, "remote_jitter"))
21114          snprintf(buf, buflen, "%.0f", qos.remote_jitter * 1000.0);
21115       else if (!strcasecmp(args.field, "remote_count"))
21116          snprintf(buf, buflen, "%u", qos.remote_count);
21117       else if (!strcasecmp(args.field, "rtt"))
21118          snprintf(buf, buflen, "%.0f", qos.rtt * 1000.0);
21119       else if (!strcasecmp(args.field, "all"))
21120          ast_copy_string(buf, all, buflen);
21121       else if (!ast_rtp_get_qos(rtp, args.field, buf, buflen))
21122           ;
21123       else {
21124          ast_log(LOG_WARNING, "Unrecognized argument '%s' to %s\n", preparse, funcname);
21125          return -1;
21126       }
21127    } else {
21128       res = -1;
21129    }
21130    return res;
21131 }
21132 
21133 /*! \brief Handle incoming BYE request */
21134 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
21135 {
21136    struct ast_channel *c=NULL;
21137    int res;
21138    struct ast_channel *bridged_to;
21139    
21140    /* If we have an INCOMING invite that we haven't answered, terminate that transaction */
21141    if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !req->ignore) {
21142       transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
21143    }
21144 
21145    __sip_pretend_ack(p);
21146 
21147    p->invitestate = INV_TERMINATED;
21148 
21149    copy_request(&p->initreq, req);
21150    if (sipdebug)
21151       ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
21152    check_via(p, req);
21153    sip_alreadygone(p);
21154 
21155    /* Get RTCP quality before end of call */
21156    if (p->do_history || p->owner) {
21157       struct ast_channel *bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
21158       char *videoqos, *textqos;
21159 
21160       /* We need to get the lock on bridge because ast_rtp_set_vars will attempt
21161        * to lock the bridge. This may get hairy...
21162        */
21163       while (bridge && ast_channel_trylock(bridge)) {
21164          ast_channel_unlock(p->owner);
21165          do {
21166             /* Can't use DEADLOCK_AVOIDANCE since p is an ao2 object */
21167             sip_pvt_unlock(p);
21168             usleep(1);
21169             sip_pvt_lock(p);
21170          } while (p->owner && ast_channel_trylock(p->owner));
21171          bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
21172       }
21173 
21174       if (p->rtp) {  
21175          if (p->do_history) {
21176             char *audioqos,
21177                  *audioqos_jitter,
21178                  *audioqos_loss,
21179                  *audioqos_rtt;
21180 
21181             audioqos        = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_SUMMARY);
21182             audioqos_jitter = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_JITTER);
21183             audioqos_loss   = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_LOSS);
21184             audioqos_rtt    = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_RTT);
21185 
21186             append_history(p, "RTCPaudio", "Quality:%s", audioqos);
21187             append_history(p, "RTCPaudioJitter", "Quality:%s", audioqos_jitter);
21188             append_history(p, "RTCPaudioLoss", "Quality:%s", audioqos_loss);
21189             append_history(p, "RTCPaudioRTT", "Quality:%s", audioqos_rtt);
21190          }
21191          
21192          if (p->owner) {
21193             ast_rtp_set_vars(p->owner, p->rtp);
21194          }
21195       }
21196 
21197       if (bridge) {
21198          struct sip_pvt *q = bridge->tech_pvt;
21199 
21200          if (IS_SIP_TECH(bridge->tech) && q && q->rtp)
21201             ast_rtp_set_vars(bridge, q->rtp);
21202          ast_channel_unlock(bridge);
21203       }
21204 
21205       if (p->vrtp) {
21206          videoqos = ast_rtp_get_quality(p->vrtp, NULL, RTPQOS_SUMMARY);
21207          if (p->do_history)
21208             append_history(p, "RTCPvideo", "Quality:%s", videoqos);
21209          if (p->owner)
21210             pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", videoqos);
21211       }
21212 
21213       if (p->trtp) {
21214          textqos = ast_rtp_get_quality(p->trtp, NULL, RTPQOS_SUMMARY);
21215          if (p->do_history)
21216             append_history(p, "RTCPtext", "Quality:%s", textqos);
21217          if (p->owner)
21218             pbx_builtin_setvar_helper(p->owner, "RTPTEXTQOS", textqos);
21219       }
21220    }
21221 
21222    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
21223    stop_session_timer(p); /* Stop Session-Timer */
21224 
21225    if (!ast_strlen_zero(get_header(req, "Also"))) {
21226       ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method.  Ask vendor to support REFER instead\n",
21227          ast_inet_ntoa(p->recv.sin_addr));
21228       if (ast_strlen_zero(p->context))
21229          ast_string_field_set(p, context, sip_cfg.default_context);
21230       res = get_also_info(p, req);
21231       if (!res) {
21232          c = p->owner;
21233          if (c) {
21234             bridged_to = ast_bridged_channel(c);
21235             if (bridged_to) {
21236                /* Don't actually hangup here... */
21237                ast_queue_control(c, AST_CONTROL_UNHOLD);
21238                ast_async_goto(bridged_to, p->context, p->refer->refer_to, 1);
21239             } else
21240                ast_queue_hangup(p->owner);
21241          }
21242       } else {
21243          ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_inet_ntoa(p->recv.sin_addr));
21244          if (p->owner)
21245             ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
21246       }
21247    } else if (p->owner) {
21248       ast_queue_hangup(p->owner);
21249       ast_debug(3, "Received bye, issuing owner hangup\n");
21250    } else {
21251       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21252       ast_debug(3, "Received bye, no owner, selfdestruct soon.\n");
21253    }
21254    ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21255    transmit_response(p, "200 OK", req);
21256 
21257    return 1;
21258 }
21259 
21260 /*! \brief Handle incoming MESSAGE request */
21261 static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
21262 {
21263    if (!req->ignore) {
21264       if (req->debug)
21265          ast_verbose("Receiving message!\n");
21266       receive_message(p, req);
21267    } else
21268       transmit_response(p, "202 Accepted", req);
21269    return 1;
21270 }
21271 
21272 static void add_peer_mwi_subs(struct sip_peer *peer)
21273 {
21274    struct sip_mailbox *mailbox;
21275 
21276    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
21277       mailbox->event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, peer,
21278          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
21279          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
21280          AST_EVENT_IE_END);
21281    }
21282 }
21283 
21284 /*! \brief  Handle incoming SUBSCRIBE request */
21285 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
21286 {
21287    int gotdest = 0;
21288    int res = 0;
21289    int firststate = AST_EXTENSION_REMOVED;
21290    struct sip_peer *authpeer = NULL;
21291    const char *eventheader = get_header(req, "Event");   /* Get Event package name */
21292    const char *acceptheader = get_header(req, "Accept");
21293    int resubscribe = (p->subscribed != NONE);
21294    char *temp, *event;
21295    struct ao2_iterator i;
21296 
21297    if (p->initreq.headers) {  
21298       /* We already have a dialog */
21299       if (p->initreq.method != SIP_SUBSCRIBE) {
21300          /* This is a SUBSCRIBE within another SIP dialog, which we do not support */
21301          /* For transfers, this could happen, but since we haven't seen it happening, let us just refuse this */
21302          transmit_response(p, "403 Forbidden (within dialog)", req);
21303          /* Do not destroy session, since we will break the call if we do */
21304          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);
21305          return 0;
21306       } else if (req->debug) {
21307          if (resubscribe)
21308             ast_debug(1, "Got a re-subscribe on existing subscription %s\n", p->callid);
21309          else
21310             ast_debug(1, "Got a new subscription %s (possibly with auth)\n", p->callid);
21311       }
21312    }
21313 
21314    /* Check if we have a global disallow setting on subscriptions. 
21315       if so, we don't have to check peer settings after auth, which saves a lot of processing
21316    */
21317    if (!sip_cfg.allowsubscribe) {
21318       transmit_response(p, "403 Forbidden (policy)", req);
21319       pvt_set_needdestroy(p, "forbidden");
21320       return 0;
21321    }
21322 
21323    if (!req->ignore && !resubscribe) { /* Set up dialog, new subscription */
21324       const char *to = get_header(req, "To");
21325       char totag[128];
21326 
21327       /* Check to see if a tag was provided, if so this is actually a resubscription of a dialog we no longer know about */
21328       if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
21329          if (req->debug)
21330             ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
21331          transmit_response(p, "481 Subscription does not exist", req);
21332          pvt_set_needdestroy(p, "subscription does not exist");
21333          return 0;
21334       }
21335 
21336       /* Use this as the basis */
21337       if (req->debug)
21338          ast_verbose("Creating new subscription\n");
21339 
21340       copy_request(&p->initreq, req);
21341       if (sipdebug)
21342          ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
21343       check_via(p, req);
21344       build_route(p, req, 0);
21345    } else if (req->debug && req->ignore)
21346       ast_verbose("Ignoring this SUBSCRIBE request\n");
21347 
21348    /* Find parameters to Event: header value and remove them for now */
21349    if (ast_strlen_zero(eventheader)) {
21350       transmit_response(p, "489 Bad Event", req);
21351       ast_debug(2, "Received SIP subscribe for unknown event package: <none>\n");
21352       pvt_set_needdestroy(p, "unknown event package in subscribe");
21353       return 0;
21354    }
21355 
21356    if ( (strchr(eventheader, ';'))) {
21357       event = ast_strdupa(eventheader);   /* Since eventheader is a const, we can't change it */
21358       temp = strchr(event, ';');       
21359       *temp = '\0';           /* Remove any options for now */
21360                      /* We might need to use them later :-) */
21361    } else
21362       event = (char *) eventheader;    /* XXX is this legal ? */
21363 
21364    /* Handle authentication */
21365    res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, sin, &authpeer);
21366    /* if an authentication response was sent, we are done here */
21367    if (res == AUTH_CHALLENGE_SENT)  /* authpeer = NULL here */
21368       return 0;
21369    if (res < 0) {
21370       if (res == AUTH_FAKE_AUTH) {
21371          ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
21372          transmit_fake_auth_response(p, SIP_SUBSCRIBE, req, XMIT_UNRELIABLE);
21373       } else {
21374          ast_log(LOG_NOTICE, "Failed to authenticate device %s for SUBSCRIBE\n", get_header(req, "From"));
21375          transmit_response_reliable(p, "403 Forbidden", req);
21376       }
21377       pvt_set_needdestroy(p, "authentication failed");
21378       return 0;
21379    }
21380 
21381    /* At this point, authpeer cannot be NULL. Remember we hold a reference,
21382     * so we must release it when done.
21383     * XXX must remove all the checks for authpeer == NULL.
21384     */
21385 
21386    /* Check if this device  is allowed to subscribe at all */
21387    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
21388       transmit_response(p, "403 Forbidden (policy)", req);
21389       pvt_set_needdestroy(p, "subscription not allowed");
21390       if (authpeer)
21391          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 1)");
21392       return 0;
21393    }
21394 
21395    if (strcmp(event, "message-summary")) {
21396       /* Get destination right away */
21397       gotdest = get_destination(p, NULL);
21398    }
21399 
21400    /* Get full contact header - this needs to be used as a request URI in NOTIFY's */
21401    parse_ok_contact(p, req);
21402 
21403    build_contact(p);
21404    if (gotdest) {
21405       transmit_response(p, "404 Not Found", req);
21406       pvt_set_needdestroy(p, "subscription target not found");
21407       if (authpeer)
21408          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
21409       return 0;
21410    }
21411 
21412    /* Initialize tag for new subscriptions */   
21413    if (ast_strlen_zero(p->tag))
21414       make_our_tag(p->tag, sizeof(p->tag));
21415 
21416    if (!strcmp(event, "presence") || !strcmp(event, "dialog")) { /* Presence, RFC 3842 */
21417       unsigned int pidf_xml;
21418 
21419       if (authpeer)  /* We do not need the authpeer any more */
21420          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
21421 
21422       /* Header from Xten Eye-beam Accept: multipart/related, application/rlmi+xml, application/pidf+xml, application/xpidf+xml */
21423 
21424       pidf_xml = strstr(acceptheader, "application/pidf+xml") ? 1 : 0;
21425 
21426       /* Older versions of Polycom firmware will claim pidf+xml, but really
21427        * they only support xpidf+xml. */
21428       if (pidf_xml && strstr(p->useragent, "Polycom")) {
21429          p->subscribed = XPIDF_XML;
21430       } else if (pidf_xml) {
21431          p->subscribed = PIDF_XML;         /* RFC 3863 format */
21432       } else if (strstr(acceptheader, "application/dialog-info+xml")) {
21433          p->subscribed = DIALOG_INFO_XML;
21434          /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
21435       } else if (strstr(acceptheader, "application/cpim-pidf+xml")) {
21436          p->subscribed = CPIM_PIDF_XML;    /* RFC 3863 format */
21437       } else if (strstr(acceptheader, "application/xpidf+xml")) {
21438          p->subscribed = XPIDF_XML;        /* Early pre-RFC 3863 format with MSN additions (Microsoft Messenger) */
21439       } else if (ast_strlen_zero(acceptheader)) {
21440          if (p->subscribed == NONE) { /* if the subscribed field is not already set, and there is no accept header... */
21441             transmit_response(p, "489 Bad Event", req);
21442   
21443             ast_log(LOG_WARNING, "SUBSCRIBE failure: no Accept header: pvt: stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
21444                p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
21445             pvt_set_needdestroy(p, "no Accept header");
21446             return 0;
21447          }
21448          /* if p->subscribed is non-zero, then accept is not obligatory; according to rfc 3265 section 3.1.3, at least.
21449             so, we'll just let it ride, keeping the value from a previous subscription, and not abort the subscription */
21450       } else {
21451          /* Can't find a format for events that we know about */
21452          char mybuf[200];
21453          snprintf(mybuf, sizeof(mybuf), "489 Bad Event (format %s)", acceptheader);
21454          transmit_response(p, mybuf, req);
21455  
21456          ast_log(LOG_WARNING, "SUBSCRIBE failure: unrecognized format: '%s' pvt: subscribed: %d, stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
21457             acceptheader, (int)p->subscribed, p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
21458          pvt_set_needdestroy(p, "unrecognized format");
21459          return 0;
21460       }
21461    } else if (!strcmp(event, "message-summary")) { 
21462       if (!ast_strlen_zero(acceptheader) && strcmp(acceptheader, "application/simple-message-summary")) {
21463          /* Format requested that we do not support */
21464          transmit_response(p, "406 Not Acceptable", req);
21465          ast_debug(2, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
21466          pvt_set_needdestroy(p, "unknown format");
21467          if (authpeer)
21468             unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 3)");
21469          return 0;
21470       }
21471       /* Looks like they actually want a mailbox status 
21472         This version of Asterisk supports mailbox subscriptions
21473         The subscribed URI needs to exist in the dial plan
21474         In most devices, this is configurable to the voicemailmain extension you use
21475       */
21476       if (!authpeer || AST_LIST_EMPTY(&authpeer->mailboxes)) {
21477          transmit_response(p, "404 Not found (no mailbox)", req);
21478          pvt_set_needdestroy(p, "received 404 response");
21479          ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", authpeer->name);
21480          if (authpeer)
21481             unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 4)");
21482          return 0;
21483       }
21484 
21485       p->subscribed = MWI_NOTIFICATION;
21486       if (ast_test_flag(&authpeer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY)) {
21487          add_peer_mwi_subs(authpeer);
21488       }
21489       if (authpeer->mwipvt && authpeer->mwipvt != p) {   /* Destroy old PVT if this is a new one */
21490          /* We only allow one subscription per peer */
21491          dialog_unlink_all(authpeer->mwipvt, TRUE, TRUE);
21492          authpeer->mwipvt = dialog_unref(authpeer->mwipvt, "unref dialog authpeer->mwipvt");
21493          /* sip_destroy(authpeer->mwipvt); */
21494       }
21495       if (authpeer->mwipvt)
21496          dialog_unref(authpeer->mwipvt, "Unref previously stored mwipvt dialog pointer");
21497       authpeer->mwipvt = dialog_ref(p, "setting peers' mwipvt to p");      /* Link from peer to pvt UH- should this be dialog_ref()? */
21498       if (p->relatedpeer)
21499          unref_peer(p->relatedpeer, "Unref previously stored relatedpeer ptr");
21500       p->relatedpeer = ref_peer(authpeer, "setting dialog's relatedpeer pointer");  /* already refcounted...Link from pvt to peer UH- should this be dialog_ref()? */
21501       /* Do not release authpeer here */
21502    } else { /* At this point, Asterisk does not understand the specified event */
21503       transmit_response(p, "489 Bad Event", req);
21504       ast_debug(2, "Received SIP subscribe for unknown event package: %s\n", event);
21505       pvt_set_needdestroy(p, "unknown event package");
21506       if (authpeer)
21507          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 5)");
21508       return 0;
21509    }
21510 
21511    /* Add subscription for extension state from the PBX core */
21512    if (p->subscribed != MWI_NOTIFICATION && !resubscribe) {
21513       if (p->stateid > -1) {
21514          ast_extension_state_del(p->stateid, cb_extensionstate);
21515          /* we need to dec the refcount, now that the extensionstate is removed */
21516          dialog_unref(p, "the extensionstate containing this dialog ptr was deleted");
21517       }
21518       p->stateid = ast_extension_state_add(p->context, p->exten, cb_extensionstate, dialog_ref(p,"copying dialog ptr into extension state struct"));
21519    }
21520 
21521    if (!req->ignore && p)
21522       p->lastinvite = seqno;
21523    if (p && !p->needdestroy) {
21524       p->expiry = atoi(get_header(req, "Expires"));
21525 
21526       /* check if the requested expiry-time is within the approved limits from sip.conf */
21527       if (p->expiry > max_expiry)
21528          p->expiry = max_expiry;
21529       if (p->expiry < min_expiry && p->expiry > 0)
21530          p->expiry = min_expiry;
21531 
21532       if (sipdebug) {
21533          if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
21534             ast_debug(2, "Adding subscription for mailbox notification - peer %s\n", p->relatedpeer->name);
21535          else
21536             ast_debug(2, "Adding subscription for extension %s context %s for peer %s\n", p->exten, p->context, p->username);
21537       }
21538       if (p->autokillid > -1 && sip_cancel_destroy(p))   /* Remove subscription expiry for renewals */
21539          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
21540       if (p->expiry > 0)
21541          sip_scheddestroy(p, (p->expiry + 10) * 1000);   /* Set timer for destruction of call at expiration */
21542 
21543       if (p->subscribed == MWI_NOTIFICATION) {
21544          ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21545          transmit_response(p, "200 OK", req);
21546          if (p->relatedpeer) {   /* Send first notification */
21547             ao2_lock(p->relatedpeer); /* was WRLOCK */
21548             sip_send_mwi_to_peer(p->relatedpeer, NULL, 0);
21549             ao2_unlock(p->relatedpeer);
21550          }
21551       } else {
21552          struct sip_pvt *p_old;
21553 
21554          if ((firststate = ast_extension_state(NULL, p->context, p->exten)) < 0) {
21555 
21556             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));
21557             transmit_response(p, "404 Not found", req);
21558             pvt_set_needdestroy(p, "no extension for SUBSCRIBE");
21559             return 0;
21560          }
21561          ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21562          transmit_response(p, "200 OK", req);
21563          transmit_state_notify(p, firststate, 1, FALSE); /* Send first notification */
21564          append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
21565          /* hide the 'complete' exten/context in the refer_to field for later display */
21566          ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
21567 
21568          /* remove any old subscription from this peer for the same exten/context,
21569          as the peer has obviously forgotten about it and it's wasteful to wait
21570          for it to expire and send NOTIFY messages to the peer only to have them
21571          ignored (or generate errors)
21572          */
21573          i = ao2_iterator_init(dialogs, 0);
21574          while ((p_old = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
21575             if (p_old == p) {
21576                ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before continue");
21577                continue;
21578             }
21579             if (p_old->initreq.method != SIP_SUBSCRIBE) {
21580                ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before continue");
21581                continue;
21582             }
21583             if (p_old->subscribed == NONE) {
21584                ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before continue");
21585                continue;
21586             }
21587             sip_pvt_lock(p_old);
21588             if (!strcmp(p_old->username, p->username)) {
21589                if (!strcmp(p_old->exten, p->exten) &&
21590                    !strcmp(p_old->context, p->context)) {
21591                   pvt_set_needdestroy(p_old, "replacing subscription");
21592                   sip_pvt_unlock(p_old);
21593                   ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before break");
21594                   break;
21595                }
21596             }
21597             sip_pvt_unlock(p_old);
21598             ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next");
21599          }
21600          ao2_iterator_destroy(&i);
21601       }
21602       if (!p->expiry) {
21603          pvt_set_needdestroy(p, "forcing expiration");
21604       }
21605    }
21606    return 1;
21607 }
21608 
21609 /*! \brief Handle incoming REGISTER request */
21610 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e)
21611 {
21612    enum check_auth_result res;
21613 
21614    /* Use this as the basis */
21615    copy_request(&p->initreq, req);
21616    if (sipdebug)
21617       ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
21618    check_via(p, req);
21619    if ((res = register_verify(p, sin, req, e)) < 0) {
21620       const char *reason;
21621 
21622       switch (res) {
21623       case AUTH_SECRET_FAILED:
21624          reason = "Wrong password";
21625          break;
21626       case AUTH_USERNAME_MISMATCH:
21627          reason = "Username/auth name mismatch";
21628          break;
21629       case AUTH_NOT_FOUND:
21630          reason = "No matching peer found";
21631          break;
21632       case AUTH_UNKNOWN_DOMAIN:
21633          reason = "Not a local domain";
21634          break;
21635       case AUTH_PEER_NOT_DYNAMIC:
21636          reason = "Peer is not supposed to register";
21637          break;
21638       case AUTH_ACL_FAILED:
21639          reason = "Device does not match ACL";
21640          break;
21641       case AUTH_BAD_TRANSPORT:
21642          reason = "Device not configured to use this transport type";
21643          break;
21644       default:
21645          reason = "Unknown failure";
21646          break;
21647       }
21648       ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
21649          get_header(req, "To"), ast_inet_ntoa(sin->sin_addr),
21650          reason);
21651       append_history(p, "RegRequest", "Failed : Account %s : %s", get_header(req, "To"), reason);
21652    } else
21653       append_history(p, "RegRequest", "Succeeded : Account %s", get_header(req, "To"));
21654 
21655    if (res < 1) {
21656       /* Destroy the session, but keep us around for just a bit in case they don't
21657          get our 200 OK */
21658       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21659    }
21660    return res;
21661 }
21662 
21663 /*! \brief Handle incoming SIP requests (methods) 
21664 \note This is where all incoming requests go first   */
21665 /* called with p and p->owner locked */
21666 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock)
21667 {
21668    /* Called with p->lock held, as well as p->owner->lock if appropriate, keeping things
21669       relatively static */
21670    const char *cmd;
21671    const char *cseq;
21672    const char *useragent;
21673    int seqno;
21674    int len;
21675    int respid;
21676    int res = 0;
21677    int debug = sip_debug_test_pvt(p);
21678    char *e;
21679    int error = 0;
21680    int oldmethod = p->method;
21681    int acked = 0;
21682 
21683    /* Get Method and Cseq */
21684    cseq = get_header(req, "Cseq");
21685    cmd = REQ_OFFSET_TO_STR(req, header[0]);
21686 
21687    /* Must have Cseq */
21688    if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq)) {
21689       ast_log(LOG_ERROR, "Missing Cseq. Dropping this SIP message, it's incomplete.\n");
21690       error = 1;
21691    }
21692    if (!error && sscanf(cseq, "%30d%n", &seqno, &len) != 1) {
21693       ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
21694       error = 1;
21695    }
21696    if (error) {
21697       if (!p->initreq.headers) { /* New call */
21698          pvt_set_needdestroy(p, "no headers");
21699       }
21700       return -1;
21701    }
21702    /* Get the command XXX */
21703 
21704    cmd = REQ_OFFSET_TO_STR(req, rlPart1);
21705    e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlPart2));
21706 
21707    /* Save useragent of the client */
21708    useragent = get_header(req, "User-Agent");
21709    if (!ast_strlen_zero(useragent))
21710       ast_string_field_set(p, useragent, useragent);
21711 
21712    /* Find out SIP method for incoming request */
21713    if (req->method == SIP_RESPONSE) {  /* Response to our request */
21714       /* ignore means "don't do anything with it" but still have to 
21715        * respond appropriately.
21716        * But in this case this is a response already, so we really
21717        * have nothing to do with this message, and even setting the
21718        * ignore flag is pointless.
21719        */
21720       if (ast_strlen_zero(e)) {
21721          return 0;
21722       }
21723       if (sscanf(e, "%30d %n", &respid, &len) != 1) {
21724          ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
21725          return 0;
21726       }
21727       if (respid <= 0) {
21728          ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
21729          return 0;
21730       }
21731       if (p->ocseq && (p->ocseq < seqno)) {
21732          if (option_debug)
21733             ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
21734          return -1;
21735       } else {
21736          if ((respid == 200) || ((respid >= 300) && (respid <= 399))) {
21737             extract_uri(p, req);
21738          }
21739          handle_response(p, respid, e + len, req, seqno);
21740       }
21741       return 0;
21742    }
21743 
21744    /* New SIP request coming in 
21745       (could be new request in existing SIP dialog as well...) 
21746     */         
21747    
21748    p->method = req->method;   /* Find out which SIP method they are using */
21749    ast_debug(4, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd); 
21750 
21751    if (p->icseq && (p->icseq > seqno) ) {
21752       if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
21753          ast_debug(2, "Got CANCEL or ACK on INVITE with transactions in between.\n");
21754       }  else {
21755          ast_debug(1, "Ignoring too old SIP packet packet %d (expecting >= %d)\n", seqno, p->icseq);
21756          if (req->method != SIP_ACK)
21757             transmit_response(p, "503 Server error", req);  /* We must respond according to RFC 3261 sec 12.2 */
21758          return -1;
21759       }
21760    } else if (p->icseq &&
21761          p->icseq == seqno &&
21762          req->method != SIP_ACK &&
21763          (p->method != SIP_CANCEL || p->alreadygone)) {
21764       /* ignore means "don't do anything with it" but still have to 
21765          respond appropriately.  We do this if we receive a repeat of
21766          the last sequence number  */
21767       req->ignore = 1;
21768       ast_debug(3, "Ignoring SIP message because of retransmit (%s Seqno %d, ours %d)\n", sip_methods[p->method].text, p->icseq, seqno);
21769    }
21770       
21771    if (seqno >= p->icseq)
21772       /* Next should follow monotonically (but not necessarily 
21773          incrementally -- thanks again to the genius authors of SIP --
21774          increasing */
21775       p->icseq = seqno;
21776 
21777    /* Find their tag if we haven't got it */
21778    if (ast_strlen_zero(p->theirtag)) {
21779       char tag[128];
21780 
21781       gettag(req, "From", tag, sizeof(tag));
21782       ast_string_field_set(p, theirtag, tag);
21783    }
21784    snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
21785 
21786    if (sip_cfg.pedanticsipchecking) {
21787       /* If this is a request packet without a from tag, it's not
21788          correct according to RFC 3261  */
21789       /* Check if this a new request in a new dialog with a totag already attached to it,
21790          RFC 3261 - section 12.2 - and we don't want to mess with recovery  */
21791       if (!p->initreq.headers && req->has_to_tag) {
21792          /* If this is a first request and it got a to-tag, it is not for us */
21793          if (!req->ignore && req->method == SIP_INVITE) {
21794             transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
21795             /* Will cease to exist after ACK */
21796          } else if (req->method != SIP_ACK) {
21797             transmit_response(p, "481 Call/Transaction Does Not Exist", req);
21798             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21799          } else {
21800             ast_debug(1, "Got ACK for unknown dialog... strange.\n");
21801          }
21802          return res;
21803       }
21804    }
21805 
21806    if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY)) {
21807       transmit_response(p, "400 Bad request", req);
21808       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21809       return -1;
21810    }
21811 
21812    /* Handle various incoming SIP methods in requests */
21813    switch (p->method) {
21814    case SIP_OPTIONS:
21815       res = handle_request_options(p, req);
21816       break;
21817    case SIP_INVITE:
21818       res = handle_request_invite(p, req, debug, seqno, sin, recount, e, nounlock);
21819       break;
21820    case SIP_REFER:
21821       res = handle_request_refer(p, req, debug, seqno, nounlock);
21822       break;
21823    case SIP_CANCEL:
21824       res = handle_request_cancel(p, req);
21825       break;
21826    case SIP_BYE:
21827       res = handle_request_bye(p, req);
21828       break;
21829    case SIP_MESSAGE:
21830       res = handle_request_message(p, req);
21831       break;
21832    case SIP_SUBSCRIBE:
21833       res = handle_request_subscribe(p, req, sin, seqno, e);
21834       break;
21835    case SIP_REGISTER:
21836       res = handle_request_register(p, req, sin, e);
21837       break;
21838    case SIP_INFO:
21839       if (req->debug)
21840          ast_verbose("Receiving INFO!\n");
21841       if (!req->ignore) 
21842          handle_request_info(p, req);
21843       else  /* if ignoring, transmit response */
21844          transmit_response(p, "200 OK", req);
21845       break;
21846    case SIP_NOTIFY:
21847       res = handle_request_notify(p, req, sin, seqno, e);
21848       break;
21849    case SIP_ACK:
21850       /* Make sure we don't ignore this */
21851       if (seqno == p->pendinginvite) {
21852          p->invitestate = INV_TERMINATED;
21853          p->pendinginvite = 0;
21854          acked = __sip_ack(p, seqno, 1 /* response */, 0);
21855          if (find_sdp(req)) {
21856             if (process_sdp(p, req, SDP_T38_NONE))
21857                return -1;
21858          }
21859          check_pendings(p);
21860       } else if (p->glareinvite == seqno) {
21861          /* handle ack for the 491 pending sent for glareinvite */
21862          p->glareinvite = 0;
21863          acked = __sip_ack(p, seqno, 1, 0);
21864       }
21865       if (!acked) {
21866          /* Got an ACK that did not match anything. Ignore
21867           * silently and restore previous method */
21868          p->method = oldmethod;
21869       }
21870       if (!p->lastinvite && ast_strlen_zero(p->randdata)) {
21871          pvt_set_needdestroy(p, "unmatched ACK");
21872       }
21873       break;
21874    default:
21875       transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
21876       ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n", 
21877          cmd, ast_inet_ntoa(p->sa.sin_addr));
21878       /* If this is some new method, and we don't have a call, destroy it now */
21879       if (!p->initreq.headers) {
21880          pvt_set_needdestroy(p, "unimplemented method");
21881       }
21882       break;
21883    }
21884    return res;
21885 }
21886 
21887 static void process_request_queue(struct sip_pvt *p, int *recount, int *nounlock)
21888 {
21889    struct sip_request *req;
21890 
21891    while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
21892       if (handle_incoming(p, req, &p->recv, recount, nounlock) == -1) {
21893          /* Request failed */
21894          if (option_debug) {
21895             ast_log(LOG_DEBUG, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
21896          }
21897       }
21898       ast_free(req);
21899    }
21900 }
21901 
21902 static int scheduler_process_request_queue(const void *data)
21903 {
21904    struct sip_pvt *p = (struct sip_pvt *) data;
21905    int recount = 0;
21906    int nounlock = 0;
21907    int lockretry;
21908 
21909    for (lockretry = 10; lockretry > 0; lockretry--) {
21910       sip_pvt_lock(p);
21911 
21912       /* lock the owner if it has one -- we may need it */
21913       /* because this is deadlock-prone, we need to try and unlock if failed */
21914       if (!p->owner || !ast_channel_trylock(p->owner)) {
21915          break;   /* locking succeeded */
21916       }
21917 
21918       if (lockretry != 1) {
21919          sip_pvt_unlock(p);
21920          /* Sleep for a very short amount of time */
21921          usleep(1);
21922       }
21923    }
21924 
21925    if (!lockretry) {
21926       int retry = !AST_LIST_EMPTY(&p->request_queue);
21927 
21928       /* we couldn't get the owner lock, which is needed to process
21929          the queued requests, so return a non-zero value, which will
21930          cause the scheduler to run this request again later if there
21931          still requests to be processed
21932       */
21933       sip_pvt_unlock(p);
21934       if (!retry) {
21935          dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
21936       }
21937       return retry;
21938    };
21939 
21940    process_request_queue(p, &recount, &nounlock);
21941    p->request_queue_sched_id = -1;
21942 
21943    if (p->owner && !nounlock) {
21944       ast_channel_unlock(p->owner);
21945    }
21946    sip_pvt_unlock(p);
21947 
21948    if (recount) {
21949       ast_update_use_count();
21950    }
21951 
21952    dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
21953 
21954    return 0;
21955 }
21956 
21957 static int queue_request(struct sip_pvt *p, const struct sip_request *req)
21958 {
21959    struct sip_request *newreq;
21960 
21961    if (!(newreq = ast_calloc(1, sizeof(*newreq)))) {
21962       return -1;
21963    }
21964 
21965    copy_request(newreq, req);
21966    AST_LIST_INSERT_TAIL(&p->request_queue, newreq, next);
21967    if (p->request_queue_sched_id == -1) {
21968       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) {
21969          dialog_unref(p, "Decrement refcount due to sched_add failure");
21970       }
21971    }
21972 
21973    return 0;
21974 }
21975 
21976 /*! \brief Read data from SIP UDP socket
21977 \note sipsock_read locks the owner channel while we are processing the SIP message
21978 \return 1 on error, 0 on success
21979 \note Successful messages is connected to SIP call and forwarded to handle_incoming() 
21980 */
21981 static int sipsock_read(int *id, int fd, short events, void *ignore)
21982 {
21983    struct sip_request req;
21984    struct sockaddr_in sin = { 0, };
21985    int res;
21986    socklen_t len = sizeof(sin);
21987    static char readbuf[65535];
21988 
21989    memset(&req, 0, sizeof(req));
21990    res = recvfrom(fd, readbuf, sizeof(readbuf) - 1, 0, (struct sockaddr *)&sin, &len);
21991    if (res < 0) {
21992 #if !defined(__FreeBSD__)
21993       if (errno == EAGAIN)
21994          ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
21995       else 
21996 #endif
21997       if (errno != ECONNREFUSED)
21998          ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
21999       return 1;
22000    }
22001 
22002    readbuf[res] = '\0';
22003 
22004    if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
22005       return 1;
22006    }
22007 
22008    if (ast_str_set(&req.data, 0, "%s", readbuf) == AST_DYNSTR_BUILD_FAILED) {
22009       return -1;
22010    }
22011 
22012    req.len = res;
22013    req.socket.fd = sipsock;
22014    set_socket_transport(&req.socket, SIP_TRANSPORT_UDP);
22015    req.socket.tcptls_session  = NULL;
22016    req.socket.port = bindaddr.sin_port;
22017 
22018    handle_request_do(&req, &sin);
22019    deinit_req(&req);
22020 
22021    return 1;
22022 }
22023 
22024 /*! \brief Handle incoming SIP message - request or response 
22025 
22026    This is used for all transports (udp, tcp and tcp/tls)
22027 */
22028 static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin) 
22029 {
22030    struct sip_pvt *p;
22031    int recount = 0;
22032    int nounlock = 0;
22033    int lockretry;
22034 
22035    if (sip_debug_test_addr(sin)) /* Set the debug flag early on packet level */
22036       req->debug = 1;
22037    if (sip_cfg.pedanticsipchecking)
22038       req->len = lws2sws(req->data->str, req->len);   /* Fix multiline headers */
22039    if (req->debug) {
22040       ast_verbose("\n<--- SIP read from %s:%s:%d --->\n%s\n<------------->\n", 
22041          get_transport(req->socket.type), ast_inet_ntoa(sin->sin_addr), 
22042          ntohs(sin->sin_port), req->data->str);
22043    }
22044 
22045    if (parse_request(req) == -1) { /* Bad packet, can't parse */
22046       ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
22047       return 1;
22048    }
22049    req->method = find_sip_method(REQ_OFFSET_TO_STR(req, rlPart1));
22050 
22051    if (req->debug)
22052       ast_verbose("--- (%d headers %d lines)%s ---\n", req->headers, req->lines, (req->headers + req->lines == 0) ? " Nat keepalive" : "");
22053 
22054    if (req->headers < 2) { /* Must have at least two headers */
22055       ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
22056       return 1;
22057    }
22058 
22059    /* Process request, with netlock held, and with usual deadlock avoidance */
22060    for (lockretry = 10; lockretry > 0; lockretry--) {
22061       ast_mutex_lock(&netlock);
22062 
22063       /* Find the active SIP dialog or create a new one */
22064       p = find_call(req, sin, req->method);  /* returns p locked */
22065       if (p == NULL) {
22066          ast_debug(1, "Invalid SIP message - rejected , no callid, len %d\n", req->len);
22067          ast_mutex_unlock(&netlock);
22068          return 1;
22069       }
22070 
22071       copy_socket_data(&p->socket, &req->socket);
22072 
22073       /* Go ahead and lock the owner if it has one -- we may need it */
22074       /* becaues this is deadlock-prone, we need to try and unlock if failed */
22075       if (!p->owner || !ast_channel_trylock(p->owner))
22076          break;   /* locking succeeded */
22077 
22078       if (lockretry != 1) {
22079          sip_pvt_unlock(p);
22080          ao2_t_ref(p, -1, "release p (from find_call) inside lockretry loop"); /* we'll look for it again, but p is dead now */
22081          ast_mutex_unlock(&netlock);
22082          /* Sleep for a very short amount of time */
22083          usleep(1);
22084       }
22085    }
22086    p->recv = *sin;
22087 
22088    if (p->do_history) /* This is a request or response, note what it was for */
22089       append_history(p, "Rx", "%s / %s / %s", req->data->str, get_header(req, "CSeq"), REQ_OFFSET_TO_STR(req, rlPart2));
22090 
22091    if (!lockretry) {
22092       if (!queue_request(p, req)) {
22093          /* the request has been queued for later handling */
22094          sip_pvt_unlock(p);
22095          ao2_t_ref(p, -1, "release p (from find_call) after queueing request");
22096          ast_mutex_unlock(&netlock);
22097          return 1;
22098       }
22099 
22100       if (p->owner)
22101          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 ??? - "));
22102       ast_log(LOG_ERROR, "SIP transaction failed: %s \n", p->callid);
22103       if (req->method != SIP_ACK)
22104          transmit_response(p, "503 Server error", req);  /* We must respond according to RFC 3261 sec 12.2 */
22105       /* XXX We could add retry-after to make sure they come back */
22106       append_history(p, "LockFail", "Owner lock failed, transaction failed.");
22107       sip_pvt_unlock(p);
22108       ao2_t_ref(p, -1, "release p (from find_call) at end of lockretry"); /* p is gone after the return */
22109       ast_mutex_unlock(&netlock);
22110       return 1;
22111    }
22112 
22113    /* if there are queued requests on this sip_pvt, process them first, so that everything is
22114       handled in order
22115    */
22116    if (!AST_LIST_EMPTY(&p->request_queue)) {
22117       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"));
22118       process_request_queue(p, &recount, &nounlock);
22119    }
22120 
22121    if (handle_incoming(p, req, sin, &recount, &nounlock) == -1) {
22122       /* Request failed */
22123       ast_debug(1, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
22124    }
22125       
22126    if (recount)
22127       ast_update_use_count();
22128 
22129    if (p->owner && !nounlock)
22130       ast_channel_unlock(p->owner);
22131    sip_pvt_unlock(p);
22132    ast_mutex_unlock(&netlock);
22133    ao2_t_ref(p, -1, "throw away dialog ptr from find_call at end of routine"); /* p is gone after the return */
22134    return 1;
22135 }
22136 
22137 /*! \brief Returns the port to use for this socket
22138  *
22139  * \param type The type of transport used
22140  * \param port Port we are checking to see if it's the standard port.
22141  * \note port is expected in host byte order
22142  */
22143 static int sip_standard_port(enum sip_transport type, int port)
22144 {
22145    if (type & SIP_TRANSPORT_TLS)
22146       return port == STANDARD_TLS_PORT;
22147    else
22148       return port == STANDARD_SIP_PORT;
22149 }
22150 
22151 static int threadinfo_locate_cb(void *obj, void *arg, int flags)
22152 {
22153    struct sip_threadinfo *th = obj;
22154    struct sockaddr_in *s = arg;
22155 
22156    if (!inaddrcmp(&th->tcptls_session->remote_address, s)) {
22157       return CMP_MATCH | CMP_STOP;
22158    }
22159 
22160    return 0;
22161 }
22162 
22163 /*! 
22164  * \brief Find thread for TCP/TLS session (based on IP/Port 
22165  *
22166  * \note This function returns an astobj2 reference
22167  */
22168 static struct ast_tcptls_session_instance *sip_tcp_locate(struct sockaddr_in *s)
22169 {
22170    struct sip_threadinfo *th;
22171    struct ast_tcptls_session_instance *tcptls_instance = NULL;
22172 
22173    if ((th = ao2_callback(threadt, 0, threadinfo_locate_cb, s))) {
22174       tcptls_instance = (ao2_ref(th->tcptls_session, +1), th->tcptls_session);
22175       ao2_t_ref(th, -1, "decrement ref from callback");
22176    }
22177    return tcptls_instance;
22178 }
22179 
22180 /*! \todo Get socket for dialog, prepare if needed, and return file handle  */
22181 static int sip_prepare_socket(struct sip_pvt *p) 
22182 {
22183    struct sip_socket *s = &p->socket;
22184    static const char name[] = "SIP socket";
22185    struct sip_threadinfo *th = NULL;
22186    struct ast_tcptls_session_instance *tcptls_session;
22187    struct ast_tcptls_session_args tmp_ca = {
22188       .name = name,
22189       .accept_fd = -1,
22190    };
22191    struct ast_tcptls_session_args *ca;
22192 
22193    /* check to see if a socket is already active */
22194    if ((s->fd != -1) && (s->type == SIP_TRANSPORT_UDP)) {
22195       return s->fd;
22196    }
22197    if ((s->type & (SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS)) &&
22198          (s->tcptls_session) &&
22199          (s->tcptls_session->fd != -1)) {
22200       return s->tcptls_session->fd;
22201    }
22202 
22203    /*! \todo Check this... This might be wrong, depending on the proxy configuration
22204       If proxy is in "force" mode its correct.
22205     */
22206    if (p->outboundproxy && p->outboundproxy->transport) {
22207       s->type = p->outboundproxy->transport;
22208    }
22209 
22210    if (s->type == SIP_TRANSPORT_UDP) {
22211       s->fd = sipsock;
22212       return s->fd;
22213    }
22214 
22215    /* At this point we are dealing with a TCP/TLS connection
22216     * 1. We need to check to see if a connectin thread exists
22217     *    for this address, if so use that.
22218     * 2. If a thread does not exist for this address, but the tcptls_session
22219     *    exists on the socket, the connection was closed.
22220     * 3. If no tcptls_session thread exists for the address, and no tcptls_session
22221     *    already exists on the socket, create a new one and launch a new thread.
22222     */
22223 
22224    /* 1.  check for existing threads */
22225    tmp_ca.remote_address = *(sip_real_dst(p));
22226    if ((tcptls_session = sip_tcp_locate(&tmp_ca.remote_address))) {
22227       s->fd = tcptls_session->fd;
22228       if (s->tcptls_session) {
22229          ao2_ref(s->tcptls_session, -1);
22230          s->tcptls_session = NULL;
22231       }
22232       s->tcptls_session = tcptls_session;
22233       return s->fd;
22234    /* 2.  Thread not found, if tcptls_session already exists, it once had a thread and is now terminated */
22235    } else if (s->tcptls_session) {
22236       return s->fd; /* XXX whether reconnection is ever necessary here needs to be investigated further */
22237    }
22238 
22239    /* 3.  Create a new TCP/TLS client connection */
22240    /* create new session arguments for the client connection */
22241    if (!(ca = ao2_alloc(sizeof(*ca), sip_tcptls_client_args_destructor)) ||
22242       !(ca->name = ast_strdup(name))) {
22243       goto create_tcptls_session_fail;
22244    }
22245    ca->accept_fd = -1;
22246    ca->remote_address = *(sip_real_dst(p));
22247    /* if type is TLS, we need to create a tls cfg for this session arg */
22248    if (s->type == SIP_TRANSPORT_TLS) {
22249       if (!(ca->tls_cfg = ast_calloc(1, sizeof(*ca->tls_cfg)))) {
22250          goto create_tcptls_session_fail;
22251       }
22252       memcpy(ca->tls_cfg, &default_tls_cfg, sizeof(*ca->tls_cfg));
22253 
22254       if (!(ca->tls_cfg->certfile = ast_strdup(default_tls_cfg.certfile)) ||
22255          !(ca->tls_cfg->cipher = ast_strdup(default_tls_cfg.cipher)) ||
22256          !(ca->tls_cfg->cafile = ast_strdup(default_tls_cfg.cafile)) ||
22257          !(ca->tls_cfg->capath = ast_strdup(default_tls_cfg.capath))) {
22258 
22259          goto create_tcptls_session_fail;
22260       }
22261 
22262       /* this host is used as the common name in ssl/tls */
22263       if (!ast_strlen_zero(p->tohost)) {
22264          ast_copy_string(ca->hostname, p->tohost, sizeof(ca->hostname));
22265       }
22266    }
22267    /* Create a client connection for address, this does not start the connection, just sets it up. */
22268    if (!(s->tcptls_session = ast_tcptls_client_create(ca))) {
22269       goto create_tcptls_session_fail;
22270    }
22271 
22272    s->fd = s->tcptls_session->fd;
22273 
22274    /* client connections need to have the sip_threadinfo object created before
22275     * the thread is detached.  This ensures the alert_pipe is up before it will
22276     * be used.  Note that this function links the new threadinfo object into the
22277     * threadt container. */
22278    if (!(th = sip_threadinfo_create(s->tcptls_session, s->type))) {
22279       goto create_tcptls_session_fail;
22280 
22281    }
22282 
22283    /* Give the new thread a reference to the tcptls_session */
22284    ao2_ref(s->tcptls_session, +1);
22285 
22286    if (ast_pthread_create_background(&ca->master, NULL, sip_tcp_worker_fn, s->tcptls_session)) {
22287       ast_debug(1, "Unable to launch '%s'.", ca->name);
22288       ao2_ref(s->tcptls_session, -1); /* take away the thread ref we just gave it */
22289       goto create_tcptls_session_fail;
22290    }
22291 
22292    return s->fd;
22293 
22294 create_tcptls_session_fail:
22295    if (ca) {
22296       ao2_t_ref(ca, -1, "failed to create client, getting rid of client tcptls_session arguments");
22297    }
22298    if (s->tcptls_session) {
22299       close(tcptls_session->fd);
22300       s->fd = tcptls_session->fd = -1;
22301       ao2_ref(s->tcptls_session, -1);
22302       s->tcptls_session = NULL;
22303    }
22304    if (th) {
22305       ao2_t_unlink(threadt, th, "Removing tcptls thread info object, thread failed to open");
22306    }
22307 
22308    return -1;
22309 }
22310 
22311 /*!
22312  * \brief Small function to parse a config line for a host with a transport
22313  *        i.e. tls://www.google.com:8056
22314  */
22315 static int sip_parse_host(char *line, int lineno, char **hostname, int *portnum, enum sip_transport *transport)
22316 {
22317    char *port;
22318 
22319    if ((*hostname = strstr(line, "://"))) {
22320       *hostname += 3;
22321 
22322       if (!strncasecmp(line, "tcp", 3))
22323          *transport = SIP_TRANSPORT_TCP;
22324       else if (!strncasecmp(line, "tls", 3))
22325          *transport = SIP_TRANSPORT_TLS;
22326       else if (!strncasecmp(line, "udp", 3))
22327          *transport = SIP_TRANSPORT_UDP;
22328       else
22329          ast_log(LOG_NOTICE, "'%.3s' is not a valid transport type on line %d of sip.conf. defaulting to udp.\n", line, lineno);
22330    } else {
22331       *hostname = line;
22332       *transport = SIP_TRANSPORT_UDP;
22333    }
22334 
22335    if ((line = strrchr(*hostname, '@')))
22336       line++;
22337    else
22338       line = *hostname;
22339 
22340    if ((port = strrchr(line, ':'))) {
22341       *port++ = '\0';
22342 
22343       if (!sscanf(port, "%5u", portnum)) {
22344          ast_log(LOG_NOTICE, "'%s' is not a valid port number on line %d of sip.conf. using default.\n", port, lineno);
22345          port = NULL;
22346       }
22347    }
22348 
22349    if (!port) {
22350       if (*transport & SIP_TRANSPORT_TLS) {
22351          *portnum = STANDARD_TLS_PORT;
22352       } else {
22353          *portnum = STANDARD_SIP_PORT;
22354       }
22355    }
22356 
22357    return 0;
22358 }
22359 
22360 /*!
22361  * \brief Get cached MWI info
22362  * \retval 0 At least one message is waiting
22363  * \retval 1 no messages waiting
22364  */
22365 static int get_cached_mwi(struct sip_peer *peer, int *new, int *old)
22366 {
22367    struct sip_mailbox *mailbox;
22368 
22369    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
22370       struct ast_event *event;
22371       event = ast_event_get_cached(AST_EVENT_MWI,
22372          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
22373          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
22374          AST_EVENT_IE_END);
22375       if (!event)
22376          continue;
22377       *new += ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
22378       *old += ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
22379       ast_event_destroy(event);
22380    }
22381 
22382    return (*new || *old) ? 0 : 1;
22383 }
22384 
22385 /*! \brief Send message waiting indication to alert peer that they've got voicemail */
22386 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only)
22387 {
22388    /* Called with peerl lock, but releases it */
22389    struct sip_pvt *p;
22390    int newmsgs = 0, oldmsgs = 0;
22391 
22392    if (ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY) && !peer->mwipvt)
22393       return 0;
22394 
22395    /* Do we have an IP address? If not, skip this peer */
22396    if (!peer->addr.sin_addr.s_addr && !peer->defaddr.sin_addr.s_addr) 
22397       return 0;
22398 
22399    if (event) {
22400       newmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
22401       oldmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
22402    } else if (!cache_only) { /* Fall back to manually checking the mailbox */
22403       struct ast_str *mailbox_str = ast_str_alloca(512);
22404       peer_mailboxes_to_str(&mailbox_str, peer);
22405       ast_app_inboxcount(mailbox_str->str, &newmsgs, &oldmsgs);
22406    } else {
22407       get_cached_mwi(peer, &newmsgs, &oldmsgs);
22408    }
22409    
22410    if (peer->mwipvt) {
22411       /* Base message on subscription */
22412       p = dialog_ref(peer->mwipvt, "sip_send_mwi_to_peer: Setting dialog ptr p from peer->mwipvt-- should this be done?");
22413    } else {
22414       /* Build temporary dialog for this message */
22415       if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) 
22416          return -1;
22417       /* If we don't set the socket type to 0, then create_addr_from_peer will fail immediately if the peer
22418        * uses any transport other than UDP. We set the type to 0 here and then let create_addr_from_peer copy 
22419        * the peer's socket information to the sip_pvt we just allocated
22420        */
22421       set_socket_transport(&p->socket, 0);
22422       if (create_addr_from_peer(p, peer)) {
22423          /* Maybe they're not registered, etc. */
22424          dialog_unlink_all(p, TRUE, TRUE);
22425          dialog_unref(p, "unref dialog p just created via sip_alloc");
22426          /* sip_destroy(p); */
22427          return 0;
22428       }
22429       /* Recalculate our side, and recalculate Call ID */
22430       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
22431       build_via(p);
22432       ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
22433       build_callid_pvt(p);
22434       ao2_t_link(dialogs, p, "Linking in under new name");
22435       /* Destroy this session after 32 secs */
22436       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22437    }
22438 
22439    /* Send MWI */
22440    ast_set_flag(&p->flags[0], SIP_OUTGOING);
22441    /* the following will decrement the refcount on p as it finishes */
22442    transmit_notify_with_mwi(p, newmsgs, oldmsgs, peer->vmexten);
22443    dialog_unref(p, "unref dialog ptr p just before it goes out of scope at the end of sip_send_mwi_to_peer.");
22444    return 0;
22445 }
22446 
22447 /*! \brief helper function for the monitoring thread -- seems to be called with the assumption that the dialog is locked */
22448 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t)
22449 {
22450    /* If we have no RTP or no active owner, no need to check timers */
22451    if (!dialog->rtp || !dialog->owner)
22452       return;
22453    /* If the call is not in UP state or redirected outside Asterisk, no need to check timers */
22454 
22455    if (dialog->owner->_state != AST_STATE_UP || dialog->redirip.sin_addr.s_addr)
22456       return;
22457 
22458    /* If the call is involved in a T38 fax session do not check RTP timeout */
22459    if (dialog->t38.state == T38_ENABLED)
22460       return;
22461 
22462    /* If we have no timers set, return now */
22463    if ((ast_rtp_get_rtpkeepalive(dialog->rtp) == 0) && (ast_rtp_get_rtptimeout(dialog->rtp) == 0) && (ast_rtp_get_rtpholdtimeout(dialog->rtp) == 0))
22464       return;
22465 
22466    /* Check AUDIO RTP keepalives */
22467    if (dialog->lastrtptx && ast_rtp_get_rtpkeepalive(dialog->rtp) &&
22468           (t > dialog->lastrtptx + ast_rtp_get_rtpkeepalive(dialog->rtp))) {
22469       /* Need to send an empty RTP packet */
22470       dialog->lastrtptx = time(NULL);
22471       ast_rtp_sendcng(dialog->rtp, 0);
22472    }
22473 
22474    /*! \todo Check video RTP keepalives
22475 
22476       Do we need to move the lastrtptx to the RTP structure to have one for audio and one
22477       for video? It really does belong to the RTP structure.
22478    */
22479 
22480    /* Check AUDIO RTP timers */
22481    if (dialog->lastrtprx && (ast_rtp_get_rtptimeout(dialog->rtp) || ast_rtp_get_rtpholdtimeout(dialog->rtp)) &&
22482           (t > dialog->lastrtprx + ast_rtp_get_rtptimeout(dialog->rtp))) {
22483 
22484       /* Might be a timeout now -- see if we're on hold */
22485       struct sockaddr_in sin;
22486       ast_rtp_get_peer(dialog->rtp, &sin);
22487       if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD) || (ast_rtp_get_rtpholdtimeout(dialog->rtp) &&
22488            (t > dialog->lastrtprx + ast_rtp_get_rtpholdtimeout(dialog->rtp)))) {
22489          /* Needs a hangup */
22490          if (ast_rtp_get_rtptimeout(dialog->rtp)) {
22491             while (dialog->owner && ast_channel_trylock(dialog->owner)) {
22492                sip_pvt_unlock(dialog);
22493                usleep(1);
22494                sip_pvt_lock(dialog);
22495             }
22496             if (!dialog->owner) {
22497                return; /* channel hangup can occur during deadlock avoidance. */
22498             }
22499             ast_log(LOG_NOTICE, "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
22500                dialog->owner->name, (long) (t - dialog->lastrtprx));
22501             /* Issue a softhangup */
22502             ast_softhangup_nolock(dialog->owner, AST_SOFTHANGUP_DEV);
22503             ast_channel_unlock(dialog->owner);
22504             /* forget the timeouts for this call, since a hangup
22505                has already been requested and we don't want to
22506                repeatedly request hangups
22507             */
22508             ast_rtp_set_rtptimeout(dialog->rtp, 0);
22509             ast_rtp_set_rtpholdtimeout(dialog->rtp, 0);
22510             if (dialog->vrtp) {
22511                ast_rtp_set_rtptimeout(dialog->vrtp, 0);
22512                ast_rtp_set_rtpholdtimeout(dialog->vrtp, 0);
22513             }
22514          }
22515       }
22516    }
22517 }
22518 
22519 /*! \brief The SIP monitoring thread 
22520 \note This thread monitors all the SIP sessions and peers that needs notification of mwi
22521    (and thus do not have a separate thread) indefinitely 
22522 */
22523 static void *do_monitor(void *data)
22524 {
22525    int res;
22526    time_t t;
22527    int reloading;
22528 
22529    /* Add an I/O event to our SIP UDP socket */
22530    if (sipsock > -1) 
22531       sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
22532 
22533    /* From here on out, we die whenever asked */
22534    for(;;) {
22535       /* Check for a reload request */
22536       ast_mutex_lock(&sip_reload_lock);
22537       reloading = sip_reloading;
22538       sip_reloading = FALSE;
22539       ast_mutex_unlock(&sip_reload_lock);
22540       if (reloading) {
22541          ast_verb(1, "Reloading SIP\n");
22542          sip_do_reload(sip_reloadreason);
22543 
22544          /* Change the I/O fd of our UDP socket */
22545          if (sipsock > -1) {
22546             if (sipsock_read_id)
22547                sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
22548             else
22549                sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
22550          } else if (sipsock_read_id) {
22551             ast_io_remove(io, sipsock_read_id);
22552             sipsock_read_id = NULL;
22553          }
22554       }
22555 
22556       /* Check for dialogs needing to be killed */
22557       t = time(NULL);
22558       /* don't scan the dialogs list if it hasn't been a reasonable period
22559          of time since the last time we did it (when MWI is being sent, we can
22560          get back to this point every millisecond or less)
22561       */
22562       ao2_t_callback(dialogs, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, dialog_needdestroy, &t,
22563             "callback to remove dialogs w/needdestroy");
22564 
22565       /* the old methodology would be to restart the search for dialogs to delete with every 
22566          dialog that was found and destroyed, probably because the list contents would change,
22567          so we'd need to restart. This isn't the best thing to do with callbacks. */
22568 
22569       /* XXX TODO The scheduler usage in this module does not have sufficient 
22570        * synchronization being done between running the scheduler and places 
22571        * scheduling tasks.  As it is written, any scheduled item may not run 
22572        * any sooner than about  1 second, regardless of whether a sooner time 
22573        * was asked for. */
22574 
22575       pthread_testcancel();
22576       /* Wait for sched or io */
22577       res = ast_sched_wait(sched);
22578       if ((res < 0) || (res > 1000))
22579          res = 1000;
22580       res = ast_io_wait(io, res);
22581       if (res > 20)
22582          ast_debug(1, "chan_sip: ast_io_wait ran %d all at once\n", res);
22583       ast_mutex_lock(&monlock);
22584       res = ast_sched_runq(sched);
22585       if (res >= 20)
22586          ast_debug(1, "chan_sip: ast_sched_runq ran %d all at once\n", res);
22587       ast_mutex_unlock(&monlock);
22588    }
22589 
22590    /* Never reached */
22591    return NULL;
22592 }
22593 
22594 /*! \brief Start the channel monitor thread */
22595 static int restart_monitor(void)
22596 {
22597    /* If we're supposed to be stopped -- stay stopped */
22598    if (monitor_thread == AST_PTHREADT_STOP)
22599       return 0;
22600    ast_mutex_lock(&monlock);
22601    if (monitor_thread == pthread_self()) {
22602       ast_mutex_unlock(&monlock);
22603       ast_log(LOG_WARNING, "Cannot kill myself\n");
22604       return -1;
22605    }
22606    if (monitor_thread != AST_PTHREADT_NULL) {
22607       /* Wake up the thread */
22608       pthread_kill(monitor_thread, SIGURG);
22609    } else {
22610       /* Start a new monitor */
22611       if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
22612          ast_mutex_unlock(&monlock);
22613          ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
22614          return -1;
22615       }
22616    }
22617    ast_mutex_unlock(&monlock);
22618    return 0;
22619 }
22620 
22621 
22622 /*! \brief Session-Timers: Restart session timer */
22623 static void restart_session_timer(struct sip_pvt *p)
22624 {
22625    if (!p->stimer) {
22626       ast_log(LOG_WARNING, "Null stimer in restart_session_timer - %s\n", p->callid);
22627       return;
22628    }
22629 
22630    if (p->stimer->st_active == TRUE) {
22631       AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
22632             dialog_unref(p, "Removing session timer ref"));
22633       ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
22634       start_session_timer(p);
22635    }
22636 }
22637 
22638 
22639 /*! \brief Session-Timers: Stop session timer */
22640 static void stop_session_timer(struct sip_pvt *p)
22641 {
22642    if (!p->stimer) {
22643       ast_log(LOG_WARNING, "Null stimer in stop_session_timer - %s\n", p->callid);
22644       return;
22645    }
22646 
22647    if (p->stimer->st_active == TRUE) {
22648       p->stimer->st_active = FALSE;
22649       AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
22650             dialog_unref(p, "removing session timer ref"));
22651       ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
22652    }
22653 }
22654 
22655 
22656 /*! \brief Session-Timers: Start session timer */
22657 static void start_session_timer(struct sip_pvt *p)
22658 {
22659    if (!p->stimer) {
22660       ast_log(LOG_WARNING, "Null stimer in start_session_timer - %s\n", p->callid);
22661       return;
22662    }
22663 
22664    p->stimer->st_schedid  = ast_sched_add(sched, p->stimer->st_interval * 1000 / 2, proc_session_timer, 
22665          dialog_ref(p, "adding session timer ref"));
22666    if (p->stimer->st_schedid < 0) {
22667       dialog_unref(p, "removing session timer ref");
22668       ast_log(LOG_ERROR, "ast_sched_add failed.\n");
22669    }
22670    ast_debug(2, "Session timer started: %d - %s\n", p->stimer->st_schedid, p->callid);
22671 }
22672 
22673 
22674 /*! \brief Session-Timers: Process session refresh timeout event */
22675 static int proc_session_timer(const void *vp)
22676 {
22677    struct sip_pvt *p = (struct sip_pvt *) vp;
22678    int sendreinv = FALSE;
22679    int res = 0;
22680 
22681    if (!p->stimer) {
22682       ast_log(LOG_WARNING, "Null stimer in proc_session_timer - %s\n", p->callid);
22683       goto return_unref;
22684    }
22685 
22686    ast_debug(2, "Session timer expired: %d - %s\n", p->stimer->st_schedid, p->callid);
22687 
22688    if (!p->owner) {
22689       goto return_unref;
22690    }
22691 
22692    if ((p->stimer->st_active != TRUE) || (p->owner->_state != AST_STATE_UP)) {
22693       goto return_unref;
22694    }
22695 
22696    switch (p->stimer->st_ref) {
22697    case SESSION_TIMER_REFRESHER_UAC:
22698       if (p->outgoing_call == TRUE) {
22699          sendreinv = TRUE;
22700       }
22701       break;
22702    case SESSION_TIMER_REFRESHER_UAS:
22703       if (p->outgoing_call != TRUE) {
22704          sendreinv = TRUE;
22705       }
22706       break;
22707    default:
22708       ast_log(LOG_ERROR, "Unknown session refresher %d\n", p->stimer->st_ref);
22709       goto return_unref;
22710    }
22711 
22712    if (sendreinv == TRUE) {
22713       res = 1;
22714       transmit_reinvite_with_sdp(p, FALSE, TRUE);
22715    } else {
22716       p->stimer->st_expirys++;
22717       if (p->stimer->st_expirys >= 2) {
22718          if (p->stimer->quit_flag) {
22719             goto return_unref;
22720          }
22721          ast_log(LOG_WARNING, "Session-Timer expired - %s\n", p->callid);
22722          sip_pvt_lock(p);
22723          while (p->owner && ast_channel_trylock(p->owner)) {
22724             sip_pvt_unlock(p);
22725             usleep(1);
22726             if (p->stimer && p->stimer->quit_flag) {
22727                goto return_unref;
22728             }
22729             sip_pvt_lock(p);
22730          }
22731 
22732          ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
22733          ast_channel_unlock(p->owner);
22734          sip_pvt_unlock(p);
22735       }
22736    }
22737 
22738 return_unref:
22739    if (!res) {
22740       /* An error occurred.  Stop session timer processing */
22741       if (p->stimer) {
22742          p->stimer->st_schedid = -1;
22743          stop_session_timer(p);
22744       }
22745 
22746       /* If we are not asking to be rescheduled, then we need to release our
22747        * reference to the dialog. */
22748       dialog_unref(p, "removing session timer ref");
22749    }
22750 
22751    return res;
22752 }
22753 
22754 
22755 /*! \brief Session-Timers: Function for parsing Min-SE header */
22756 int parse_minse (const char *p_hdrval, int *const p_interval)
22757 {
22758    if (ast_strlen_zero(p_hdrval)) {
22759       ast_log(LOG_WARNING, "Null Min-SE header\n");
22760       return -1;
22761    }
22762 
22763    *p_interval = 0;
22764    p_hdrval = ast_skip_blanks(p_hdrval);
22765    if (!sscanf(p_hdrval, "%30d", p_interval)) {
22766       ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
22767       return -1;
22768    }
22769 
22770    ast_debug(2, "Received Min-SE: %d\n", *p_interval);
22771    return 0;
22772 }
22773 
22774 
22775 /*! \brief Session-Timers: Function for parsing Session-Expires header */
22776 int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref)
22777 {
22778    char *p_token;
22779    int  ref_idx;
22780    char *p_se_hdr;
22781 
22782    if (ast_strlen_zero(p_hdrval)) {
22783       ast_log(LOG_WARNING, "Null Session-Expires header\n");
22784       return -1;
22785    }
22786 
22787    *p_ref = SESSION_TIMER_REFRESHER_AUTO;
22788    *p_interval = 0;
22789 
22790    p_se_hdr = ast_strdupa(p_hdrval);
22791    p_se_hdr = ast_skip_blanks(p_se_hdr);
22792 
22793    while ((p_token = strsep(&p_se_hdr, ";"))) {
22794       p_token = ast_skip_blanks(p_token);
22795       if (!sscanf(p_token, "%30d", p_interval)) {
22796          ast_log(LOG_WARNING, "Parsing of Session-Expires failed\n");
22797          return -1;
22798       }
22799 
22800       ast_debug(2, "Session-Expires: %d\n", *p_interval);
22801 
22802       if (!p_se_hdr)
22803          continue;
22804 
22805       p_se_hdr = ast_skip_blanks(p_se_hdr);
22806       ref_idx = strlen("refresher=");
22807       if (!strncasecmp(p_se_hdr, "refresher=", ref_idx)) {
22808          p_se_hdr += ref_idx;
22809          p_se_hdr = ast_skip_blanks(p_se_hdr);
22810 
22811          if (!strncasecmp(p_se_hdr, "uac", strlen("uac"))) {
22812             *p_ref = SESSION_TIMER_REFRESHER_UAC;
22813             ast_debug(2, "Refresher: UAC\n");
22814          } else if (!strncasecmp(p_se_hdr, "uas", strlen("uas"))) {
22815             *p_ref = SESSION_TIMER_REFRESHER_UAS;
22816             ast_debug(2, "Refresher: UAS\n");
22817          } else {
22818             ast_log(LOG_WARNING, "Invalid refresher value %s\n", p_se_hdr);
22819             return -1;
22820          }
22821          break;
22822       }
22823    }
22824    return 0;
22825 }
22826 
22827 
22828 /*! \brief Handle 422 response to INVITE with session-timer requested
22829 
22830    Session-Timers:   An INVITE originated by Asterisk that asks for session-timers support
22831    from the UAS can result into a 422 response. This is how a UAS or an intermediary proxy 
22832    server tells Asterisk that the session refresh interval offered by Asterisk is too low 
22833    for them.  The proc_422_rsp() function handles a 422 response.  It extracts the Min-SE 
22834    header that comes back in 422 and sends a new INVITE accordingly. */
22835 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp)
22836 {
22837    int rtn;
22838    const char *p_hdrval;
22839    int minse;
22840 
22841    p_hdrval = get_header(rsp, "Min-SE");
22842    if (ast_strlen_zero(p_hdrval)) {
22843       ast_log(LOG_WARNING, "422 response without a Min-SE header %s\n", p_hdrval);
22844       return;
22845    }
22846    rtn = parse_minse(p_hdrval, &minse);
22847    if (rtn != 0) {
22848       ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
22849       return;
22850    }
22851    p->stimer->st_interval = minse;
22852    transmit_invite(p, SIP_INVITE, 1, 2); 
22853 }
22854 
22855 
22856 /*! \brief Get Max or Min SE (session timer expiry)
22857  * \param p pointer to the SIP dialog 
22858  * \param max if true, get max se, otherwise min se
22859 */
22860 int st_get_se(struct sip_pvt *p, int max)
22861 {
22862    if (max == TRUE) {
22863       if (p->stimer->st_cached_max_se) {
22864          return p->stimer->st_cached_max_se;
22865       } else if (p->peername) {
22866          struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
22867          if (pp) {
22868             p->stimer->st_cached_max_se = pp->stimer.st_max_se;
22869             unref_peer(pp, "unref peer pointer from find_peer call in st_get_se");
22870             return (p->stimer->st_cached_max_se);
22871          }
22872       }
22873       p->stimer->st_cached_max_se = global_max_se;
22874       return (p->stimer->st_cached_max_se);
22875    } else {
22876       if (p->stimer->st_cached_min_se) {
22877          return p->stimer->st_cached_min_se;
22878       } else if (p->peername) {
22879          struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
22880          if (pp) {
22881             p->stimer->st_cached_min_se = pp->stimer.st_min_se;
22882             unref_peer(pp, "unref peer pointer from find_peer call in st_get_se (2)");
22883             return (p->stimer->st_cached_min_se);
22884          }
22885       }
22886       p->stimer->st_cached_min_se = global_min_se;
22887       return (p->stimer->st_cached_min_se);
22888    }
22889 }
22890 
22891 
22892 /*! \brief Get the entity (UAC or UAS) that's acting as the session-timer refresher 
22893  * \param p pointer to the SIP dialog 
22894 */
22895 enum st_refresher st_get_refresher(struct sip_pvt *p)
22896 {
22897    if (p->stimer->st_cached_ref != SESSION_TIMER_REFRESHER_AUTO) 
22898       return p->stimer->st_cached_ref;
22899 
22900    if (p->peername) {
22901       struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
22902       if (pp) {
22903          p->stimer->st_cached_ref = pp->stimer.st_ref;
22904          unref_peer(pp, "unref peer pointer from find_peer call in st_get_refresher");
22905          return pp->stimer.st_ref;
22906       }
22907    }
22908    
22909    p->stimer->st_cached_ref = global_st_refresher;
22910    return global_st_refresher;
22911 }
22912 
22913 
22914 /*! \brief Get the session-timer mode 
22915  * \param p pointer to the SIP dialog 
22916 */
22917 enum st_mode st_get_mode(struct sip_pvt *p)
22918 {
22919    if (!p->stimer) 
22920       sip_st_alloc(p);
22921 
22922    if (p->stimer->st_cached_mode != SESSION_TIMER_MODE_INVALID) 
22923       return p->stimer->st_cached_mode;
22924 
22925    if (p->peername) {
22926       struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
22927       if (pp) {
22928          p->stimer->st_cached_mode = pp->stimer.st_mode_oper;
22929          unref_peer(pp, "unref peer pointer from find_peer call in st_get_mode");
22930          return pp->stimer.st_mode_oper;
22931       }
22932    }
22933 
22934    p->stimer->st_cached_mode = global_st_mode;
22935    return global_st_mode;
22936 }
22937 
22938 
22939 /*! \brief React to lack of answer to Qualify poke */
22940 static int sip_poke_noanswer(const void *data)
22941 {
22942    struct sip_peer *peer = (struct sip_peer *)data;
22943    
22944    peer->pokeexpire = -1;
22945 
22946    if (peer->lastms > -1) {
22947       ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE!  Last qualify: %d\n", peer->name, peer->lastms);
22948       if (sip_cfg.peer_rtupdate) {
22949          ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", "-1", SENTINEL);
22950       }
22951       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
22952       if (sip_cfg.regextenonqualify) {
22953          register_peer_exten(peer, FALSE);
22954       }
22955    }
22956 
22957    if (peer->call) {
22958       dialog_unlink_all(peer->call, TRUE, TRUE);
22959       peer->call = dialog_unref(peer->call, "unref dialog peer->call");
22960       /* peer->call = sip_destroy(peer->call);*/
22961    }
22962    
22963    peer->lastms = -1;
22964    ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
22965 
22966    /* Try again quickly */
22967    AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, 
22968          DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer,
22969          unref_peer(_data, "removing poke peer ref"),
22970          unref_peer(peer, "removing poke peer ref"),
22971          ref_peer(peer, "adding poke peer ref"));
22972 
22973    /* Release the ref held by the running scheduler entry */
22974    unref_peer(peer, "release peer poke noanswer ref");
22975 
22976    return 0;
22977 }
22978 
22979 /*! \brief Check availability of peer, also keep NAT open
22980 \note This is done with 60 seconds between each ping,
22981    unless forced by cli or manager. If peer is unreachable,
22982    we check every 10th second by default. 
22983 */
22984 static int sip_poke_peer(struct sip_peer *peer, int force)
22985 {
22986    struct sip_pvt *p;
22987    int xmitres = 0;
22988    
22989    if ((!peer->maxms && !force) || !peer->addr.sin_addr.s_addr) {
22990       /* IF we have no IP, or this isn't to be monitored, return
22991         immediately after clearing things out */
22992       AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
22993             unref_peer(peer, "removing poke peer ref"));
22994       
22995       peer->lastms = 0;
22996       if (peer->call) {
22997          peer->call = dialog_unref(peer->call, "unref dialog peer->call");
22998       }
22999       return 0;
23000    }
23001    if (peer->call) {
23002       if (sipdebug) {
23003          ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
23004       }
23005       dialog_unlink_all(peer->call, TRUE, TRUE);
23006       peer->call = dialog_unref(peer->call, "unref dialog peer->call");
23007       /* peer->call = sip_destroy(peer->call); */
23008    }
23009    if (!(p = sip_alloc(NULL, NULL, 0, SIP_OPTIONS, NULL))) {
23010       return -1;
23011    }
23012    peer->call = dialog_ref(p, "copy sip alloc from p to peer->call");
23013    
23014    p->sa = peer->addr;
23015    p->recv = peer->addr;
23016    copy_socket_data(&p->socket, &peer->socket);
23017    ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
23018    ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
23019 
23020    /* Send OPTIONs to peer's fullcontact */
23021    if (!ast_strlen_zero(peer->fullcontact))
23022       ast_string_field_set(p, fullcontact, peer->fullcontact);
23023 
23024    if (!ast_strlen_zero(peer->tohost))
23025       ast_string_field_set(p, tohost, peer->tohost);
23026    else
23027       ast_string_field_set(p, tohost, ast_inet_ntoa(peer->addr.sin_addr));
23028 
23029    /* Recalculate our side, and recalculate Call ID */
23030    ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
23031    build_via(p);
23032    ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
23033    build_callid_pvt(p);
23034    ao2_t_link(dialogs, p, "Linking in under new name");
23035 
23036    AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
23037          unref_peer(peer, "removing poke peer ref"));
23038    
23039    if (p->relatedpeer)
23040       p->relatedpeer = unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
23041    p->relatedpeer = ref_peer(peer, "setting the relatedpeer field in the dialog");
23042    ast_set_flag(&p->flags[0], SIP_OUTGOING);
23043 #ifdef VOCAL_DATA_HACK
23044    ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
23045    xmitres = transmit_invite(p, SIP_INVITE, 0, 2); /* sinks the p refcount */
23046 #else
23047    xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2); /* sinks the p refcount */
23048 #endif
23049    peer->ps = ast_tvnow();
23050    if (xmitres == XMIT_ERROR) {
23051       sip_poke_noanswer(peer);   /* Immediately unreachable, network problems */
23052    } else if (!force) {
23053       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, peer->maxms * 2, sip_poke_noanswer, peer,
23054             unref_peer(_data, "removing poke peer ref"),
23055             unref_peer(peer, "removing poke peer ref"),
23056             ref_peer(peer, "adding poke peer ref"));
23057    }
23058    dialog_unref(p, "unref dialog at end of sip_poke_peer, obtained from sip_alloc, just before it goes out of scope");
23059    return 0;
23060 }
23061 
23062 /*! \brief Part of PBX channel interface
23063 \note
23064 \par  Return values:---
23065 
23066    If we have qualify on and the device is not reachable, regardless of registration
23067    state we return AST_DEVICE_UNAVAILABLE
23068 
23069    For peers with call limit:
23070       - not registered        AST_DEVICE_UNAVAILABLE
23071       - registered, no call         AST_DEVICE_NOT_INUSE
23072       - registered, active calls    AST_DEVICE_INUSE
23073       - registered, call limit reached AST_DEVICE_BUSY
23074       - registered, onhold       AST_DEVICE_ONHOLD
23075       - registered, ringing         AST_DEVICE_RINGING
23076 
23077    For peers without call limit:
23078       - not registered        AST_DEVICE_UNAVAILABLE
23079       - registered            AST_DEVICE_NOT_INUSE
23080       - fixed IP (!dynamic)         AST_DEVICE_NOT_INUSE
23081    
23082    Peers that does not have a known call and can't be reached by OPTIONS
23083       - unreachable           AST_DEVICE_UNAVAILABLE
23084 
23085    If we return AST_DEVICE_UNKNOWN, the device state engine will try to find
23086    out a state by walking the channel list.
23087 
23088    The queue system (\ref app_queue.c) treats a member as "active"
23089    if devicestate is != AST_DEVICE_UNAVAILBALE && != AST_DEVICE_INVALID
23090 
23091    When placing a call to the queue member, queue system sets a member to busy if
23092    != AST_DEVICE_NOT_INUSE and != AST_DEVICE_UNKNOWN
23093 
23094 */
23095 static int sip_devicestate(void *data)
23096 {
23097    char *host;
23098    char *tmp;
23099    struct sip_peer *p;
23100 
23101    int res = AST_DEVICE_INVALID;
23102 
23103    /* make sure data is not null. Maybe unnecessary, but better be safe */
23104    host = ast_strdupa(data ? data : "");
23105    if ((tmp = strchr(host, '@')))
23106       host = tmp + 1;
23107 
23108    ast_debug(3, "Checking device state for peer %s\n", host);
23109 
23110    /* If find_peer asks for a realtime peer, then this breaks rtautoclear.  This
23111     * is because when a peer tries to autoexpire, the last thing it does is to
23112     * queue up an event telling the system that the devicestate has changed
23113     * (presumably to unavailable).  If we ask for a realtime peer here, this would
23114     * load it BACK into memory, thus defeating the point of trying to clear dead
23115     * hosts out of memory.
23116     */
23117    if ((p = find_peer(host, NULL, FALSE, FINDALLDEVICES, TRUE, 0))) {
23118       if (p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) {
23119          /* we have an address for the peer */
23120       
23121          /* Check status in this order
23122             - Hold
23123             - Ringing
23124             - Busy (enforced only by call limit)
23125             - Inuse (we have a call)
23126             - Unreachable (qualify)
23127             If we don't find any of these state, report AST_DEVICE_NOT_INUSE
23128             for registered devices */
23129 
23130          if (p->onHold)
23131             /* First check for hold or ring states */
23132             res = AST_DEVICE_ONHOLD;
23133          else if (p->inRinging) {
23134             if (p->inRinging == p->inUse)
23135                res = AST_DEVICE_RINGING;
23136             else
23137                res = AST_DEVICE_RINGINUSE;
23138          } else if (p->call_limit && (p->inUse == p->call_limit))
23139             /* check call limit */
23140             res = AST_DEVICE_BUSY;
23141          else if (p->call_limit && p->busy_level && p->inUse >= p->busy_level)
23142             /* We're forcing busy before we've reached the call limit */
23143             res = AST_DEVICE_BUSY;
23144          else if (p->call_limit && p->inUse)
23145             /* Not busy, but we do have a call */
23146             res = AST_DEVICE_INUSE;
23147          else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0))) 
23148             /* We don't have a call. Are we reachable at all? Requires qualify= */
23149             res = AST_DEVICE_UNAVAILABLE;
23150          else  /* Default reply if we're registered and have no other data */
23151             res = AST_DEVICE_NOT_INUSE;
23152       } else {
23153          /* there is no address, it's unavailable */
23154          res = AST_DEVICE_UNAVAILABLE;
23155       }
23156       unref_peer(p, "unref_peer, from sip_devicestate, release ref from find_peer");
23157    } else {
23158       res = AST_DEVICE_UNKNOWN;
23159    }
23160 
23161    return res;
23162 }
23163 
23164 /*! \brief PBX interface function -build SIP pvt structure 
23165  * SIP calls initiated by the PBX arrive here. 
23166  *
23167  * \verbatim   
23168  *    SIP Dial string syntax
23169  *    SIP/exten@host!dnid
23170  * or SIP/host/exten!dnid
23171  * or SIP/host!dnid
23172  * \endverbatim
23173 */
23174 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause)
23175 {
23176    struct sip_pvt *p;
23177    struct ast_channel *tmpc = NULL;
23178    char *ext = NULL, *host;
23179    char tmp[256];
23180    char *dest = data;
23181    char *dnid;
23182    char *secret = NULL;
23183    char *md5secret = NULL;
23184    char *authname = NULL;
23185    char *trans = NULL;
23186    enum sip_transport transport = 0;
23187    int oldformat = format;
23188 
23189    /* mask request with some set of allowed formats.
23190     * XXX this needs to be fixed.
23191     * The original code uses AST_FORMAT_AUDIO_MASK, but it is
23192     * unclear what to use here. We have global_capabilities, which is
23193     * configured from sip.conf, and sip_tech.capabilities, which is
23194     * hardwired to all audio formats.
23195     */
23196    format &= AST_FORMAT_AUDIO_MASK;
23197    if (!format) {
23198       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));
23199       *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;   /* Can't find codec to connect to host */
23200       return NULL;
23201    }
23202    ast_debug(1, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));
23203 
23204    if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE, NULL))) {
23205       ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", dest);
23206       *cause = AST_CAUSE_SWITCH_CONGESTION;
23207       return NULL;
23208    }
23209 
23210    p->outgoing_call = TRUE;
23211 
23212    if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
23213       dialog_unlink_all(p, TRUE, TRUE);
23214       dialog_unref(p, "unref dialog p from mem fail");
23215       /* sip_destroy(p); */
23216       ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
23217       *cause = AST_CAUSE_SWITCH_CONGESTION;
23218       return NULL;
23219    }
23220 
23221    /* Save the destination, the SIP dial string */
23222    ast_copy_string(tmp, dest, sizeof(tmp));
23223 
23224 
23225    /* Find DNID and take it away */
23226    dnid = strchr(tmp, '!');
23227    if (dnid != NULL) {
23228       *dnid++ = '\0';
23229       ast_string_field_set(p, todnid, dnid);
23230    }
23231 
23232    /* Find at sign - @ */
23233    host = strchr(tmp, '@');
23234    if (host) {
23235       *host++ = '\0';
23236       ext = tmp;
23237       secret = strchr(ext, ':');
23238    }
23239    if (secret) {
23240       *secret++ = '\0';
23241       md5secret = strchr(secret, ':');
23242    }
23243    if (md5secret) {
23244       *md5secret++ = '\0';
23245       authname = strchr(md5secret, ':');
23246    }
23247    if (authname) {
23248       *authname++ = '\0';
23249       trans = strchr(authname, ':');
23250    }
23251    if (trans) {
23252       *trans++ = '\0';
23253       if (!strcasecmp(trans, "tcp"))
23254          transport = SIP_TRANSPORT_TCP;
23255       else if (!strcasecmp(trans, "tls"))
23256          transport = SIP_TRANSPORT_TLS;
23257       else {
23258          if (strcasecmp(trans, "udp"))
23259             ast_log(LOG_WARNING, "'%s' is not a valid transport option to Dial() for SIP calls, using udp by default.\n", trans);
23260          transport = SIP_TRANSPORT_UDP;
23261       }
23262    } else { /* use default */
23263       transport = SIP_TRANSPORT_UDP;
23264    }
23265 
23266    if (!host) {
23267       ext = strchr(tmp, '/');
23268       if (ext) 
23269          *ext++ = '\0';
23270       host = tmp;
23271    }
23272 
23273    set_socket_transport(&p->socket, transport);
23274 
23275    /* We now have 
23276       host = peer name, DNS host name or DNS domain (for SRV) 
23277       ext = extension (user part of URI)
23278       dnid = destination of the call (applies to the To: header)
23279    */
23280    if (create_addr(p, host, NULL, 1)) {
23281       *cause = AST_CAUSE_UNREGISTERED;
23282       ast_debug(3, "Cant create SIP call - target device not registered\n");
23283       dialog_unlink_all(p, TRUE, TRUE);
23284       dialog_unref(p, "unref dialog p UNREGISTERED");
23285       /* sip_destroy(p); */
23286       return NULL;
23287    }
23288    if (ast_strlen_zero(p->peername) && ext)
23289       ast_string_field_set(p, peername, ext);
23290    /* Recalculate our side, and recalculate Call ID */
23291    ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
23292    build_via(p);
23293    ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
23294    build_callid_pvt(p);
23295    ao2_t_link(dialogs, p, "Linking in under new name");
23296    
23297    /* We have an extension to call, don't use the full contact here */
23298    /* This to enable dialing registered peers with extension dialling,
23299       like SIP/peername/extension   
23300       SIP/peername will still use the full contact 
23301     */
23302    if (ext) {
23303       ast_string_field_set(p, username, ext);
23304       ast_string_field_set(p, fullcontact, NULL);
23305    }
23306    if (secret && !ast_strlen_zero(secret))
23307       ast_string_field_set(p, peersecret, secret);
23308 
23309    if (md5secret && !ast_strlen_zero(md5secret))
23310       ast_string_field_set(p, peermd5secret, md5secret);
23311 
23312    if (authname && !ast_strlen_zero(authname))
23313       ast_string_field_set(p, authname, authname);
23314 #if 0
23315    printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
23316 #endif
23317    p->prefcodec = oldformat;           /* Format for this call */
23318    p->jointcapability = oldformat & p->capability;
23319    sip_pvt_lock(p);
23320    tmpc = sip_new(p, AST_STATE_DOWN, host);  /* Place the call */
23321    if (sip_cfg.callevents)
23322       manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
23323          "Channel: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
23324          p->owner? p->owner->name : "", "SIP", p->callid, p->fullcontact, p->peername);
23325    sip_pvt_unlock(p);
23326    if (!tmpc) {
23327       dialog_unlink_all(p, TRUE, TRUE);
23328       /* sip_destroy(p); */
23329    }
23330    dialog_unref(p, "toss pvt ptr at end of sip_request_call");
23331    ast_update_use_count();
23332    restart_monitor();
23333    return tmpc;
23334 }
23335 
23336 /*! \brief Parse insecure= setting in sip.conf and set flags according to setting */
23337 static void set_insecure_flags (struct ast_flags *flags, const char *value, int lineno)
23338 {
23339    if (ast_strlen_zero(value))
23340       return;
23341 
23342    if (!ast_false(value)) {
23343       char buf[64];
23344       char *word, *next;
23345 
23346       ast_copy_string(buf, value, sizeof(buf));
23347       next = buf;
23348       while ((word = strsep(&next, ","))) {
23349          if (!strcasecmp(word, "port"))
23350             ast_set_flag(&flags[0], SIP_INSECURE_PORT);
23351          else if (!strcasecmp(word, "invite"))
23352             ast_set_flag(&flags[0], SIP_INSECURE_INVITE);
23353          else
23354             ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
23355       }
23356    }
23357 }
23358 
23359 /*!
23360   \brief Handle T.38 configuration options common to users and peers
23361   \returns non-zero if any config options were handled, zero otherwise
23362 */
23363 static int handle_t38_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v,
23364                int *maxdatagram)
23365 {
23366    int res = 1;
23367 
23368    if (!strcasecmp(v->name, "t38pt_udptl")) {
23369       char *buf = ast_strdupa(v->value);
23370       char *word, *next = buf;
23371 
23372       ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT);
23373 
23374       while ((word = strsep(&next, ","))) {
23375          if (ast_true(word) || !strcasecmp(word, "fec")) {
23376             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
23377             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_FEC);
23378          } else if (!strcasecmp(word, "redundancy")) {
23379             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
23380             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY);
23381          } else if (!strcasecmp(word, "none")) {
23382             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
23383             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
23384          } else if (!strncasecmp(word, "maxdatagram=", 12)) {
23385             if (sscanf(&word[12], "%30u", maxdatagram) != 1) {
23386                ast_log(LOG_WARNING, "Invalid maxdatagram '%s' at line %d of %s\n", v->value, v->lineno, config);
23387                *maxdatagram = global_t38_maxdatagram;
23388             }
23389          }
23390       }
23391    } else if (!strcasecmp(v->name, "t38pt_usertpsource")) {
23392       ast_set_flag(&mask[1], SIP_PAGE2_UDPTL_DESTINATION);
23393       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_UDPTL_DESTINATION);
23394    } else if (!strcasecmp(v->name, "forwardloopdetected")) {
23395       ast_set_flag(&mask[1], SIP_PAGE2_FORWARD_LOOP_DETECTED);
23396       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_FORWARD_LOOP_DETECTED);
23397    } else {
23398       res = 0;
23399    }
23400 
23401    return res;
23402 }
23403 
23404 /*!
23405   \brief Handle flag-type options common to configuration of devices - peers
23406   \param flags array of two struct ast_flags
23407   \param mask array of two struct ast_flags
23408   \param v linked list of config variables to process
23409   \returns non-zero if any config options were handled, zero otherwise
23410 */
23411 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
23412 {
23413    int res = 1;
23414 
23415    if (!strcasecmp(v->name, "trustrpid")) {
23416       ast_set_flag(&mask[0], SIP_TRUSTRPID);
23417       ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
23418    } else if (!strcasecmp(v->name, "sendrpid")) {
23419       ast_set_flag(&mask[0], SIP_SENDRPID);
23420       ast_set2_flag(&flags[0], ast_true(v->value), SIP_SENDRPID);
23421    } else if (!strcasecmp(v->name, "g726nonstandard")) {
23422       ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
23423       ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
23424    } else if (!strcasecmp(v->name, "useclientcode")) {
23425       ast_set_flag(&mask[0], SIP_USECLIENTCODE);
23426       ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
23427    } else if (!strcasecmp(v->name, "dtmfmode")) {
23428       ast_set_flag(&mask[0], SIP_DTMF);
23429       ast_clear_flag(&flags[0], SIP_DTMF);
23430       if (!strcasecmp(v->value, "inband"))
23431          ast_set_flag(&flags[0], SIP_DTMF_INBAND);
23432       else if (!strcasecmp(v->value, "rfc2833"))
23433          ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
23434       else if (!strcasecmp(v->value, "info"))
23435          ast_set_flag(&flags[0], SIP_DTMF_INFO);
23436       else if (!strcasecmp(v->value, "shortinfo"))
23437          ast_set_flag(&flags[0], SIP_DTMF_SHORTINFO);
23438       else if (!strcasecmp(v->value, "auto"))
23439          ast_set_flag(&flags[0], SIP_DTMF_AUTO);
23440       else {
23441          ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
23442          ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
23443       }
23444    } else if (!strcasecmp(v->name, "nat")) {
23445       ast_set_flag(&mask[0], SIP_NAT);
23446       ast_clear_flag(&flags[0], SIP_NAT);
23447       if (!strcasecmp(v->value, "never"))
23448          ast_set_flag(&flags[0], SIP_NAT_NEVER);
23449       else if (!strcasecmp(v->value, "route"))
23450          ast_set_flag(&flags[0], SIP_NAT_ROUTE);
23451       else if (ast_true(v->value))
23452          ast_set_flag(&flags[0], SIP_NAT_ALWAYS);
23453       else
23454          ast_set_flag(&flags[0], SIP_NAT_RFC3581);
23455    } else if (!strcasecmp(v->name, "directmedia") || !strcasecmp(v->name, "canreinvite")) {
23456       ast_set_flag(&mask[0], SIP_REINVITE);
23457       ast_clear_flag(&flags[0], SIP_REINVITE);
23458       if (ast_true(v->value)) {
23459          ast_set_flag(&flags[0], SIP_DIRECT_MEDIA | SIP_DIRECT_MEDIA_NAT);
23460       } else if (!ast_false(v->value)) {
23461          char buf[64];
23462          char *word, *next = buf;
23463 
23464          ast_copy_string(buf, v->value, sizeof(buf));
23465          while ((word = strsep(&next, ","))) {
23466             if (!strcasecmp(word, "update")) {
23467                ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_DIRECT_MEDIA);
23468             } else if (!strcasecmp(word, "nonat")) {
23469                ast_set_flag(&flags[0], SIP_DIRECT_MEDIA);
23470                ast_clear_flag(&flags[0], SIP_DIRECT_MEDIA_NAT);
23471             } else {
23472                ast_log(LOG_WARNING, "Unknown directmedia mode '%s' on line %d\n", v->value, v->lineno);
23473             }
23474          }
23475       }
23476    } else if (!strcasecmp(v->name, "insecure")) {
23477       ast_set_flag(&mask[0], SIP_INSECURE);
23478       ast_clear_flag(&flags[0], SIP_INSECURE);
23479       set_insecure_flags(&flags[0], v->value, v->lineno);   
23480    } else if (!strcasecmp(v->name, "progressinband")) {
23481       ast_set_flag(&mask[0], SIP_PROG_INBAND);
23482       ast_clear_flag(&flags[0], SIP_PROG_INBAND);
23483       if (ast_true(v->value))
23484          ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
23485       else if (strcasecmp(v->value, "never"))
23486          ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
23487    } else if (!strcasecmp(v->name, "promiscredir")) {
23488       ast_set_flag(&mask[0], SIP_PROMISCREDIR);
23489       ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
23490    } else if (!strcasecmp(v->name, "videosupport")) {
23491       if (!strcasecmp(v->value, "always")) {
23492          ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
23493          ast_set_flag(&flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
23494       } else {
23495          ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
23496          ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
23497       }
23498    } else if (!strcasecmp(v->name, "textsupport")) {
23499       ast_set_flag(&mask[1], SIP_PAGE2_TEXTSUPPORT);
23500       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_TEXTSUPPORT);
23501       res = 1;
23502    } else if (!strcasecmp(v->name, "allowoverlap")) {
23503       ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
23504       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWOVERLAP);
23505    } else if (!strcasecmp(v->name, "allowsubscribe")) {
23506       ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
23507       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
23508    } else if (!strcasecmp(v->name, "ignoresdpversion")) {
23509       ast_set_flag(&mask[1], SIP_PAGE2_IGNORESDPVERSION);
23510       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_IGNORESDPVERSION);
23511    } else if (!strcasecmp(v->name, "faxdetect")) {
23512       ast_set_flag(&mask[1], SIP_PAGE2_FAX_DETECT);
23513       if (ast_true(v->value)) {
23514          ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
23515       } else if (ast_false(v->value)) {
23516          ast_clear_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
23517       } else {
23518          char *buf = ast_strdupa(v->value);
23519          char *word, *next = buf;
23520 
23521          while ((word = strsep(&next, ","))) {
23522             if (!strcasecmp(word, "cng")) {
23523                ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_CNG);
23524             } else if (!strcasecmp(word, "t38")) {
23525                ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_T38);
23526             } else {
23527                ast_log(LOG_WARNING, "Unknown faxdetect mode '%s' on line %d.\n", word, v->lineno);
23528             }
23529          }
23530       }
23531    } else if (!strcasecmp(v->name, "rfc2833compensate")) {
23532       ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
23533       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
23534    } else if (!strcasecmp(v->name, "buggymwi")) {
23535       ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
23536       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
23537    } else
23538       res = 0;
23539 
23540    return res;
23541 }
23542 
23543 /*! \brief Add SIP domain to list of domains we are responsible for */
23544 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
23545 {
23546    struct domain *d;
23547 
23548    if (ast_strlen_zero(domain)) {
23549       ast_log(LOG_WARNING, "Zero length domain.\n");
23550       return 1;
23551    }
23552 
23553    if (!(d = ast_calloc(1, sizeof(*d))))
23554       return 0;
23555 
23556    ast_copy_string(d->domain, domain, sizeof(d->domain));
23557 
23558    if (!ast_strlen_zero(context))
23559       ast_copy_string(d->context, context, sizeof(d->context));
23560 
23561    d->mode = mode;
23562 
23563    AST_LIST_LOCK(&domain_list);
23564    AST_LIST_INSERT_TAIL(&domain_list, d, list);
23565    AST_LIST_UNLOCK(&domain_list);
23566 
23567    if (sipdebug)  
23568       ast_debug(1, "Added local SIP domain '%s'\n", domain);
23569 
23570    return 1;
23571 }
23572 
23573 /*! \brief  check_sip_domain: Check if domain part of uri is local to our server */
23574 static int check_sip_domain(const char *domain, char *context, size_t len)
23575 {
23576    struct domain *d;
23577    int result = 0;
23578 
23579    AST_LIST_LOCK(&domain_list);
23580    AST_LIST_TRAVERSE(&domain_list, d, list) {
23581       if (strcasecmp(d->domain, domain))
23582          continue;
23583 
23584       if (len && !ast_strlen_zero(d->context))
23585          ast_copy_string(context, d->context, len);
23586       
23587       result = 1;
23588       break;
23589    }
23590    AST_LIST_UNLOCK(&domain_list);
23591 
23592    return result;
23593 }
23594 
23595 /*! \brief Clear our domain list (at reload) */
23596 static void clear_sip_domains(void)
23597 {
23598    struct domain *d;
23599 
23600    AST_LIST_LOCK(&domain_list);
23601    while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
23602       ast_free(d);
23603    AST_LIST_UNLOCK(&domain_list);
23604 }
23605 
23606 
23607 /*! \brief Add realm authentication in list */
23608 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno)
23609 {
23610    char authcopy[256];
23611    char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
23612    struct sip_auth *a, *b, *auth;
23613 
23614    if (ast_strlen_zero(configuration))
23615       return authlist;
23616 
23617    ast_debug(1, "Auth config ::  %s\n", configuration);
23618 
23619    ast_copy_string(authcopy, configuration, sizeof(authcopy));
23620    username = authcopy;
23621 
23622    /* split user[:secret] and relm */
23623    realm = strrchr(username, '@');
23624    if (realm)
23625       *realm++ = '\0';
23626    if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
23627       ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
23628       return authlist;
23629    }
23630 
23631    /* parse username at ':' for secret, or '#" for md5secret */
23632    if ((secret = strchr(username, ':'))) {
23633       *secret++ = '\0';
23634    } else if ((md5secret = strchr(username, '#'))) {
23635       *md5secret++ = '\0';
23636    }
23637 
23638    if (!(auth = ast_calloc(1, sizeof(*auth))))
23639       return authlist;
23640 
23641    ast_copy_string(auth->realm, realm, sizeof(auth->realm));
23642    ast_copy_string(auth->username, username, sizeof(auth->username));
23643    if (secret)
23644       ast_copy_string(auth->secret, secret, sizeof(auth->secret));
23645    if (md5secret)
23646       ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
23647 
23648    /* find the end of the list */
23649    for (b = NULL, a = authlist; a ; b = a, a = a->next)
23650       ;
23651    if (b)
23652       b->next = auth;   /* Add structure add end of list */
23653    else
23654       authlist = auth;
23655 
23656    ast_verb(3, "Added authentication for realm %s\n", realm);
23657 
23658    return authlist;
23659 
23660 }
23661 
23662 /*! \brief Clear realm authentication list (at reload) */
23663 static int clear_realm_authentication(struct sip_auth *authlist)
23664 {
23665    struct sip_auth *a = authlist;
23666    struct sip_auth *b;
23667 
23668    while (a) {
23669       b = a;
23670       a = a->next;
23671       ast_free(b);
23672    }
23673 
23674    return 1;
23675 }
23676 
23677 /*! \brief Find authentication for a specific realm */
23678 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm)
23679 {
23680    struct sip_auth *a;
23681 
23682    for (a = authlist; a; a = a->next) {
23683       if (!strcasecmp(a->realm, realm))
23684          break;
23685    }
23686 
23687    return a;
23688 }
23689 
23690 /*! \brief
23691  * implement the setvar config line
23692  */
23693 static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
23694 {
23695    struct ast_variable *tmpvar = NULL;
23696    char *varname = ast_strdupa(buf), *varval = NULL;
23697    
23698    if ((varval = strchr(varname, '='))) {
23699       *varval++ = '\0';
23700       if ((tmpvar = ast_variable_new(varname, varval, ""))) {
23701          tmpvar->next = list;
23702          list = tmpvar;
23703       }
23704    }
23705    return list;
23706 }
23707 
23708 /*! \brief Set peer defaults before configuring specific configurations */
23709 static void set_peer_defaults(struct sip_peer *peer)
23710 {
23711    if (peer->expire == 0) {
23712       /* Don't reset expire or port time during reload 
23713          if we have an active registration 
23714       */
23715       peer->expire = -1;
23716       peer->pokeexpire = -1;
23717       peer->addr.sin_port = htons(STANDARD_SIP_PORT);
23718       set_socket_transport(&peer->socket, SIP_TRANSPORT_UDP);
23719    }
23720    peer->type = SIP_TYPE_PEER;
23721    ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
23722    ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
23723    ast_string_field_set(peer, context, sip_cfg.default_context);
23724    ast_string_field_set(peer, subscribecontext, sip_cfg.default_subscribecontext);
23725    ast_string_field_set(peer, language, default_language);
23726    ast_string_field_set(peer, mohinterpret, default_mohinterpret);
23727    ast_string_field_set(peer, mohsuggest, default_mohsuggest);
23728    peer->addr.sin_family = AF_INET;
23729    peer->defaddr.sin_family = AF_INET;
23730    peer->capability = global_capability;
23731    peer->maxcallbitrate = default_maxcallbitrate;
23732    peer->rtptimeout = global_rtptimeout;
23733    peer->rtpholdtimeout = global_rtpholdtimeout;
23734    peer->rtpkeepalive = global_rtpkeepalive;
23735    peer->allowtransfer = sip_cfg.allowtransfer;
23736    peer->autoframing = global_autoframing;
23737    peer->t38_maxdatagram = global_t38_maxdatagram;
23738    peer->qualifyfreq = global_qualifyfreq;
23739    if (global_callcounter)
23740       peer->call_limit=INT_MAX;
23741    ast_string_field_set(peer, vmexten, default_vmexten);
23742    ast_string_field_set(peer, secret, "");
23743    ast_string_field_set(peer, remotesecret, "");
23744    ast_string_field_set(peer, md5secret, "");
23745    ast_string_field_set(peer, cid_num, "");
23746    ast_string_field_set(peer, cid_name, "");
23747    ast_string_field_set(peer, fromdomain, "");
23748    ast_string_field_set(peer, fromuser, "");
23749    ast_string_field_set(peer, regexten, "");
23750    peer->callgroup = 0;
23751    peer->pickupgroup = 0;
23752    peer->maxms = default_qualify;
23753    peer->prefs = default_prefs;
23754    peer->stimer.st_mode_oper = global_st_mode;  /* Session-Timers */
23755    peer->stimer.st_ref = global_st_refresher;
23756    peer->stimer.st_min_se = global_min_se;
23757    peer->stimer.st_max_se = global_max_se;
23758    peer->timer_t1 = global_t1;
23759    peer->timer_b = global_timer_b;
23760    clear_peer_mailboxes(peer);
23761 }
23762 
23763 /*! \brief Create temporary peer (used in autocreatepeer mode) */
23764 static struct sip_peer *temp_peer(const char *name)
23765 {
23766    struct sip_peer *peer;
23767 
23768    if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
23769       return NULL;
23770 
23771    if (ast_string_field_init(peer, 512)) {
23772       ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
23773       return NULL;
23774    }
23775 
23776    ast_atomic_fetchadd_int(&apeerobjs, 1);
23777    set_peer_defaults(peer);
23778 
23779    ast_copy_string(peer->name, name, sizeof(peer->name));
23780 
23781    peer->selfdestruct = TRUE;
23782    peer->host_dynamic = TRUE;
23783    peer->prefs = default_prefs;
23784    reg_source_db(peer);
23785 
23786    return peer;
23787 }
23788 
23789 /*! \todo document this function */
23790 static void add_peer_mailboxes(struct sip_peer *peer, const char *value)
23791 {
23792    char *next, *mbox, *context;
23793 
23794    next = ast_strdupa(value);
23795 
23796    while ((mbox = context = strsep(&next, ","))) {
23797       struct sip_mailbox *mailbox;
23798       int duplicate = 0;
23799 
23800       strsep(&context, "@");
23801 
23802       if (ast_strlen_zero(mbox)) {
23803          continue;
23804       }
23805 
23806       /* Check whether the mailbox is already in the list */
23807       AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
23808          if (!strcmp(mailbox->mailbox, mbox) && !strcmp(S_OR(mailbox->context, ""), S_OR(context, ""))) {
23809             duplicate = 1;
23810             mailbox->delme = 1;
23811             break;
23812          }
23813       }
23814       if (duplicate) {
23815          continue;
23816       }
23817 
23818       if (!(mailbox = ast_calloc(1, sizeof(*mailbox)))) {
23819          continue;
23820       }
23821 
23822       mailbox->mailbox = ast_strdup(mbox);
23823       mailbox->context = ast_strdup(context);
23824 
23825       AST_LIST_INSERT_TAIL(&peer->mailboxes, mailbox, entry);
23826    }
23827 }
23828 
23829 /*! \brief Build peer from configuration (file or realtime static/dynamic) */
23830 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only)
23831 {
23832    struct sip_peer *peer = NULL;
23833    struct ast_ha *oldha = NULL;
23834    int found = 0;
23835    int firstpass = 1;
23836    uint16_t port = 0;
23837    int format = 0;      /* Ama flags */
23838    time_t regseconds = 0;
23839    struct ast_flags peerflags[2] = {{(0)}};
23840    struct ast_flags mask[2] = {{(0)}};
23841    char callback[256] = "";
23842    struct sip_peer tmp_peer;
23843    const char *srvlookup = NULL;
23844    static int deprecation_warning = 1;
23845    int alt_fullcontact = alt ? 1 : 0;
23846    struct ast_str *fullcontact = ast_str_alloca(512);
23847 
23848    if (!realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
23849       /* Note we do NOT use find_peer here, to avoid realtime recursion */
23850       /* We also use a case-sensitive comparison (unlike find_peer) so
23851          that case changes made to the peer name will be properly handled
23852          during reload
23853       */
23854       ast_copy_string(tmp_peer.name, name, sizeof(tmp_peer.name));
23855       peer = ao2_t_find(peers, &tmp_peer, OBJ_POINTER | OBJ_UNLINK, "find and unlink peer from peers table");
23856    }
23857 
23858    if (peer) {
23859       /* Already in the list, remove it and it will be added back (or FREE'd)  */
23860       found++;
23861       if (!(peer->the_mark))
23862          firstpass = 0;
23863    } else {
23864       if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
23865          return NULL;
23866 
23867       if (ast_string_field_init(peer, 512)) {
23868          ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
23869          return NULL;
23870       }
23871 
23872       if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
23873          ast_atomic_fetchadd_int(&rpeerobjs, 1);
23874          ast_debug(3, "-REALTIME- peer built. Name: %s. Peer objects: %d\n", name, rpeerobjs);
23875       } else
23876          ast_atomic_fetchadd_int(&speerobjs, 1);
23877    }
23878 
23879    /* Note that our peer HAS had its reference count increased */
23880    if (firstpass) {
23881       peer->lastmsgssent = -1;
23882       oldha = peer->ha;
23883       peer->ha = NULL;
23884       set_peer_defaults(peer);   /* Set peer defaults */
23885       peer->type = 0;
23886    }
23887    if (!found && name)
23888       ast_copy_string(peer->name, name, sizeof(peer->name));
23889 
23890    /* If we have channel variables, remove them (reload) */
23891    if (peer->chanvars) {
23892       ast_variables_destroy(peer->chanvars);
23893       peer->chanvars = NULL;
23894       /* XXX should unregister ? */
23895    }
23896 
23897    if (found)
23898       peer->portinuri = 0;
23899 
23900    /* If we have realm authentication information, remove them (reload) */
23901    clear_realm_authentication(peer->auth);
23902    peer->auth = NULL;
23903    peer->default_outbound_transport = 0;
23904    peer->transports = 0;
23905 
23906    if (!devstate_only) {
23907       struct sip_mailbox *mailbox;
23908       AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
23909          mailbox->delme = 1;
23910       }
23911    }
23912 
23913    for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
23914       if (!devstate_only) {
23915          if (handle_common_options(&peerflags[0], &mask[0], v)) {
23916             continue;
23917          }
23918          if (handle_t38_options(&peerflags[0], &mask[0], v, &peer->t38_maxdatagram)) {
23919             continue;
23920          }
23921          if (!strcasecmp(v->name, "transport") && !ast_strlen_zero(v->value)) {
23922             char *val = ast_strdupa(v->value);
23923             char *trans;
23924 
23925             while ((trans = strsep(&val, ","))) {
23926                trans = ast_skip_blanks(trans);
23927 
23928                if (!strncasecmp(trans, "udp", 3)) {
23929                   peer->transports |= SIP_TRANSPORT_UDP;
23930                } else if (!strncasecmp(trans, "tcp", 3)) {
23931                   peer->transports |= SIP_TRANSPORT_TCP;
23932                } else if (!strncasecmp(trans, "tls", 3)) {
23933                   peer->transports |= SIP_TRANSPORT_TLS;
23934                } else {
23935                   ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
23936                }
23937 
23938                if (!peer->default_outbound_transport) { /*!< The first transport listed should be default outbound */
23939                   peer->default_outbound_transport = peer->transports;
23940                }
23941             }
23942          } else if (realtime && !strcasecmp(v->name, "regseconds")) {
23943             ast_get_time_t(v->value, &regseconds, 0, NULL);
23944          } else if (realtime && !strcasecmp(v->name, "name")) {
23945             ast_copy_string(peer->name, v->value, sizeof(peer->name));
23946          } else if (realtime && !strcasecmp(v->name, "useragent")) {
23947             ast_string_field_set(peer, useragent, v->value);
23948          } else if (!strcasecmp(v->name, "type")) {
23949             if (!strcasecmp(v->value, "peer")) {
23950                peer->type |= SIP_TYPE_PEER;
23951             } else if (!strcasecmp(v->value, "user")) {
23952                peer->type |= SIP_TYPE_USER;
23953             } else if (!strcasecmp(v->value, "friend")) {
23954                peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
23955             }
23956          } else if (!strcasecmp(v->name, "remotesecret")) {
23957             ast_string_field_set(peer, remotesecret, v->value);
23958          } else if (!strcasecmp(v->name, "secret")) {
23959             ast_string_field_set(peer, secret, v->value);
23960          } else if (!strcasecmp(v->name, "md5secret")) {
23961             ast_string_field_set(peer, md5secret, v->value);
23962          } else if (!strcasecmp(v->name, "auth")) {
23963             peer->auth = add_realm_authentication(peer->auth, v->value, v->lineno);
23964          } else if (!strcasecmp(v->name, "callerid")) {
23965             char cid_name[80] = { '\0' }, cid_num[80] = { '\0' };
23966 
23967             ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
23968             ast_string_field_set(peer, cid_name, cid_name);
23969             ast_string_field_set(peer, cid_num, cid_num);
23970          } else if (!strcasecmp(v->name, "fullname")) {
23971             ast_string_field_set(peer, cid_name, v->value);
23972          } else if (!strcasecmp(v->name, "trunkname")) {
23973             /* This is actually for a trunk, so we don't want to override callerid */
23974             ast_string_field_set(peer, cid_name, "");
23975          } else if (!strcasecmp(v->name, "cid_number")) {
23976             ast_string_field_set(peer, cid_num, v->value);
23977          } else if (!strcasecmp(v->name, "context")) {
23978             ast_string_field_set(peer, context, v->value);
23979             ast_set_flag(&peer->flags[1], SIP_PAGE2_HAVEPEERCONTEXT);
23980          } else if (!strcasecmp(v->name, "subscribecontext")) {
23981             ast_string_field_set(peer, subscribecontext, v->value);
23982          } else if (!strcasecmp(v->name, "fromdomain")) {
23983             ast_string_field_set(peer, fromdomain, v->value);
23984          } else if (!strcasecmp(v->name, "usereqphone")) {
23985             ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
23986          } else if (!strcasecmp(v->name, "fromuser")) {
23987             ast_string_field_set(peer, fromuser, v->value);
23988          } else if (!strcasecmp(v->name, "outboundproxy")) {
23989             char *port, *next, *force, *proxyname;
23990             int forceopt = FALSE;
23991             /* Set peer channel variable */
23992             next = proxyname = ast_strdupa(v->value);
23993             if ((port = strchr(proxyname, ':'))) {
23994                *port++ = '\0';
23995                next = port;
23996             }
23997             if ((force = strchr(next, ','))) {
23998                *force++ = '\0';
23999                forceopt = strcmp(force, "force");
24000             }
24001             /* Allocate proxy object */
24002             peer->outboundproxy = proxy_allocate(proxyname, port, forceopt);
24003          } else if (!strcasecmp(v->name, "host")) {
24004             if (!strcasecmp(v->value, "dynamic")) {
24005                /* They'll register with us */
24006                if (!found || !peer->host_dynamic) {
24007                   /* Initialize stuff if this is a new peer, or if it used to
24008                    * not be dynamic before the reload. */
24009                   memset(&peer->addr.sin_addr, 0, 4);
24010                   peer->addr.sin_port = 0;
24011                }
24012                peer->host_dynamic = TRUE;
24013             } else {
24014                /* Non-dynamic.  Make sure we become that way if we're not */
24015                AST_SCHED_DEL_UNREF(sched, peer->expire,
24016                      unref_peer(peer, "removing register expire ref"));
24017                /* the port will either be set to a default value or a config specified value once all option parsing is complete */
24018                peer->addr.sin_port = 0;
24019                peer->host_dynamic = FALSE;
24020                srvlookup = v->value;
24021                if (global_dynamic_exclude_static) {
24022                   int err = 0;
24023                   global_contact_ha = ast_append_ha("deny", (char *)ast_inet_ntoa(peer->addr.sin_addr), global_contact_ha, &err);
24024                   if (err) {
24025                      ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
24026                   }
24027                }
24028             }
24029          } else if (!strcasecmp(v->name, "defaultip")) {
24030             if (!ast_strlen_zero(v->value) && ast_get_ip(&peer->defaddr, v->value)) {
24031                unref_peer(peer, "unref_peer: from build_peer defaultip");
24032                return NULL;
24033             }
24034          } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
24035             int ha_error = 0;
24036             if (!ast_strlen_zero(v->value)) {
24037                peer->ha = ast_append_ha(v->name, v->value, peer->ha, &ha_error);
24038             }
24039             if (ha_error) {
24040                ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
24041             }
24042          } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
24043             int ha_error = 0;
24044             if (!ast_strlen_zero(v->value)) {
24045                peer->contactha = ast_append_ha(v->name + 7, v->value, peer->contactha, &ha_error);
24046             }
24047             if (ha_error) {
24048                ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
24049             }
24050          } else if (!strcasecmp(v->name, "port")) {
24051             peer->portinuri = 1;
24052             if (!(port = port_str2int(v->value, 0))) {
24053                if (realtime) {
24054                   /* If stored as integer, could be 0 for some DBs (notably MySQL) */
24055                   peer->portinuri = 0;
24056                } else {
24057                   ast_log(LOG_WARNING, "Invalid peer port configuration at line %d : %s\n", v->lineno, v->value);
24058                }
24059             }
24060          } else if (!strcasecmp(v->name, "callingpres")) {
24061             peer->callingpres = ast_parse_caller_presentation(v->value);
24062             if (peer->callingpres == -1) {
24063                peer->callingpres = atoi(v->value);
24064             }
24065          } else if (!strcasecmp(v->name, "username") || !strcmp(v->name, "defaultuser")) {   /* "username" is deprecated */
24066             ast_string_field_set(peer, username, v->value);
24067             if (!strcasecmp(v->name, "username")) {
24068                if (deprecation_warning) {
24069                   ast_log(LOG_NOTICE, "The 'username' field for sip peers has been deprecated in favor of the term 'defaultuser'\n");
24070                   deprecation_warning = 0;
24071                }
24072                peer->deprecated_username = 1;
24073             }
24074          } else if (!strcasecmp(v->name, "language")) {
24075             ast_string_field_set(peer, language, v->value);
24076          } else if (!strcasecmp(v->name, "regexten")) {
24077             ast_string_field_set(peer, regexten, v->value);
24078          } else if (!strcasecmp(v->name, "callbackextension")) {
24079             ast_copy_string(callback, v->value, sizeof(callback));
24080          } else if (!strcasecmp(v->name, "amaflags")) {
24081             format = ast_cdr_amaflags2int(v->value);
24082             if (format < 0) {
24083                ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
24084             } else {
24085                peer->amaflags = format;
24086             }
24087          } else if (!strcasecmp(v->name, "accountcode")) {
24088             ast_string_field_set(peer, accountcode, v->value);
24089          } else if (!strcasecmp(v->name, "mohinterpret")) {
24090             ast_string_field_set(peer, mohinterpret, v->value);
24091          } else if (!strcasecmp(v->name, "mohsuggest")) {
24092             ast_string_field_set(peer, mohsuggest, v->value);
24093          } else if (!strcasecmp(v->name, "parkinglot")) {
24094             ast_string_field_set(peer, parkinglot, v->value);
24095          } else if (!strcasecmp(v->name, "mailbox")) {
24096             add_peer_mailboxes(peer, v->value);
24097          } else if (!strcasecmp(v->name, "hasvoicemail")) {
24098             /* People expect that if 'hasvoicemail' is set, that the mailbox will
24099              * be also set, even if not explicitly specified. */
24100             if (ast_true(v->value) && AST_LIST_EMPTY(&peer->mailboxes)) {
24101                add_peer_mailboxes(peer, name);
24102             }
24103          } else if (!strcasecmp(v->name, "subscribemwi")) {
24104             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
24105          } else if (!strcasecmp(v->name, "vmexten")) {
24106             ast_string_field_set(peer, vmexten, v->value);
24107          } else if (!strcasecmp(v->name, "callgroup")) {
24108             peer->callgroup = ast_get_group(v->value);
24109          } else if (!strcasecmp(v->name, "allowtransfer")) {
24110             peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
24111          } else if (!strcasecmp(v->name, "pickupgroup")) {
24112             peer->pickupgroup = ast_get_group(v->value);
24113          } else if (!strcasecmp(v->name, "allow")) {
24114             int error =  ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, TRUE);
24115             if (error) {
24116                ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
24117             }
24118          } else if (!strcasecmp(v->name, "disallow")) {
24119             int error =  ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, FALSE);
24120             if (error) {
24121                ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
24122             }
24123          } else if (!strcasecmp(v->name, "registertrying")) {
24124             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_REGISTERTRYING);
24125          } else if (!strcasecmp(v->name, "autoframing")) {
24126             peer->autoframing = ast_true(v->value);
24127          } else if (!strcasecmp(v->name, "rtptimeout")) {
24128             if ((sscanf(v->value, "%30d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
24129                ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
24130                peer->rtptimeout = global_rtptimeout;
24131             }
24132          } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
24133             if ((sscanf(v->value, "%30d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
24134                ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
24135                peer->rtpholdtimeout = global_rtpholdtimeout;
24136             }
24137          } else if (!strcasecmp(v->name, "rtpkeepalive")) {
24138             if ((sscanf(v->value, "%30d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
24139                ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d.  Using default.\n", v->value, v->lineno);
24140                peer->rtpkeepalive = global_rtpkeepalive;
24141             }
24142          } else if (!strcasecmp(v->name, "timert1")) {
24143             if ((sscanf(v->value, "%30d", &peer->timer_t1) != 1) || (peer->timer_t1 < 0)) {
24144                ast_log(LOG_WARNING, "'%s' is not a valid T1 time at line %d.  Using default.\n", v->value, v->lineno);
24145                peer->timer_t1 = global_t1;
24146             }
24147             /* Note that Timer B is dependent upon T1 and MUST NOT be lower
24148              * than T1 * 64, according to RFC 3261, Section 17.1.1.2 */
24149             if (peer->timer_b < peer->timer_t1 * 64) {
24150                peer->timer_b = peer->timer_t1 * 64;
24151             }
24152          } else if (!strcasecmp(v->name, "timerb")) {
24153             if ((sscanf(v->value, "%30d", &peer->timer_b) != 1) || (peer->timer_b < 0)) {
24154                ast_log(LOG_WARNING, "'%s' is not a valid Timer B time at line %d.  Using default.\n", v->value, v->lineno);
24155                peer->timer_b = global_timer_b;
24156             }
24157             if (peer->timer_b < peer->timer_t1 * 64) {
24158                static int warning = 0;
24159                if (warning++ % 20 == 0) {
24160                   ast_log(LOG_WARNING, "Timer B has been set lower than recommended. (RFC 3261, 17.1.1.2)\n");
24161                }
24162             }
24163          } else if (!strcasecmp(v->name, "setvar")) {
24164             peer->chanvars = add_var(v->value, peer->chanvars);
24165          } else if (!strcasecmp(v->name, "qualifyfreq")) {
24166             int i;
24167             if (sscanf(v->value, "%30d", &i) == 1) {
24168                peer->qualifyfreq = i * 1000;
24169             } else {
24170                ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
24171                peer->qualifyfreq = global_qualifyfreq;
24172             }
24173          } else if (!strcasecmp(v->name, "maxcallbitrate")) {
24174             peer->maxcallbitrate = atoi(v->value);
24175             if (peer->maxcallbitrate < 0) {
24176                peer->maxcallbitrate = default_maxcallbitrate;
24177             }
24178          } else if (!strcasecmp(v->name, "session-timers")) {
24179             int i = (int) str2stmode(v->value);
24180             if (i < 0) {
24181                ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
24182                peer->stimer.st_mode_oper = global_st_mode;
24183             } else {
24184                peer->stimer.st_mode_oper = i;
24185             }
24186          } else if (!strcasecmp(v->name, "session-expires")) {
24187             if (sscanf(v->value, "%30d", &peer->stimer.st_max_se) != 1) {
24188                ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
24189                peer->stimer.st_max_se = global_max_se;
24190             }
24191          } else if (!strcasecmp(v->name, "session-minse")) {
24192             if (sscanf(v->value, "%30d", &peer->stimer.st_min_se) != 1) {
24193                ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
24194                peer->stimer.st_min_se = global_min_se;
24195             }
24196             if (peer->stimer.st_min_se < 90) {
24197                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);
24198                peer->stimer.st_min_se = global_min_se;
24199             }
24200          } else if (!strcasecmp(v->name, "session-refresher")) {
24201             int i = (int) str2strefresher(v->value);
24202             if (i < 0) {
24203                ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
24204                peer->stimer.st_ref = global_st_refresher;
24205             } else {
24206                peer->stimer.st_ref = i;
24207             }
24208          }
24209       }
24210 
24211       /* These apply to devstate lookups */
24212       if (realtime && !strcasecmp(v->name, "lastms")) {
24213          sscanf(v->value, "%30d", &peer->lastms);
24214       } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
24215          inet_aton(v->value, &(peer->addr.sin_addr));
24216       } else if (realtime && !strcasecmp(v->name, "fullcontact")) {
24217          if (alt_fullcontact && !alt) {
24218             /* Reset, because the alternate also has a fullcontact and we
24219              * do NOT want the field value to be doubled. It might be
24220              * tempting to skip this, but the first table might not have
24221              * fullcontact and since we're here, we know that the alternate
24222              * absolutely does. */
24223             alt_fullcontact = 0;
24224             ast_str_reset(fullcontact);
24225          }
24226          /* Reconstruct field, because realtime separates our value at the ';' */
24227          if (fullcontact->used > 0) {
24228             ast_str_append(&fullcontact, 0, ";%s", v->value);
24229          } else {
24230             ast_str_set(&fullcontact, 0, "%s", v->value);
24231          }
24232       } else if (!strcasecmp(v->name, "qualify")) {
24233          if (!strcasecmp(v->value, "no")) {
24234             peer->maxms = 0;
24235          } else if (!strcasecmp(v->value, "yes")) {
24236             peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
24237          } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
24238             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);
24239             peer->maxms = 0;
24240          }
24241          if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->maxms > 0) {
24242             /* This would otherwise cause a network storm, where the
24243              * qualify response refreshes the peer from the database,
24244              * which in turn causes another qualify to be sent, ad
24245              * infinitum. */
24246             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);
24247             peer->maxms = 0;
24248          }
24249       } else if (!strcasecmp(v->name, "callcounter")) {
24250          peer->call_limit = ast_true(v->value) ? INT_MAX : 0;
24251       } else if (!strcasecmp(v->name, "call-limit")) {
24252          peer->call_limit = atoi(v->value);
24253          if (peer->call_limit < 0) {
24254             peer->call_limit = 0;
24255          }
24256       } else if (!strcasecmp(v->name, "busylevel")) {
24257          peer->busy_level = atoi(v->value);
24258          if (peer->busy_level < 0) {
24259             peer->busy_level = 0;
24260          }
24261       }
24262    }
24263 
24264    if (!devstate_only) {
24265       struct sip_mailbox *mailbox;
24266       AST_LIST_TRAVERSE_SAFE_BEGIN(&peer->mailboxes, mailbox, entry) {
24267          if (mailbox->delme) {
24268             AST_LIST_REMOVE_CURRENT(entry);
24269             destroy_mailbox(mailbox);
24270          }
24271       }
24272       AST_LIST_TRAVERSE_SAFE_END;
24273    }
24274 
24275    if (!peer->default_outbound_transport) {
24276       /* Set default set of transports */
24277       peer->transports = default_transports;
24278       /* Set default primary transport */
24279       peer->default_outbound_transport = default_primary_transport;
24280    }
24281 
24282    /* The default transport type set during build_peer should only replace the socket.type when...
24283     * 1. Registration is not present and the socket.type and default transport types are different.
24284     * 2. The socket.type is not an acceptable transport type after rebuilding peer.
24285     * 3. The socket.type is not set yet. */
24286    if (((peer->socket.type != peer->default_outbound_transport) && (peer->expire == -1)) ||
24287       !(peer->socket.type & peer->transports) || !(peer->socket.type)) {
24288 
24289       set_socket_transport(&peer->socket, peer->default_outbound_transport);
24290    }
24291 
24292    if (port && !realtime && peer->host_dynamic) {
24293       peer->defaddr.sin_port = htons(port);
24294    } else if (port) {
24295       peer->addr.sin_port = htons(port);
24296    }
24297 
24298    if (ast_str_strlen(fullcontact)) {
24299       ast_string_field_set(peer, fullcontact, ast_str_buffer(fullcontact));
24300       peer->rt_fromcontact = TRUE;
24301       /* We have a hostname in the fullcontact, but if we don't have an
24302        * address listed on the entry (or if it's 'dynamic'), then we need to
24303        * parse the entry to obtain the IP address, so a dynamic host can be
24304        * contacted immediately after reload (as opposed to waiting for it to
24305        * register once again). But if we have an address for this peer and NAT was
24306        * specified, use that address instead. */
24307       /* XXX May need to revisit the final argument; does the realtime DB store whether
24308        * the original contact was over TLS or not? XXX */
24309       if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) || !peer->addr.sin_addr.s_addr) {
24310          __set_address_from_contact(fullcontact->str, &peer->addr, 0);
24311       }
24312    }
24313 
24314    if (srvlookup && peer->dnsmgr == NULL) {
24315       char transport[MAXHOSTNAMELEN];
24316       char _srvlookup[MAXHOSTNAMELEN];
24317       char *params;
24318 
24319       ast_copy_string(_srvlookup, srvlookup, sizeof(_srvlookup));
24320       if ((params = strchr(_srvlookup, ';'))) {
24321          *params++ = '\0';
24322       }
24323 
24324       snprintf(transport, sizeof(transport), "_sip._%s", get_transport(peer->socket.type));
24325 
24326       if (ast_dnsmgr_lookup(_srvlookup, &peer->addr, &peer->dnsmgr, sip_cfg.srvlookup && !peer->portinuri ? transport : NULL)) {
24327          ast_log(LOG_ERROR, "srvlookup failed for host: %s, on peer %s, removing peer\n", _srvlookup, peer->name);
24328          unref_peer(peer, "getting rid of a peer pointer");
24329          return NULL;
24330       }
24331 
24332       ast_string_field_set(peer, tohost, srvlookup);
24333    }
24334 
24335    if (!peer->addr.sin_port) {
24336       peer->addr.sin_port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
24337    }
24338    if (!peer->defaddr.sin_port) {
24339       peer->defaddr.sin_port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
24340    }
24341    if (!peer->socket.port) {
24342       peer->socket.port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
24343    }
24344 
24345    if (!sip_cfg.ignore_regexpire && peer->host_dynamic && realtime) {
24346       time_t nowtime = time(NULL);
24347 
24348       if ((nowtime - regseconds) > 0) {
24349          destroy_association(peer);
24350          memset(&peer->addr, 0, sizeof(peer->addr));
24351          peer->lastms = -1;
24352          ast_debug(1, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
24353       }
24354    }
24355 
24356    /* Startup regular pokes */
24357    if (!devstate_only && realtime && peer->lastms > 0) {
24358       ref_peer(peer, "schedule qualify");
24359       sip_poke_peer(peer, 0);
24360    }
24361 
24362    ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
24363    ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
24364    if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
24365       sip_cfg.allowsubscribe = TRUE;   /* No global ban any more */
24366    }
24367    if (peer->host_dynamic && !peer->is_realtime) {
24368       reg_source_db(peer);
24369    }
24370 
24371    /* If they didn't request that MWI is sent *only* on subscribe, go ahead and
24372     * subscribe to it now. */
24373    if (!devstate_only && !ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
24374       !AST_LIST_EMPTY(&peer->mailboxes)) {
24375       add_peer_mwi_subs(peer);
24376       /* Send MWI from the event cache only.  This is so we can send initial
24377        * MWI if app_voicemail got loaded before chan_sip.  If it is the other
24378        * way, then we will get events when app_voicemail gets loaded. */
24379       sip_send_mwi_to_peer(peer, NULL, 1);
24380    }
24381 
24382    peer->the_mark = 0;
24383 
24384    ast_free_ha(oldha);
24385    if (!ast_strlen_zero(callback)) { /* build string from peer info */
24386       char *reg_string;
24387       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) {
24388          ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
24389       } else if (reg_string) {
24390          sip_register(reg_string, 0); /* XXX TODO: count in registry_count */
24391          ast_free(reg_string);
24392       }
24393    }
24394    return peer;
24395 }
24396 
24397 static int peer_markall_func(void *device, void *arg, int flags)
24398 {
24399    struct sip_peer *peer = device;
24400    peer->the_mark = 1;
24401    return 0;
24402 }
24403 
24404 /*! \brief Re-read SIP.conf config file
24405 \note This function reloads all config data, except for
24406    active peers (with registrations). They will only
24407    change configuration data at restart, not at reload.
24408    SIP debug and recordhistory state will not change
24409  */
24410 static int reload_config(enum channelreloadreason reason)
24411 {
24412    struct ast_config *cfg, *ucfg;
24413    struct ast_variable *v;
24414    struct sip_peer *peer;
24415    char *cat, *stringp, *context, *oldregcontext;
24416    char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
24417    struct ast_flags dummy[2];
24418    struct ast_flags config_flags = { reason == CHANNEL_MODULE_LOAD ? 0 : ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? 0 : CONFIG_FLAG_FILEUNCHANGED };
24419    int auto_sip_domains = FALSE;
24420    struct sockaddr_in old_bindaddr = bindaddr;
24421    int registry_count = 0, peer_count = 0;
24422    time_t run_start, run_end;
24423    
24424    run_start = time(0);
24425    ast_unload_realtime("sipregs");     
24426    ast_unload_realtime("sippeers");
24427    cfg = ast_config_load(config, config_flags);
24428 
24429    /* We *must* have a config file otherwise stop immediately */
24430    if (!cfg) {
24431       ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
24432       return -1;
24433    } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
24434       ucfg = ast_config_load("users.conf", config_flags);
24435       if (ucfg == CONFIG_STATUS_FILEUNCHANGED) {
24436          return 1;
24437       } else if (ucfg == CONFIG_STATUS_FILEINVALID) {
24438          ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
24439          return 1;
24440       }
24441       /* Must reread both files, because one changed */
24442       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
24443       if ((cfg = ast_config_load(config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
24444          ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
24445          ast_config_destroy(ucfg);
24446          return 1;
24447       }
24448    } else if (cfg == CONFIG_STATUS_FILEINVALID) {
24449       ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
24450       return 1;
24451    } else {
24452       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
24453       if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
24454          ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
24455          ast_config_destroy(cfg);
24456          return 1;
24457       }
24458    }
24459 
24460    /* Initialize tcp sockets */
24461    memset(&sip_tcp_desc.local_address, 0, sizeof(sip_tcp_desc.local_address));
24462    memset(&sip_tls_desc.local_address, 0, sizeof(sip_tls_desc.local_address));
24463 
24464    ast_free_ha(global_contact_ha);
24465    global_contact_ha = NULL;
24466 
24467    default_tls_cfg.enabled = FALSE;    /* Default: Disable TLS */
24468 
24469    sip_tcp_desc.local_address.sin_port = htons(STANDARD_SIP_PORT);
24470    sip_tls_desc.local_address.sin_port = htons(STANDARD_TLS_PORT);
24471 
24472    if (reason != CHANNEL_MODULE_LOAD) {
24473       ast_debug(4, "--------------- SIP reload started\n");
24474 
24475       clear_realm_authentication(authl);
24476       clear_sip_domains();
24477       authl = NULL;
24478 
24479       /* First, destroy all outstanding registry calls */
24480       /* This is needed, since otherwise active registry entries will not be destroyed */
24481       ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {  /* regl is locked */
24482 
24483             ASTOBJ_RDLOCK(iterator); /* now regl is locked, and the object is also locked */
24484             if (iterator->call) {
24485                ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
24486                /* This will also remove references to the registry */
24487                dialog_unlink_all(iterator->call, TRUE, TRUE);
24488                iterator->call = dialog_unref(iterator->call, "remove iterator->call from registry traversal");
24489             }
24490             if (iterator->expire > -1) {
24491                AST_SCHED_DEL_UNREF(sched, iterator->expire, registry_unref(iterator, "reg ptr unref from reload config"));
24492             }
24493             if (iterator->timeout > -1) {
24494                AST_SCHED_DEL_UNREF(sched, iterator->timeout, registry_unref(iterator, "reg ptr unref from reload config"));
24495             }
24496             ASTOBJ_UNLOCK(iterator);
24497             
24498       } while(0));
24499 
24500       /* Then, actually destroy users and registry */
24501       ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
24502       ast_debug(4, "--------------- Done destroying registry list\n");
24503       ao2_t_callback(peers, OBJ_NODATA, peer_markall_func, NULL, "callback to mark all peers");
24504    }
24505    
24506    /* Reset certificate handling for TLS sessions */
24507    if (reason != CHANNEL_MODULE_LOAD) {
24508       ast_free(default_tls_cfg.certfile);
24509       ast_free(default_tls_cfg.cipher);
24510       ast_free(default_tls_cfg.cafile);
24511       ast_free(default_tls_cfg.capath);
24512    }
24513    default_tls_cfg.certfile = ast_strdup(AST_CERTFILE); /*XXX Not sure if this is useful */
24514    default_tls_cfg.cipher = ast_strdup("");
24515    default_tls_cfg.cafile = ast_strdup("");
24516    default_tls_cfg.capath = ast_strdup("");
24517 
24518    
24519    /* Initialize copy of current global_regcontext for later use in removing stale contexts */
24520    ast_copy_string(oldcontexts, global_regcontext, sizeof(oldcontexts));
24521    oldregcontext = oldcontexts;
24522 
24523    /* Clear all flags before setting default values */
24524    /* Preserve debugging settings for console */
24525    sipdebug &= sip_debug_console;
24526    ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
24527    ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
24528 
24529    /* Reset IP addresses  */
24530    memset(&bindaddr, 0, sizeof(bindaddr));
24531    memset(&stunaddr, 0, sizeof(stunaddr));
24532    memset(&internip, 0, sizeof(internip));
24533 
24534    /* Free memory for local network address mask */
24535    ast_free_ha(localaddr);
24536    memset(&localaddr, 0, sizeof(localaddr));
24537    memset(&externip, 0, sizeof(externip));
24538    memset(&default_prefs, 0 , sizeof(default_prefs));
24539    memset(&sip_cfg.outboundproxy, 0, sizeof(struct sip_proxy));
24540    sip_cfg.outboundproxy.ip.sin_port = htons(STANDARD_SIP_PORT);
24541    sip_cfg.outboundproxy.ip.sin_family = AF_INET;  /*!< Type of address: IPv4 */
24542    sip_cfg.outboundproxy.force = FALSE;      /*!< Don't force proxy usage, use route: headers */
24543    default_transports = 0;          /*!< Reset default transport to zero here, default value later on */
24544    default_primary_transport = 0;         /*!< Reset default primary transport to zero here, default value later on */
24545    ourport_tcp = STANDARD_SIP_PORT;
24546    ourport_tls = STANDARD_TLS_PORT;
24547    bindaddr.sin_port = htons(STANDARD_SIP_PORT);
24548    sip_cfg.srvlookup = DEFAULT_SRVLOOKUP;
24549    global_tos_sip = DEFAULT_TOS_SIP;
24550    global_tos_audio = DEFAULT_TOS_AUDIO;
24551    global_tos_video = DEFAULT_TOS_VIDEO;
24552    global_tos_text = DEFAULT_TOS_TEXT;
24553    global_cos_sip = DEFAULT_COS_SIP;
24554    global_cos_audio = DEFAULT_COS_AUDIO;
24555    global_cos_video = DEFAULT_COS_VIDEO;
24556    global_cos_text = DEFAULT_COS_TEXT;
24557 
24558    externhost[0] = '\0';         /* External host name (for behind NAT DynDNS support) */
24559    externexpire = 0;       /* Expiration for DNS re-issuing */
24560    externrefresh = 10;
24561 
24562    /* Reset channel settings to default before re-configuring */
24563    sip_cfg.allow_external_domains = DEFAULT_ALLOW_EXT_DOM;           /* Allow external invites */
24564    global_regcontext[0] = '\0';
24565    sip_cfg.regextenonqualify = DEFAULT_REGEXTENONQUALIFY;
24566    sip_cfg.notifyringing = DEFAULT_NOTIFYRINGING;
24567    sip_cfg.notifycid = DEFAULT_NOTIFYCID;
24568    sip_cfg.notifyhold = FALSE;      /*!< Keep track of hold status for a peer */
24569    sip_cfg.directrtpsetup = FALSE;     /* Experimental feature, disabled by default */
24570    sip_cfg.alwaysauthreject = DEFAULT_ALWAYSAUTHREJECT;
24571    sip_cfg.allowsubscribe = FALSE;
24572    snprintf(global_useragent, sizeof(global_useragent), "%s %s", DEFAULT_USERAGENT, ast_get_version());
24573    snprintf(global_sdpsession, sizeof(global_sdpsession), "%s %s", DEFAULT_SDPSESSION, ast_get_version());
24574    snprintf(global_sdpowner, sizeof(global_sdpowner), "%s", DEFAULT_SDPOWNER);
24575    global_prematuremediafilter = TRUE;
24576    ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
24577    ast_copy_string(sip_cfg.realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM), sizeof(sip_cfg.realm));
24578    ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
24579    sip_cfg.compactheaders = DEFAULT_COMPACTHEADERS;
24580    global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
24581    global_regattempts_max = 0;
24582    sip_cfg.pedanticsipchecking = DEFAULT_PEDANTIC;
24583    sip_cfg.autocreatepeer = DEFAULT_AUTOCREATEPEER;
24584    global_autoframing = 0;
24585    sip_cfg.allowguest = DEFAULT_ALLOWGUEST;
24586    global_callcounter = DEFAULT_CALLCOUNTER;
24587    global_match_auth_username = FALSE;    /*!< Match auth username if available instead of From: Default off. */
24588    global_rtptimeout = 0;
24589    global_rtpholdtimeout = 0;
24590    global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
24591    sip_cfg.allowtransfer = TRANSFER_OPENFORALL; /* Merrily accept all transfers by default */
24592    sip_cfg.rtautoclear = 120;
24593    ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE);   /* Default for all devices: TRUE */
24594    ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP);     /* Default for all devices: TRUE */
24595    sip_cfg.peer_rtupdate = TRUE;
24596    global_dynamic_exclude_static = 0;  /* Exclude static peers */
24597 
24598    /* Session-Timers */
24599    global_st_mode = SESSION_TIMER_MODE_ACCEPT;    
24600    global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
24601    global_min_se  = DEFAULT_MIN_SE;
24602    global_max_se  = DEFAULT_MAX_SE;
24603 
24604    /* Peer poking settings */
24605    global_qualify_gap = DEFAULT_QUALIFY_GAP;
24606    global_qualify_peers = DEFAULT_QUALIFY_PEERS;
24607 
24608    /* Initialize some reasonable defaults at SIP reload (used both for channel and as default for devices */
24609    ast_copy_string(sip_cfg.default_context, DEFAULT_CONTEXT, sizeof(sip_cfg.default_context));
24610    sip_cfg.default_subscribecontext[0] = '\0';
24611    default_language[0] = '\0';
24612    default_fromdomain[0] = '\0';
24613    default_qualify = DEFAULT_QUALIFY;
24614    default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
24615    ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
24616    ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
24617    ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
24618    ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833);        /*!< Default DTMF setting: RFC2833 */
24619    ast_set_flag(&global_flags[0], SIP_NAT_RFC3581);         /*!< NAT support if requested by device with rport */
24620    ast_set_flag(&global_flags[0], SIP_DIRECT_MEDIA);        /*!< Allow re-invites */
24621    ast_set_flag(&global_flags[1], SIP_PAGE2_FORWARD_LOOP_DETECTED); /*!< Set up call forward on 482 Loop Detected */
24622 
24623    /* Debugging settings, always default to off */
24624    dumphistory = FALSE;
24625    recordhistory = FALSE;
24626    sipdebug &= ~sip_debug_config;
24627 
24628    /* Misc settings for the channel */
24629    global_relaxdtmf = FALSE;
24630    sip_cfg.callevents = DEFAULT_CALLEVENTS;
24631    global_authfailureevents = FALSE;
24632    global_t1 = DEFAULT_TIMER_T1;
24633    global_timer_b = 64 * DEFAULT_TIMER_T1;
24634    global_t1min = DEFAULT_T1MIN;
24635    global_qualifyfreq = DEFAULT_QUALIFYFREQ;
24636    global_t38_maxdatagram = -1;
24637    global_shrinkcallerid = 1;
24638 
24639    sip_cfg.matchexterniplocally = DEFAULT_MATCHEXTERNIPLOCALLY;
24640 
24641    /* Copy the default jb config over global_jbconf */
24642    memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
24643 
24644    ast_clear_flag(&global_flags[1], SIP_PAGE2_FAX_DETECT);
24645    ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
24646    ast_clear_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT);
24647    ast_clear_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION);
24648 
24649 
24650    /* Read the [general] config section of sip.conf (or from realtime config) */
24651    for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
24652       if (handle_common_options(&global_flags[0], &dummy[0], v))
24653          continue;
24654       if (handle_t38_options(&global_flags[0], &dummy[0], v, &global_t38_maxdatagram)) {
24655          continue;
24656       }
24657       /* handle jb conf */
24658       if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
24659          continue;
24660 
24661       if (!strcasecmp(v->name, "context")) {
24662          ast_copy_string(sip_cfg.default_context, v->value, sizeof(sip_cfg.default_context));
24663       } else if (!strcasecmp(v->name, "subscribecontext")) {
24664          ast_copy_string(sip_cfg.default_subscribecontext, v->value, sizeof(sip_cfg.default_subscribecontext));
24665       } else if (!strcasecmp(v->name, "callcounter")) {
24666          global_callcounter = ast_true(v->value) ? 1 : 0;
24667       } else if (!strcasecmp(v->name, "allowguest")) {
24668          sip_cfg.allowguest = ast_true(v->value) ? 1 : 0;
24669       } else if (!strcasecmp(v->name, "realm")) {
24670          ast_copy_string(sip_cfg.realm, v->value, sizeof(sip_cfg.realm));
24671       } else if (!strcasecmp(v->name, "useragent")) {
24672          ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
24673          ast_debug(1, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
24674       } else if (!strcasecmp(v->name, "sdpsession")) {
24675          ast_copy_string(global_sdpsession, v->value, sizeof(global_sdpsession));
24676       } else if (!strcasecmp(v->name, "sdpowner")) {
24677          /* Field cannot contain spaces */
24678          if (!strstr(v->value, " "))
24679             ast_copy_string(global_sdpowner, v->value, sizeof(global_sdpowner));
24680          else
24681             ast_log(LOG_WARNING, "'%s' must not contain spaces at line %d.  Using default.\n", v->value, v->lineno);
24682       } else if (!strcasecmp(v->name, "allowtransfer")) {
24683          sip_cfg.allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
24684       } else if (!strcasecmp(v->name, "rtcachefriends")) {
24685          ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);   
24686       } else if (!strcasecmp(v->name, "rtsavesysname")) {
24687          sip_cfg.rtsave_sysname = ast_true(v->value);
24688       } else if (!strcasecmp(v->name, "rtupdate")) {
24689          sip_cfg.peer_rtupdate = ast_true(v->value);
24690       } else if (!strcasecmp(v->name, "ignoreregexpire")) {
24691          sip_cfg.ignore_regexpire = ast_true(v->value);
24692       } else if (!strcasecmp(v->name, "timert1")) {
24693          /* Defaults to 500ms, but RFC 3261 states that it is recommended
24694           * for the value to be set higher, though a lower value is only
24695           * allowed on private networks unconnected to the Internet. */
24696          global_t1 = atoi(v->value);
24697          /* Note that timer B is dependent on the value of T1 */
24698          global_timer_b = global_t1 * 64;
24699       } else if (!strcasecmp(v->name, "t1min")) {
24700          global_t1min = atoi(v->value);
24701       } else if (!strcasecmp(v->name, "transport") && !ast_strlen_zero(v->value)) {
24702          char *val = ast_strdupa(v->value);
24703          char *trans;
24704 
24705          while ((trans = strsep(&val, ","))) {
24706             trans = ast_skip_blanks(trans);
24707 
24708             if (!strncasecmp(trans, "udp", 3)) 
24709                default_transports |= SIP_TRANSPORT_UDP;
24710             else if (!strncasecmp(trans, "tcp", 3))
24711                default_transports |= SIP_TRANSPORT_TCP;
24712             else if (!strncasecmp(trans, "tls", 3))
24713                default_transports |= SIP_TRANSPORT_TLS;
24714             else
24715                ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
24716             if (default_primary_transport == 0) {
24717                default_primary_transport = default_transports;
24718             }
24719          }
24720       } else if (!strcasecmp(v->name, "tcpenable")) {
24721          sip_tcp_desc.local_address.sin_family = ast_false(v->value) ? 0 : AF_INET;
24722          ast_debug(2, "Enabling TCP socket for listening\n");
24723       } else if (!strcasecmp(v->name, "tcpbindaddr")) {
24724          int family = sip_tcp_desc.local_address.sin_family;
24725          if (ast_parse_arg(v->value, PARSE_INADDR, &sip_tcp_desc.local_address))
24726             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n", v->name, v->value, v->lineno, config);
24727          sip_tcp_desc.local_address.sin_family = family;
24728          ast_debug(2, "Setting TCP socket address to %s\n", v->value);
24729       } else if (!strcasecmp(v->name, "tlsenable")) {
24730          default_tls_cfg.enabled = ast_true(v->value) ? TRUE : FALSE;
24731          sip_tls_desc.local_address.sin_family = AF_INET;
24732       } else if (!strcasecmp(v->name, "tlscertfile")) {
24733          ast_free(default_tls_cfg.certfile);
24734          default_tls_cfg.certfile = ast_strdup(v->value);
24735       } else if (!strcasecmp(v->name, "tlscipher")) {
24736          ast_free(default_tls_cfg.cipher);
24737          default_tls_cfg.cipher = ast_strdup(v->value);
24738       } else if (!strcasecmp(v->name, "tlscafile")) {
24739          ast_free(default_tls_cfg.cafile);
24740          default_tls_cfg.cafile = ast_strdup(v->value);
24741       } else if (!strcasecmp(v->name, "tlscapath")) {
24742          ast_free(default_tls_cfg.capath);
24743          default_tls_cfg.capath = ast_strdup(v->value);
24744       } else if (!strcasecmp(v->name, "tlsverifyclient")) {
24745          ast_set2_flag(&default_tls_cfg.flags, ast_true(v->value), AST_SSL_VERIFY_CLIENT);   
24746       } else if (!strcasecmp(v->name, "tlsdontverifyserver")) {
24747          ast_set2_flag(&default_tls_cfg.flags, ast_true(v->value), AST_SSL_DONT_VERIFY_SERVER); 
24748       } else if (!strcasecmp(v->name, "tlsbindaddr")) {
24749          if (ast_parse_arg(v->value, PARSE_INADDR, &sip_tls_desc.local_address))
24750             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n", v->name, v->value, v->lineno, config);
24751       } else if (!strcasecmp(v->name, "dynamic_exclude_static") || !strcasecmp(v->name, "dynamic_excludes_static")) {
24752          global_dynamic_exclude_static = ast_true(v->value);
24753       } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
24754          int ha_error = 0;
24755          global_contact_ha = ast_append_ha(v->name + 7, v->value, global_contact_ha, &ha_error);
24756          if (ha_error) {
24757             ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
24758          }
24759       } else if (!strcasecmp(v->name, "rtautoclear")) {
24760          int i = atoi(v->value);
24761          if (i > 0)
24762             sip_cfg.rtautoclear = i;
24763          else
24764             i = 0;
24765          ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
24766       } else if (!strcasecmp(v->name, "usereqphone")) {
24767          ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);   
24768       } else if (!strcasecmp(v->name, "prematuremedia")) {
24769          global_prematuremediafilter = ast_true(v->value);
24770       } else if (!strcasecmp(v->name, "relaxdtmf")) {
24771          global_relaxdtmf = ast_true(v->value);
24772       } else if (!strcasecmp(v->name, "vmexten")) {
24773          ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
24774       } else if (!strcasecmp(v->name, "rtptimeout")) {
24775          if ((sscanf(v->value, "%30d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
24776             ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
24777             global_rtptimeout = 0;
24778          }
24779       } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
24780          if ((sscanf(v->value, "%30d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
24781             ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
24782             global_rtpholdtimeout = 0;
24783          }
24784       } else if (!strcasecmp(v->name, "rtpkeepalive")) {
24785          if ((sscanf(v->value, "%30d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
24786             ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d.  Using default.\n", v->value, v->lineno);
24787             global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
24788          }
24789       } else if (!strcasecmp(v->name, "compactheaders")) {
24790          sip_cfg.compactheaders = ast_true(v->value);
24791       } else if (!strcasecmp(v->name, "notifymimetype")) {
24792          ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
24793       } else if (!strcasecmp(v->name, "directrtpsetup")) {
24794          sip_cfg.directrtpsetup = ast_true(v->value);
24795       } else if (!strcasecmp(v->name, "notifyringing")) {
24796          sip_cfg.notifyringing = ast_true(v->value);
24797       } else if (!strcasecmp(v->name, "notifyhold")) {
24798          sip_cfg.notifyhold = ast_true(v->value);
24799       } else if (!strcasecmp(v->name, "notifycid")) {
24800          if (!strcasecmp(v->value, "ignore-context")) {
24801             sip_cfg.notifycid = IGNORE_CONTEXT;
24802          } else {
24803             sip_cfg.notifycid = ast_true(v->value);
24804          }
24805       } else if (!strcasecmp(v->name, "alwaysauthreject")) {
24806          sip_cfg.alwaysauthreject = ast_true(v->value);
24807       } else if (!strcasecmp(v->name, "mohinterpret")) {
24808          ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
24809       } else if (!strcasecmp(v->name, "mohsuggest")) {
24810          ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
24811       } else if (!strcasecmp(v->name, "language")) {
24812          ast_copy_string(default_language, v->value, sizeof(default_language));
24813       } else if (!strcasecmp(v->name, "regcontext")) {
24814          ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
24815          stringp = newcontexts;
24816          /* Let's remove any contexts that are no longer defined in regcontext */
24817          cleanup_stale_contexts(stringp, oldregcontext);
24818          /* Create contexts if they don't exist already */
24819          while ((context = strsep(&stringp, "&"))) {
24820             ast_copy_string(used_context, context, sizeof(used_context));
24821             ast_context_find_or_create(NULL, NULL, context, "SIP");
24822          }
24823          ast_copy_string(global_regcontext, v->value, sizeof(global_regcontext));
24824       } else if (!strcasecmp(v->name, "regextenonqualify")) {
24825          sip_cfg.regextenonqualify = ast_true(v->value);
24826       } else if (!strcasecmp(v->name, "callerid")) {
24827          ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
24828       } else if (!strcasecmp(v->name, "fromdomain")) {
24829          ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
24830       } else if (!strcasecmp(v->name, "outboundproxy")) {
24831          int portnum;
24832          char *tok, *proxyname;
24833 
24834          if (ast_strlen_zero(v->value)) {
24835             ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf.", v->lineno);
24836             continue;
24837          }
24838 
24839          tok = ast_skip_blanks(strtok(ast_strdupa(v->value), ","));
24840 
24841          sip_parse_host(tok, v->lineno, &proxyname, &portnum, &sip_cfg.outboundproxy.transport);
24842 
24843          sip_cfg.outboundproxy.ip.sin_port = htons(portnum);
24844    
24845          if ((tok = strtok(NULL, ","))) {
24846             sip_cfg.outboundproxy.force = !strncasecmp(ast_skip_blanks(tok), "force", 5);
24847          } else {
24848             sip_cfg.outboundproxy.force = FALSE;
24849          }
24850 
24851          if (ast_strlen_zero(proxyname)) {
24852             ast_log(LOG_WARNING, "you must specify a name for the outboundproxy on line %d of sip.conf.", v->lineno);
24853             sip_cfg.outboundproxy.name[0] = '\0';
24854             continue;
24855          }
24856 
24857          ast_copy_string(sip_cfg.outboundproxy.name, proxyname, sizeof(sip_cfg.outboundproxy.name));
24858 
24859          proxy_update(&sip_cfg.outboundproxy);
24860       } else if (!strcasecmp(v->name, "autocreatepeer")) {
24861          sip_cfg.autocreatepeer = ast_true(v->value);
24862       } else if (!strcasecmp(v->name, "match_auth_username")) {
24863          global_match_auth_username = ast_true(v->value);
24864       } else if (!strcasecmp(v->name, "srvlookup")) {
24865          sip_cfg.srvlookup = ast_true(v->value);
24866       } else if (!strcasecmp(v->name, "pedantic")) {
24867          sip_cfg.pedanticsipchecking = ast_true(v->value);
24868       } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
24869          max_expiry = atoi(v->value);
24870          if (max_expiry < 1)
24871             max_expiry = DEFAULT_MAX_EXPIRY;
24872       } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
24873          min_expiry = atoi(v->value);
24874          if (min_expiry < 1)
24875             min_expiry = DEFAULT_MIN_EXPIRY;
24876       } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
24877          default_expiry = atoi(v->value);
24878          if (default_expiry < 1)
24879             default_expiry = DEFAULT_DEFAULT_EXPIRY;
24880       } else if (!strcasecmp(v->name, "mwiexpiry") || !strcasecmp(v->name, "mwiexpirey")) {
24881          mwi_expiry = atoi(v->value);
24882          if (mwi_expiry < 1)
24883             mwi_expiry = DEFAULT_MWI_EXPIRY;
24884       } else if (!strcasecmp(v->name, "sipdebug")) {
24885          if (ast_true(v->value))
24886             sipdebug |= sip_debug_config;
24887       } else if (!strcasecmp(v->name, "dumphistory")) {
24888          dumphistory = ast_true(v->value);
24889       } else if (!strcasecmp(v->name, "recordhistory")) {
24890          recordhistory = ast_true(v->value);
24891       } else if (!strcasecmp(v->name, "registertimeout")) {
24892          global_reg_timeout = atoi(v->value);
24893          if (global_reg_timeout < 1)
24894             global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
24895       } else if (!strcasecmp(v->name, "registerattempts")) {
24896          global_regattempts_max = atoi(v->value);
24897       } else if (!strcasecmp(v->name, "stunaddr")) {
24898          stunaddr.sin_port = htons(3478);
24899          if (ast_parse_arg(v->value, PARSE_INADDR, &stunaddr))
24900             ast_log(LOG_WARNING, "Invalid STUN server address: %s\n", v->value);
24901          externexpire = time(NULL);
24902       } else if (!strcasecmp(v->name, "bindaddr") || !strcasecmp(v->name, "udpbindaddr")) {
24903          if (ast_parse_arg(v->value, PARSE_INADDR, &bindaddr))
24904             ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
24905       } else if (!strcasecmp(v->name, "localnet")) {
24906          struct ast_ha *na;
24907          int ha_error = 0;
24908 
24909          if (!(na = ast_append_ha("d", v->value, localaddr, &ha_error)))
24910             ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
24911          else
24912             localaddr = na;
24913          if (ha_error)
24914             ast_log(LOG_ERROR, "Bad localnet configuration value line %d : %s\n", v->lineno, v->value);
24915       } else if (!strcasecmp(v->name, "externip")) {
24916          if (ast_parse_arg(v->value, PARSE_INADDR, &externip))
24917             ast_log(LOG_WARNING, "Invalid address for externip keyword: %s\n", v->value);
24918          externexpire = 0;
24919          /* If no port was specified use the value of bindport */
24920          if (!externip.sin_port)
24921             externip.sin_port = bindaddr.sin_port;
24922       } else if (!strcasecmp(v->name, "externhost")) {
24923          ast_copy_string(externhost, v->value, sizeof(externhost));
24924          if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
24925             ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
24926          externexpire = time(NULL);
24927          /* If no port was specified use the value of bindport */
24928          if (!externip.sin_port)
24929             externip.sin_port = bindaddr.sin_port;
24930       } else if (!strcasecmp(v->name, "externrefresh")) {
24931          if (sscanf(v->value, "%30d", &externrefresh) != 1) {
24932             ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
24933             externrefresh = 10;
24934          }
24935       } else if (!strcasecmp(v->name, "allow")) {
24936          int error =  ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, TRUE);
24937          if (error)
24938             ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
24939       } else if (!strcasecmp(v->name, "disallow")) {
24940          int error =  ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, FALSE);
24941          if (error)
24942             ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
24943       } else if (!strcasecmp(v->name, "autoframing")) {
24944          global_autoframing = ast_true(v->value);
24945       } else if (!strcasecmp(v->name, "allowexternaldomains")) {
24946          sip_cfg.allow_external_domains = ast_true(v->value);
24947       } else if (!strcasecmp(v->name, "autodomain")) {
24948          auto_sip_domains = ast_true(v->value);
24949       } else if (!strcasecmp(v->name, "domain")) {
24950          char *domain = ast_strdupa(v->value);
24951          char *cntx = strchr(domain, ',');
24952 
24953          if (cntx)
24954             *cntx++ = '\0';
24955 
24956          if (ast_strlen_zero(cntx))
24957             ast_debug(1, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
24958          if (ast_strlen_zero(domain))
24959             ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
24960          else
24961             add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, cntx ? ast_strip(cntx) : "");
24962       } else if (!strcasecmp(v->name, "register")) {
24963          if (sip_register(v->value, v->lineno) == 0)
24964             registry_count++;
24965       } else if (!strcasecmp(v->name, "mwi")) {
24966          sip_subscribe_mwi(v->value, v->lineno);
24967       } else if (!strcasecmp(v->name, "tos_sip")) {
24968          if (ast_str2tos(v->value, &global_tos_sip))
24969             ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, refer to QoS documentation\n", v->lineno);
24970       } else if (!strcasecmp(v->name, "tos_audio")) {
24971          if (ast_str2tos(v->value, &global_tos_audio))
24972             ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, refer to QoS documentation\n", v->lineno);
24973       } else if (!strcasecmp(v->name, "tos_video")) {
24974          if (ast_str2tos(v->value, &global_tos_video))
24975             ast_log(LOG_WARNING, "Invalid tos_video value at line %d, refer to QoS documentation\n", v->lineno);
24976       } else if (!strcasecmp(v->name, "tos_text")) {
24977          if (ast_str2tos(v->value, &global_tos_text))
24978             ast_log(LOG_WARNING, "Invalid tos_text value at line %d, refer to QoS documentation\n", v->lineno);
24979       } else if (!strcasecmp(v->name, "cos_sip")) {
24980          if (ast_str2cos(v->value, &global_cos_sip))
24981             ast_log(LOG_WARNING, "Invalid cos_sip value at line %d, refer to QoS documentation\n", v->lineno);
24982       } else if (!strcasecmp(v->name, "cos_audio")) {
24983          if (ast_str2cos(v->value, &global_cos_audio))
24984             ast_log(LOG_WARNING, "Invalid cos_audio value at line %d, refer to QoS documentation\n", v->lineno);
24985       } else if (!strcasecmp(v->name, "cos_video")) {
24986          if (ast_str2cos(v->value, &global_cos_video))
24987             ast_log(LOG_WARNING, "Invalid cos_video value at line %d, refer to QoS documentation\n", v->lineno);
24988       } else if (!strcasecmp(v->name, "cos_text")) {
24989          if (ast_str2cos(v->value, &global_cos_text))
24990             ast_log(LOG_WARNING, "Invalid cos_text value at line %d, refer to QoS documentation\n", v->lineno);
24991       } else if (!strcasecmp(v->name, "bindport")) {
24992          int i;
24993          if (sscanf(v->value, "%5d", &i) == 1) {
24994             bindaddr.sin_port = htons(i);
24995          } else {
24996             ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
24997          }
24998       } else if (!strcasecmp(v->name, "qualify")) {
24999          if (!strcasecmp(v->value, "no")) {
25000             default_qualify = 0;
25001          } else if (!strcasecmp(v->value, "yes")) {
25002             default_qualify = DEFAULT_MAXMS;
25003          } else if (sscanf(v->value, "%30d", &default_qualify) != 1) {
25004             ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
25005             default_qualify = 0;
25006          }
25007       } else if (!strcasecmp(v->name, "qualifyfreq")) {
25008          int i;
25009          if (sscanf(v->value, "%30d", &i) == 1)
25010             global_qualifyfreq = i * 1000;
25011          else {
25012             ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
25013             global_qualifyfreq = DEFAULT_QUALIFYFREQ;
25014          }
25015       } else if (!strcasecmp(v->name, "callevents")) {
25016          sip_cfg.callevents = ast_true(v->value);
25017       } else if (!strcasecmp(v->name, "authfailureevents")) {
25018          global_authfailureevents = ast_true(v->value);
25019       } else if (!strcasecmp(v->name, "maxcallbitrate")) {
25020          default_maxcallbitrate = atoi(v->value);
25021          if (default_maxcallbitrate < 0)
25022             default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
25023       } else if (!strcasecmp(v->name, "matchexterniplocally")) {
25024          sip_cfg.matchexterniplocally = ast_true(v->value);
25025       } else if (!strcasecmp(v->name, "session-timers")) {
25026          int i = (int) str2stmode(v->value); 
25027          if (i < 0) {
25028             ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
25029             global_st_mode = SESSION_TIMER_MODE_ACCEPT;
25030          } else {
25031             global_st_mode = i;
25032          }
25033       } else if (!strcasecmp(v->name, "session-expires")) {
25034          if (sscanf(v->value, "%30d", &global_max_se) != 1) {
25035             ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
25036             global_max_se = DEFAULT_MAX_SE;
25037          } 
25038       } else if (!strcasecmp(v->name, "session-minse")) {
25039          if (sscanf(v->value, "%30d", &global_min_se) != 1) {
25040             ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
25041             global_min_se = DEFAULT_MIN_SE;
25042          } 
25043          if (global_min_se < 90) {
25044             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);
25045             global_min_se = DEFAULT_MIN_SE;
25046          } 
25047       } else if (!strcasecmp(v->name, "session-refresher")) {
25048          int i = (int) str2strefresher(v->value); 
25049          if (i < 0) {
25050             ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
25051             global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
25052          } else {
25053             global_st_refresher = i;
25054          }
25055       } else if (!strcasecmp(v->name, "qualifygap")) {
25056          if (sscanf(v->value, "%30d", &global_qualify_gap) != 1) {
25057             ast_log(LOG_WARNING, "Invalid qualifygap '%s' at line %d of %s\n", v->value, v->lineno, config);
25058             global_qualify_gap = DEFAULT_QUALIFY_GAP;
25059          }
25060       } else if (!strcasecmp(v->name, "qualifypeers")) {
25061          if (sscanf(v->value, "%30d", &global_qualify_peers) != 1) {
25062             ast_log(LOG_WARNING, "Invalid pokepeers '%s' at line %d of %s\n", v->value, v->lineno, config);
25063             global_qualify_peers = DEFAULT_QUALIFY_PEERS;
25064          }
25065       } else if (!strcasecmp(v->name, "shrinkcallerid")) {
25066          if (ast_true(v->value)) {
25067             global_shrinkcallerid = 1;
25068          } else if (ast_false(v->value)) {
25069             global_shrinkcallerid = 0;
25070          } else {
25071             ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
25072          }
25073       }
25074    }
25075 
25076    if (!sip_cfg.allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
25077       ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
25078       sip_cfg.allow_external_domains = 1;
25079    }
25080    /* If not configured, set default transports */
25081    if (default_transports == 0) {
25082       default_transports = default_primary_transport = SIP_TRANSPORT_UDP;
25083    }
25084    
25085    /* Build list of authentication to various SIP realms, i.e. service providers */
25086    for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
25087       /* Format for authentication is auth = username:password@realm */
25088       if (!strcasecmp(v->name, "auth"))
25089          authl = add_realm_authentication(authl, v->value, v->lineno);
25090    }
25091 
25092    /* Set UDP address and open socket */
25093    bindaddr.sin_family = AF_INET;
25094    internip = bindaddr;
25095    if (ast_find_ourip(&internip.sin_addr, bindaddr)) {
25096       ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
25097       ast_config_destroy(cfg);
25098       return 0;
25099    }
25100 
25101    ast_mutex_lock(&netlock);
25102    if ((sipsock > -1) && (memcmp(&old_bindaddr, &bindaddr, sizeof(struct sockaddr_in)))) {
25103       close(sipsock);
25104       sipsock = -1;
25105    }
25106    if (sipsock < 0) {
25107       sipsock = socket(AF_INET, SOCK_DGRAM, 0);
25108       if (sipsock < 0) {
25109          ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
25110          ast_config_destroy(cfg);
25111          return -1;
25112       } else {
25113          /* Allow SIP clients on the same host to access us: */
25114          const int reuseFlag = 1;
25115 
25116          setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
25117                (const char*)&reuseFlag,
25118                sizeof reuseFlag);
25119 
25120          ast_enable_packet_fragmentation(sipsock);
25121 
25122          if (bind(sipsock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
25123             ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
25124             ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
25125             strerror(errno));
25126             close(sipsock);
25127             sipsock = -1;
25128          } else {
25129             ast_verb(2, "SIP Listening on %s:%d\n",
25130                   ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
25131             ast_netsock_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
25132          }
25133       }
25134    }
25135    if (stunaddr.sin_addr.s_addr != 0) {
25136       ast_debug(1, "stun to %s:%d\n",
25137          ast_inet_ntoa(stunaddr.sin_addr) , ntohs(stunaddr.sin_port));
25138       ast_stun_request(sipsock, &stunaddr,
25139          NULL, &externip);
25140       ast_debug(1, "STUN sees us at %s:%d\n", 
25141          ast_inet_ntoa(externip.sin_addr) , ntohs(externip.sin_port));
25142    }
25143    ast_mutex_unlock(&netlock);
25144 
25145    /* Start TCP server */
25146    ast_tcptls_server_start(&sip_tcp_desc);
25147    if (sip_tcp_desc.accept_fd == -1 &&  sip_tcp_desc.local_address.sin_family == AF_INET) {
25148       /* TCP server start failed. Tell the admin */
25149       ast_log(LOG_ERROR, "SIP TCP Server start failed. Not listening on TCP socket.\n");
25150       sip_tcp_desc.local_address.sin_family = 0;
25151    } else {
25152       ast_debug(2, "SIP TCP server started\n");
25153    }
25154 
25155    /* Start TLS server if needed */
25156    memcpy(sip_tls_desc.tls_cfg, &default_tls_cfg, sizeof(default_tls_cfg));
25157 
25158    if (ast_ssl_setup(sip_tls_desc.tls_cfg)) {
25159       ast_tcptls_server_start(&sip_tls_desc);
25160       if (default_tls_cfg.enabled && sip_tls_desc.accept_fd == -1) {
25161          ast_log(LOG_ERROR, "TLS Server start failed. Not listening on TLS socket.\n");
25162          sip_tls_desc.tls_cfg = NULL;
25163       }
25164    } else if (sip_tls_desc.tls_cfg->enabled) {
25165       sip_tls_desc.tls_cfg = NULL;
25166       ast_log(LOG_WARNING, "SIP TLS server did not load because of errors.\n");
25167    }
25168 
25169    if (ucfg) {
25170       struct ast_variable *gen;
25171       int genhassip, genregistersip;
25172       const char *hassip, *registersip;
25173       
25174       genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
25175       genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
25176       gen = ast_variable_browse(ucfg, "general");
25177       cat = ast_category_browse(ucfg, NULL);
25178       while (cat) {
25179          if (strcasecmp(cat, "general")) {
25180             hassip = ast_variable_retrieve(ucfg, cat, "hassip");
25181             registersip = ast_variable_retrieve(ucfg, cat, "registersip");
25182             if (ast_true(hassip) || (!hassip && genhassip)) {
25183                peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0, 0);
25184                if (peer) {
25185                   /* user.conf entries are always of type friend */
25186                   peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
25187                   ao2_t_link(peers, peer, "link peer into peer table");
25188                   if ((peer->type & SIP_TYPE_PEER) && peer->addr.sin_addr.s_addr) {
25189                      ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
25190                   }
25191                   
25192                   unref_peer(peer, "unref_peer: from reload_config");
25193                   peer_count++;
25194                }
25195             }
25196             if (ast_true(registersip) || (!registersip && genregistersip)) {
25197                char tmp[256];
25198                const char *host = ast_variable_retrieve(ucfg, cat, "host");
25199                const char *username = ast_variable_retrieve(ucfg, cat, "username");
25200                const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
25201                const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
25202                const char *authuser = ast_variable_retrieve(ucfg, cat, "authuser");
25203                if (!host)
25204                   host = ast_variable_retrieve(ucfg, "general", "host");
25205                if (!username)
25206                   username = ast_variable_retrieve(ucfg, "general", "username");
25207                if (!secret)
25208                   secret = ast_variable_retrieve(ucfg, "general", "secret");
25209                if (!contact)
25210                   contact = "s";
25211                if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
25212                   if (!ast_strlen_zero(secret)) {
25213                      if (!ast_strlen_zero(authuser)) {
25214                         snprintf(tmp, sizeof(tmp), "%s?%s:%s:%s@%s/%s", cat, username, secret, authuser, host, contact);
25215                      } else {
25216                         snprintf(tmp, sizeof(tmp), "%s?%s:%s@%s/%s", cat, username, secret, host, contact);
25217                      }
25218                   } else if (!ast_strlen_zero(authuser)) {
25219                      snprintf(tmp, sizeof(tmp), "%s?%s::%s@%s/%s", cat, username, authuser, host, contact);
25220                   } else {
25221                      snprintf(tmp, sizeof(tmp), "%s?%s@%s/%s", cat, username, host, contact);
25222                   }
25223                   if (sip_register(tmp, 0) == 0)
25224                      registry_count++;
25225                }
25226             }
25227          }
25228          cat = ast_category_browse(ucfg, cat);
25229       }
25230       ast_config_destroy(ucfg);
25231    }
25232 
25233    /* Load peers, users and friends */
25234    cat = NULL;
25235    while ( (cat = ast_category_browse(cfg, cat)) ) {
25236       const char *utype;
25237       if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
25238          continue;
25239       utype = ast_variable_retrieve(cfg, cat, "type");
25240       if (!utype) {
25241          ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
25242          continue;
25243       } else {
25244          if (!strcasecmp(utype, "user")) {
25245             ;
25246          } else if (!strcasecmp(utype, "friend")) {
25247             ;
25248          } else if (!strcasecmp(utype, "peer")) {
25249             ;
25250          } else {
25251             ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
25252             continue;
25253          }
25254          peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0, 0);
25255          if (peer) {
25256             ao2_t_link(peers, peer, "link peer into peers table");
25257             if ((peer->type & SIP_TYPE_PEER) && peer->addr.sin_addr.s_addr) {
25258                ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
25259             }
25260             unref_peer(peer, "unref the result of the build_peer call. Now, the links from the tables are the only ones left.");
25261             peer_count++;
25262          }
25263       }
25264    }
25265 
25266    /* Add default domains - host name, IP address and IP:port
25267     * Only do this if user added any sip domain with "localdomains" 
25268     * In order to *not* break backwards compatibility 
25269     *    Some phones address us at IP only, some with additional port number 
25270     */
25271    if (auto_sip_domains) {
25272       char temp[MAXHOSTNAMELEN];
25273 
25274       /* First our default IP address */
25275       if (bindaddr.sin_addr.s_addr) {
25276          add_sip_domain(ast_inet_ntoa(bindaddr.sin_addr), SIP_DOMAIN_AUTO, NULL);
25277       } else if (internip.sin_addr.s_addr) {
25278       /* Our internal IP address, if configured */
25279          add_sip_domain(ast_inet_ntoa(internip.sin_addr), SIP_DOMAIN_AUTO, NULL);
25280       } else {
25281          ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
25282       }
25283 
25284       /* If TCP is running on a different IP than UDP, then add it too */
25285       if (sip_tcp_desc.local_address.sin_addr.s_addr && !inaddrcmp(&bindaddr, &sip_tcp_desc.local_address))
25286          add_sip_domain(ast_inet_ntoa(sip_tcp_desc.local_address.sin_addr), SIP_DOMAIN_AUTO, NULL);
25287 
25288       /* If TLS is running on a differen IP than UDP and TCP, then add that too */
25289       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))
25290          add_sip_domain(ast_inet_ntoa(sip_tls_desc.local_address.sin_addr), SIP_DOMAIN_AUTO, NULL);
25291 
25292       /* Our extern IP address, if configured */
25293       if (externip.sin_addr.s_addr)
25294          add_sip_domain(ast_inet_ntoa(externip.sin_addr), SIP_DOMAIN_AUTO, NULL);
25295 
25296       /* Extern host name (NAT traversal support) */
25297       if (!ast_strlen_zero(externhost))
25298          add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
25299       
25300       /* Our host name */
25301       if (!gethostname(temp, sizeof(temp)))
25302          add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
25303    }
25304 
25305    /* Release configuration from memory */
25306    ast_config_destroy(cfg);
25307 
25308    /* Load the list of manual NOTIFY types to support */
25309    if (notify_types)
25310       ast_config_destroy(notify_types);
25311    if ((notify_types = ast_config_load(notify_config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
25312       ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed.\n", notify_config);
25313       notify_types = NULL;
25314    }
25315 
25316    /* Done, tell the manager */
25317    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);
25318    run_end = time(0);
25319    ast_debug(4, "SIP reload_config done...Runtime= %d sec\n", (int)(run_end-run_start));
25320 
25321    return 0;
25322 }
25323 
25324 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
25325 {
25326    struct sip_pvt *p;
25327    struct ast_udptl *udptl = NULL;
25328    
25329    p = chan->tech_pvt;
25330    if (!p)
25331       return NULL;
25332    
25333    sip_pvt_lock(p);
25334    if (p->udptl && ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
25335       udptl = p->udptl;
25336    sip_pvt_unlock(p);
25337    return udptl;
25338 }
25339 
25340 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
25341 {
25342    struct sip_pvt *p;
25343    
25344    p = chan->tech_pvt;
25345    if (!p)
25346       return -1;
25347    sip_pvt_lock(p);
25348    if (udptl)
25349       ast_udptl_get_peer(udptl, &p->udptlredirip);
25350    else
25351       memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
25352    if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
25353       if (!p->pendinginvite) {
25354          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);
25355          transmit_reinvite_with_sdp(p, TRUE, FALSE);
25356       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
25357          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);
25358          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
25359       }
25360    }
25361    /* Reset lastrtprx timer */
25362    p->lastrtprx = p->lastrtptx = time(NULL);
25363    sip_pvt_unlock(p);
25364    return 0;
25365 }
25366 
25367 /*! \brief Returns null if we can't reinvite audio (part of RTP interface) */
25368 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
25369 {
25370    struct sip_pvt *p = NULL;
25371    enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
25372 
25373    if (!(p = chan->tech_pvt))
25374       return AST_RTP_GET_FAILED;
25375 
25376    sip_pvt_lock(p);
25377    if (!(p->rtp)) {
25378       sip_pvt_unlock(p);
25379       return AST_RTP_GET_FAILED;
25380    }
25381 
25382    *rtp = p->rtp;
25383 
25384    if (ast_rtp_getnat(*rtp) && !ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT))
25385       res = AST_RTP_TRY_PARTIAL;
25386    else if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
25387       res = AST_RTP_TRY_NATIVE;
25388    else if (ast_test_flag(&global_jbconf, AST_JB_FORCED))
25389       res = AST_RTP_GET_FAILED;
25390 
25391    sip_pvt_unlock(p);
25392 
25393    return res;
25394 }
25395 
25396 /*! \brief Returns null if we can't reinvite video (part of RTP interface) */
25397 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
25398 {
25399    struct sip_pvt *p = NULL;
25400    enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
25401    
25402    if (!(p = chan->tech_pvt))
25403       return AST_RTP_GET_FAILED;
25404 
25405    sip_pvt_lock(p);
25406    if (!(p->vrtp)) {
25407       sip_pvt_unlock(p);
25408       return AST_RTP_GET_FAILED;
25409    }
25410 
25411    *rtp = p->vrtp;
25412 
25413    if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
25414       res = AST_RTP_TRY_NATIVE;
25415 
25416    sip_pvt_unlock(p);
25417 
25418    return res;
25419 }
25420 
25421 /*! \brief Returns null if we can't reinvite text (part of RTP interface) */
25422 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
25423 {
25424    struct sip_pvt *p = NULL;
25425    enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
25426    
25427    if (!(p = chan->tech_pvt))
25428       return AST_RTP_GET_FAILED;
25429 
25430    sip_pvt_lock(p);
25431    if (!(p->trtp)) {
25432       sip_pvt_unlock(p);
25433       return AST_RTP_GET_FAILED;
25434    }
25435 
25436    *rtp = p->trtp;
25437 
25438    if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
25439       res = AST_RTP_TRY_NATIVE;
25440 
25441    sip_pvt_unlock(p);
25442 
25443    return res;
25444 }
25445 
25446 /*! \brief Set the RTP peer for this call */
25447 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)
25448 {
25449    struct sip_pvt *p;
25450    int changed = 0;
25451 
25452    p = chan->tech_pvt;
25453    if (!p) 
25454       return -1;
25455 
25456    /* Disable early RTP bridge  */
25457    if (!ast_bridged_channel(chan) && !sip_cfg.directrtpsetup)  /* We are in early state */
25458       return 0;
25459 
25460    sip_pvt_lock(p);
25461    if (p->alreadygone) {
25462       /* If we're destroyed, don't bother */
25463       sip_pvt_unlock(p);
25464       return 0;
25465    }
25466 
25467    /* if this peer cannot handle reinvites of the media stream to devices
25468       that are known to be behind a NAT, then stop the process now
25469    */
25470         if (nat_active && !ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
25471                 sip_pvt_unlock(p);
25472                 return 0;
25473         }
25474 
25475    if (rtp) {
25476       changed |= ast_rtp_get_peer(rtp, &p->redirip);
25477    } else if (p->redirip.sin_addr.s_addr || ntohs(p->redirip.sin_port) != 0) {
25478       memset(&p->redirip, 0, sizeof(p->redirip));
25479       changed = 1;
25480    }
25481    if (vrtp) {
25482       changed |= ast_rtp_get_peer(vrtp, &p->vredirip);
25483    } else if (p->vredirip.sin_addr.s_addr || ntohs(p->vredirip.sin_port) != 0) {
25484       memset(&p->vredirip, 0, sizeof(p->vredirip));
25485       changed = 1;
25486    }
25487    if (trtp) {
25488       changed |= ast_rtp_get_peer(trtp, &p->tredirip);
25489    } else if (p->tredirip.sin_addr.s_addr || ntohs(p->tredirip.sin_port) != 0) {
25490       memset(&p->tredirip, 0, sizeof(p->tredirip));
25491       changed = 1;
25492    }
25493    if (codecs && (p->redircodecs != codecs)) {
25494       p->redircodecs = codecs;
25495       changed = 1;
25496    }
25497    if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
25498       if (chan->_state != AST_STATE_UP) { /* We are in early state */
25499          if (p->do_history)
25500             append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
25501          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));
25502       } else if (!p->pendinginvite) {     /* We are up, and have no outstanding invite */
25503          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));
25504          transmit_reinvite_with_sdp(p, FALSE, FALSE);
25505       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
25506          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));
25507          /* We have a pending Invite. Send re-invite when we're done with the invite */
25508          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);   
25509       }
25510    }
25511    /* Reset lastrtprx timer */
25512    p->lastrtprx = p->lastrtptx = time(NULL);
25513    sip_pvt_unlock(p);
25514    return 0;
25515 }
25516 
25517 static char *app_dtmfmode = "SIPDtmfMode";
25518 static char *app_sipaddheader = "SIPAddHeader";
25519 static char *app_sipremoveheader = "SIPRemoveHeader";
25520 
25521 /*! \brief Set the DTMFmode for an outbound SIP call (application) */
25522 static int sip_dtmfmode(struct ast_channel *chan, void *data)
25523 {
25524    struct sip_pvt *p;
25525    char *mode = data;
25526 
25527    if (!data) {
25528       ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
25529       return 0;
25530    }
25531    ast_channel_lock(chan);
25532    if (!IS_SIP_TECH(chan->tech)) {
25533       ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
25534       ast_channel_unlock(chan);
25535       return 0;
25536    }
25537    p = chan->tech_pvt;
25538    if (!p) {
25539       ast_channel_unlock(chan);
25540       return 0;
25541    }
25542    sip_pvt_lock(p);
25543    if (!strcasecmp(mode, "info")) {
25544       ast_clear_flag(&p->flags[0], SIP_DTMF);
25545       ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
25546       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
25547    } else if (!strcasecmp(mode, "shortinfo")) {
25548       ast_clear_flag(&p->flags[0], SIP_DTMF);
25549       ast_set_flag(&p->flags[0], SIP_DTMF_SHORTINFO);
25550       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
25551    } else if (!strcasecmp(mode, "rfc2833")) {
25552       ast_clear_flag(&p->flags[0], SIP_DTMF);
25553       ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
25554       p->jointnoncodeccapability |= AST_RTP_DTMF;
25555    } else if (!strcasecmp(mode, "inband")) { 
25556       ast_clear_flag(&p->flags[0], SIP_DTMF);
25557       ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
25558       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
25559    } else
25560       ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n", mode);
25561    if (p->rtp)
25562       ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
25563    if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
25564       if (!p->dsp) {
25565          p->dsp = ast_dsp_new();
25566          ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
25567       }
25568    } else {
25569       if (p->dsp) {
25570          ast_dsp_free(p->dsp);
25571          p->dsp = NULL;
25572       }
25573    }
25574    sip_pvt_unlock(p);
25575    ast_channel_unlock(chan);
25576    return 0;
25577 }
25578 
25579 /*! \brief Add a SIP header to an outbound INVITE */
25580 static int sip_addheader(struct ast_channel *chan, void *data)
25581 {
25582    int no = 0;
25583    int ok = FALSE;
25584    char varbuf[30];
25585    char *inbuf = data, *subbuf;
25586    
25587    if (ast_strlen_zero(inbuf)) {
25588       ast_log(LOG_WARNING, "This application requires the argument: Header\n");
25589       return 0;
25590    }
25591    ast_channel_lock(chan);
25592 
25593    /* Check for headers */
25594    while (!ok && no <= 50) {
25595       no++;
25596       snprintf(varbuf, sizeof(varbuf), "__SIPADDHEADER%.2d", no);
25597 
25598       /* Compare without the leading underscores */
25599       if ((pbx_builtin_getvar_helper(chan, (const char *) varbuf + 2) == (const char *) NULL)) {
25600          ok = TRUE;
25601       }
25602    }
25603    if (ok) {
25604       size_t len = strlen(inbuf);
25605       subbuf = alloca(len + 1);
25606       ast_get_encoded_str(inbuf, subbuf, len + 1);
25607       pbx_builtin_setvar_helper(chan, varbuf, subbuf);
25608       if (sipdebug) {
25609          ast_debug(1, "SIP Header added \"%s\" as %s\n", inbuf, varbuf);
25610       }
25611    } else {
25612       ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
25613    }
25614    ast_channel_unlock(chan);
25615    return 0;
25616 }
25617 
25618 /*! \brief Remove SIP headers added previously with SipAddHeader application */
25619 static int sip_removeheader(struct ast_channel *chan, void *data)
25620 {
25621    struct ast_var_t *newvariable;
25622    struct varshead *headp;
25623    int removeall = 0;
25624    char *inbuf = (char *) data;
25625 
25626    if (ast_strlen_zero(inbuf)) {
25627       removeall = 1;
25628    }
25629    ast_channel_lock(chan);
25630  
25631    headp=&chan->varshead;
25632    AST_LIST_TRAVERSE_SAFE_BEGIN (headp, newvariable, entries) {
25633       if (strncasecmp(ast_var_name(newvariable), "SIPADDHEADER", strlen("SIPADDHEADER")) == 0) {
25634          if (removeall || (!strncasecmp(ast_var_value(newvariable),inbuf,strlen(inbuf)))) {
25635             if (sipdebug)
25636                ast_log(LOG_DEBUG,"removing SIP Header \"%s\" as %s\n",
25637                   ast_var_value(newvariable),
25638                   ast_var_name(newvariable));
25639             AST_LIST_REMOVE_CURRENT(entries);
25640             ast_var_delete(newvariable);
25641          }
25642       }
25643    }
25644    AST_LIST_TRAVERSE_SAFE_END;
25645  
25646    ast_channel_unlock(chan);
25647    return 0;
25648 }
25649 
25650 /*! \brief Transfer call before connect with a 302 redirect
25651 \note Called by the transfer() dialplan application through the sip_transfer()
25652    pbx interface function if the call is in ringing state 
25653 \todo Fix this function so that we wait for reply to the REFER and
25654    react to errors, denials or other issues the other end might have.
25655  */
25656 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
25657 {
25658    char *cdest;
25659    char *extension, *host, *port;
25660    char tmp[80];
25661 
25662    cdest = ast_strdupa(dest);
25663    
25664    extension = strsep(&cdest, "@");
25665    host = strsep(&cdest, ":");
25666    port = strsep(&cdest, ":");
25667    if (ast_strlen_zero(extension)) {
25668       ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
25669       return 0;
25670    }
25671 
25672    /* we'll issue the redirect message here */
25673    if (!host) {
25674       char *localtmp;
25675 
25676       ast_copy_string(tmp, get_header(&p->initreq, "To"), sizeof(tmp));
25677       if (ast_strlen_zero(tmp)) {
25678          ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
25679          return 0;
25680       }
25681       if ( ( (localtmp = strcasestr(tmp, "sip:")) || (localtmp = strcasestr(tmp, "sips:")) ) 
25682          && (localtmp = strchr(localtmp, '@'))) {
25683          char lhost[80], lport[80];
25684 
25685          memset(lhost, 0, sizeof(lhost));
25686          memset(lport, 0, sizeof(lport));
25687          localtmp++;
25688          /* This is okey because lhost and lport are as big as tmp */
25689          sscanf(localtmp, "%80[^<>:; ]:%80[^<>:; ]", lhost, lport);
25690          if (ast_strlen_zero(lhost)) {
25691             ast_log(LOG_ERROR, "Can't find the host address\n");
25692             return 0;
25693          }
25694          host = ast_strdupa(lhost);
25695          if (!ast_strlen_zero(lport)) {
25696             port = ast_strdupa(lport);
25697          }
25698       }
25699    }
25700 
25701    ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s%s%s>", extension, host, port ? ":" : "", port ? port : "");
25702    transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
25703 
25704    sip_scheddestroy(p, SIP_TRANS_TIMEOUT);   /* Make sure we stop send this reply. */
25705    sip_alreadygone(p);
25706    /* hangup here */
25707    return 0;
25708 }
25709 
25710 /*! \brief Return SIP UA's codec (part of the RTP interface) */
25711 static int sip_get_codec(struct ast_channel *chan)
25712 {
25713    struct sip_pvt *p = chan->tech_pvt;
25714    return p->jointcapability ? p->jointcapability : p->capability;   
25715 }
25716 
25717 /*! \brief Send a poke to all known peers */
25718 static void sip_poke_all_peers(void)
25719 {
25720    int ms = 0, num = 0;
25721    struct ao2_iterator i;
25722    struct sip_peer *peer;
25723 
25724    if (!speerobjs)   /* No peers, just give up */
25725       return;
25726 
25727    i = ao2_iterator_init(peers, 0);
25728    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
25729       ao2_lock(peer);
25730       if (num == global_qualify_peers) {
25731          ms += global_qualify_gap;
25732          num = 0;
25733       } else {
25734          num++;
25735       }
25736       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ms, sip_poke_peer_s, peer,
25737             unref_peer(_data, "removing poke peer ref"),
25738             unref_peer(peer, "removing poke peer ref"),
25739             ref_peer(peer, "adding poke peer ref"));
25740       ao2_unlock(peer);
25741       unref_peer(peer, "toss iterator peer ptr");
25742    }
25743    ao2_iterator_destroy(&i);
25744 }
25745 
25746 /*! \brief Send all known registrations */
25747 static void sip_send_all_registers(void)
25748 {
25749    int ms;
25750    int regspacing;
25751    if (!regobjs)
25752       return;
25753    regspacing = default_expiry * 1000/regobjs;
25754    if (regspacing > 100)
25755       regspacing = 100;
25756    ms = regspacing;
25757    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
25758       ASTOBJ_WRLOCK(iterator);
25759       ms += regspacing;
25760       AST_SCHED_REPLACE_UNREF(iterator->expire, sched, ms, sip_reregister, iterator, 
25761                         registry_unref(_data, "REPLACE sched del decs the refcount"),
25762                         registry_unref(iterator, "REPLACE sched add failure decs the refcount"),
25763                         registry_addref(iterator, "REPLACE sched add incs the refcount"));
25764       ASTOBJ_UNLOCK(iterator);
25765    } while (0)
25766    );
25767 }
25768 
25769 /*! \brief Send all MWI subscriptions */
25770 static void sip_send_all_mwi_subscriptions(void)
25771 {
25772    ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
25773       ASTOBJ_WRLOCK(iterator);
25774       AST_SCHED_DEL(sched, iterator->resub);
25775       if ((iterator->resub = ast_sched_add(sched, 1, sip_subscribe_mwi_do, ASTOBJ_REF(iterator))) < 0) {
25776          ASTOBJ_UNREF(iterator, sip_subscribe_mwi_destroy);
25777       }
25778       ASTOBJ_UNLOCK(iterator);
25779    } while (0));
25780 }
25781 
25782 /*! \brief Reload module */
25783 static int sip_do_reload(enum channelreloadreason reason)
25784 {
25785    time_t start_poke, end_poke;
25786    
25787    reload_config(reason);
25788    ast_sched_dump(sched);
25789 
25790    start_poke = time(0);
25791    /* Prune peers who still are supposed to be deleted */
25792    ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, NULL,
25793          "callback to remove marked peers");
25794    
25795    ast_debug(4, "--------------- Done destroying pruned peers\n");
25796 
25797    /* Send qualify (OPTIONS) to all peers */
25798    sip_poke_all_peers();
25799 
25800    /* Register with all services */
25801    sip_send_all_registers();
25802 
25803    sip_send_all_mwi_subscriptions();
25804 
25805    end_poke = time(0);
25806    
25807    ast_debug(4, "do_reload finished. peer poke/prune reg contact time = %d sec.\n", (int)(end_poke-start_poke));
25808 
25809    ast_debug(4, "--------------- SIP reload done\n");
25810 
25811    return 0;
25812 }
25813 
25814 /*! \brief Force reload of module from cli */
25815 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
25816 {
25817    
25818    switch (cmd) {
25819    case CLI_INIT:
25820       e->command = "sip reload";
25821       e->usage =
25822          "Usage: sip reload\n"
25823          "       Reloads SIP configuration from sip.conf\n";
25824       return NULL;
25825    case CLI_GENERATE:
25826       return NULL;
25827    }
25828 
25829    ast_mutex_lock(&sip_reload_lock);
25830    if (sip_reloading) 
25831       ast_verbose("Previous SIP reload not yet done\n");
25832    else {
25833       sip_reloading = TRUE;
25834       sip_reloadreason = (a && a->fd) ? CHANNEL_CLI_RELOAD : CHANNEL_MODULE_RELOAD;
25835    }
25836    ast_mutex_unlock(&sip_reload_lock);
25837    restart_monitor();
25838 
25839    return CLI_SUCCESS;
25840 }
25841 
25842 /*! \brief  Part of Asterisk module interface */
25843 static int reload(void)
25844 {
25845    if (sip_reload(0, 0, NULL))
25846       return 0;
25847    return 1;
25848 }
25849 
25850 /*! \brief SIP Cli commands definition */
25851 static struct ast_cli_entry cli_sip[] = {
25852    AST_CLI_DEFINE(sip_show_channels, "List active SIP channels or subscriptions"),
25853    AST_CLI_DEFINE(sip_show_channelstats, "List statistics for active SIP channels"),
25854    AST_CLI_DEFINE(sip_show_domains, "List our local SIP domains"),
25855    AST_CLI_DEFINE(sip_show_inuse, "List all inuse/limits"),
25856    AST_CLI_DEFINE(sip_show_objects, "List all SIP object allocations"),
25857    AST_CLI_DEFINE(sip_show_peers, "List defined SIP peers"),
25858    AST_CLI_DEFINE(sip_show_registry, "List SIP registration status"),
25859    AST_CLI_DEFINE(sip_unregister, "Unregister (force expiration) a SIP peer from the registry"),
25860    AST_CLI_DEFINE(sip_show_settings, "Show SIP global settings"),
25861    AST_CLI_DEFINE(sip_show_mwi, "Show MWI subscriptions"),
25862    AST_CLI_DEFINE(sip_cli_notify, "Send a notify packet to a SIP peer"),
25863    AST_CLI_DEFINE(sip_show_channel, "Show detailed SIP channel info"),
25864    AST_CLI_DEFINE(sip_show_history, "Show SIP dialog history"),
25865    AST_CLI_DEFINE(sip_show_peer, "Show details on specific SIP peer"),
25866    AST_CLI_DEFINE(sip_show_users, "List defined SIP users"),
25867    AST_CLI_DEFINE(sip_show_user, "Show details on specific SIP user"),
25868    AST_CLI_DEFINE(sip_qualify_peer, "Send an OPTIONS packet to a peer"),
25869    AST_CLI_DEFINE(sip_show_sched, "Present a report on the status of the sched queue"),
25870    AST_CLI_DEFINE(sip_prune_realtime, "Prune cached Realtime users/peers"),
25871    AST_CLI_DEFINE(sip_do_debug, "Enable/Disable SIP debugging"),
25872    AST_CLI_DEFINE(sip_set_history, "Enable/Disable SIP history"),
25873    AST_CLI_DEFINE(sip_reload, "Reload SIP configuration"),
25874    AST_CLI_DEFINE(sip_show_tcp, "List TCP Connections")
25875 };
25876 
25877 /*! \brief PBX load module - initialization */
25878 static int load_module(void)
25879 {
25880    ast_verbose("SIP channel loading...\n");
25881    /* the fact that ao2_containers can't resize automatically is a major worry! */
25882    /* if the number of objects gets above MAX_XXX_BUCKETS, things will slow down */
25883    peers = ao2_t_container_alloc(HASH_PEER_SIZE, peer_hash_cb, peer_cmp_cb, "allocate peers");
25884    peers_by_ip = ao2_t_container_alloc(HASH_PEER_SIZE, peer_iphash_cb, peer_ipcmp_cb, "allocate peers_by_ip");
25885    dialogs = ao2_t_container_alloc(HASH_DIALOG_SIZE, dialog_hash_cb, dialog_cmp_cb, "allocate dialogs");
25886    threadt = ao2_t_container_alloc(HASH_DIALOG_SIZE, threadt_hash_cb, threadt_cmp_cb, "allocate threadt table");
25887    
25888    ASTOBJ_CONTAINER_INIT(&regl); /* Registry object list -- not searched for anything */
25889    ASTOBJ_CONTAINER_INIT(&submwil); /* MWI subscription object list */
25890 
25891    if (!(sched = sched_context_create())) {
25892       ast_log(LOG_ERROR, "Unable to create scheduler context\n");
25893       return AST_MODULE_LOAD_FAILURE;
25894    }
25895 
25896    if (!(io = io_context_create())) {
25897       ast_log(LOG_ERROR, "Unable to create I/O context\n");
25898       sched_context_destroy(sched);
25899       return AST_MODULE_LOAD_FAILURE;
25900    }
25901 
25902    sip_reloadreason = CHANNEL_MODULE_LOAD;
25903 
25904    if(reload_config(sip_reloadreason)) /* Load the configuration from sip.conf */
25905       return AST_MODULE_LOAD_DECLINE;
25906 
25907    /* Prepare the version that does not require DTMF BEGIN frames.
25908     * We need to use tricks such as memcpy and casts because the variable
25909     * has const fields.
25910     */
25911    memcpy(&sip_tech_info, &sip_tech, sizeof(sip_tech));
25912    memset((void *) &sip_tech_info.send_digit_begin, 0, sizeof(sip_tech_info.send_digit_begin));
25913 
25914    /* Make sure we can register our sip channel type */
25915    if (ast_channel_register(&sip_tech)) {
25916       ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
25917       io_context_destroy(io);
25918       sched_context_destroy(sched);
25919       return AST_MODULE_LOAD_FAILURE;
25920    }
25921 
25922    /* Register all CLI functions for SIP */
25923    ast_cli_register_multiple(cli_sip, ARRAY_LEN(cli_sip));
25924 
25925    /* Tell the RTP subdriver that we're here */
25926    ast_rtp_proto_register(&sip_rtp);
25927 
25928    /* Tell the UDPTL subdriver that we're here */
25929    ast_udptl_proto_register(&sip_udptl);
25930 
25931    /* Register dialplan applications */
25932    ast_register_application_xml(app_dtmfmode, sip_dtmfmode);
25933    ast_register_application_xml(app_sipaddheader, sip_addheader);
25934    ast_register_application_xml(app_sipremoveheader, sip_removeheader);
25935 
25936    /* Register dialplan functions */
25937    ast_custom_function_register(&sip_header_function);
25938    ast_custom_function_register(&sippeer_function);
25939    ast_custom_function_register(&sipchaninfo_function);
25940    ast_custom_function_register(&checksipdomain_function);
25941 
25942    /* Register manager commands */
25943    ast_manager_register2("SIPpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peers,
25944          "List SIP peers (text format)", mandescr_show_peers);
25945    ast_manager_register2("SIPshowpeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peer,
25946          "Show SIP peer (text format)", mandescr_show_peer);
25947    ast_manager_register2("SIPqualifypeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_qualify_peer,
25948          "Show SIP peer (text format)", mandescr_show_peer);   /*! \todo Fix this XXX This must be all wrong XXXX */
25949    ast_manager_register2("SIPshowregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_show_registry,
25950          "Show SIP registrations (text format)", mandescr_show_registry);
25951    ast_manager_register2("SIPnotify", EVENT_FLAG_SYSTEM, manager_sipnotify,
25952          "Send a SIP notify", mandescr_sipnotify);
25953    sip_poke_all_peers();   
25954    sip_send_all_registers();
25955    sip_send_all_mwi_subscriptions();
25956 
25957    /* And start the monitor for the first time */
25958    restart_monitor();
25959 
25960    ast_realtime_require_field(ast_check_realtime("sipregs") ? "sipregs" : "sippeers",
25961       "name", RQ_CHAR, 10,
25962       "ipaddr", RQ_CHAR, 15,
25963       "port", RQ_UINTEGER2, 5,
25964       "regseconds", RQ_INTEGER4, 11,
25965       "defaultuser", RQ_CHAR, 10,
25966       "fullcontact", RQ_CHAR, 35,
25967       "regserver", RQ_CHAR, 20,
25968       "useragent", RQ_CHAR, 20,
25969       "lastms", RQ_INTEGER4, 11,
25970       SENTINEL);
25971 
25972    return AST_MODULE_LOAD_SUCCESS;
25973 }
25974 
25975 /*! \brief PBX unload module API */
25976 static int unload_module(void)
25977 {
25978    struct sip_pvt *p;
25979    struct sip_threadinfo *th;
25980    struct ast_context *con;
25981    struct ao2_iterator i;
25982 
25983    ast_sched_dump(sched);
25984    
25985    /* First, take us out of the channel type list */
25986    ast_channel_unregister(&sip_tech);
25987 
25988    /* Unregister dial plan functions */
25989    ast_custom_function_unregister(&sipchaninfo_function);
25990    ast_custom_function_unregister(&sippeer_function);
25991    ast_custom_function_unregister(&sip_header_function);
25992    ast_custom_function_unregister(&checksipdomain_function);
25993 
25994    /* Unregister dial plan applications */
25995    ast_unregister_application(app_dtmfmode);
25996    ast_unregister_application(app_sipaddheader);
25997    ast_unregister_application(app_sipremoveheader);
25998 
25999    /* Unregister CLI commands */
26000    ast_cli_unregister_multiple(cli_sip, ARRAY_LEN(cli_sip));
26001 
26002    /* Disconnect from the RTP subsystem */
26003    ast_rtp_proto_unregister(&sip_rtp);
26004 
26005    /* Disconnect from UDPTL */
26006    ast_udptl_proto_unregister(&sip_udptl);
26007 
26008    /* Unregister AMI actions */
26009    ast_manager_unregister("SIPpeers");
26010    ast_manager_unregister("SIPshowpeer");
26011    ast_manager_unregister("SIPqualifypeer");
26012    ast_manager_unregister("SIPshowregistry");
26013    ast_manager_unregister("SIPnotify");
26014    
26015    /* Kill TCP/TLS server threads */
26016    if (sip_tcp_desc.master)
26017       ast_tcptls_server_stop(&sip_tcp_desc);
26018    if (sip_tls_desc.master)
26019       ast_tcptls_server_stop(&sip_tls_desc);
26020 
26021    /* Kill all existing TCP/TLS threads */
26022    i = ao2_iterator_init(threadt, 0);
26023    while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
26024       pthread_t thread = th->threadid;
26025       th->stop = 1;
26026       pthread_kill(thread, SIGURG);
26027       pthread_join(thread, NULL);
26028       ao2_t_ref(th, -1, "decrement ref from iterator");
26029    }
26030    ao2_iterator_destroy(&i);
26031 
26032    /* Hangup all dialogs if they have an owner */
26033    i = ao2_iterator_init(dialogs, 0);
26034    while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
26035       if (p->owner)
26036          ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
26037       ao2_t_ref(p, -1, "toss dialog ptr from iterator_next");
26038    }
26039    ao2_iterator_destroy(&i);
26040 
26041    ast_mutex_lock(&monlock);
26042    if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
26043       pthread_cancel(monitor_thread);
26044       pthread_kill(monitor_thread, SIGURG);
26045       pthread_join(monitor_thread, NULL);
26046    }
26047    monitor_thread = AST_PTHREADT_STOP;
26048    ast_mutex_unlock(&monlock);
26049 
26050    /* Destroy all the dialogs and free their memory */
26051    i = ao2_iterator_init(dialogs, 0);
26052    while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
26053       dialog_unlink_all(p, TRUE, TRUE);
26054       ao2_t_ref(p, -1, "throw away iterator result"); 
26055    }
26056    ao2_iterator_destroy(&i);
26057 
26058    /* Free memory for local network address mask */
26059    ast_free_ha(localaddr);
26060 
26061    clear_realm_authentication(authl);
26062 
26063 
26064    if (default_tls_cfg.certfile)
26065       ast_free(default_tls_cfg.certfile);
26066    if (default_tls_cfg.cipher)
26067       ast_free(default_tls_cfg.cipher);
26068    if (default_tls_cfg.cafile)
26069       ast_free(default_tls_cfg.cafile);
26070    if (default_tls_cfg.capath)
26071       ast_free(default_tls_cfg.capath);
26072 
26073    ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
26074    ASTOBJ_CONTAINER_DESTROY(&regl);
26075    ASTOBJ_CONTAINER_DESTROYALL(&submwil, sip_subscribe_mwi_destroy);
26076    ASTOBJ_CONTAINER_DESTROY(&submwil);
26077 
26078    ao2_t_ref(peers, -1, "unref the peers table");
26079    ao2_t_ref(peers_by_ip, -1, "unref the peers_by_ip table");
26080    ao2_t_ref(dialogs, -1, "unref the dialogs table");
26081    ao2_t_ref(threadt, -1, "unref the thread table");
26082 
26083    clear_sip_domains();
26084    ast_free_ha(global_contact_ha);
26085    close(sipsock);
26086    sched_context_destroy(sched);
26087    con = ast_context_find(used_context);
26088    if (con)
26089       ast_context_destroy(con, "SIP");
26090    ast_unload_realtime("sipregs");
26091    ast_unload_realtime("sippeers");
26092 
26093    return 0;
26094 }
26095 
26096 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Session Initiation Protocol (SIP)",
26097       .load = load_module,
26098       .unload = unload_module,
26099       .reload = reload,
26100           );

Generated on Wed Aug 11 01:05:09 2010 for Asterisk - the Open Source PBX by  doxygen 1.5.9