Wed Mar 2 18:53:20 2011

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: 301682 $")
00211 
00212 #include <ctype.h>
00213 #include <sys/ioctl.h>
00214 #include <fcntl.h>
00215 #include <signal.h>
00216 #include <sys/signal.h>
00217 #include <regex.h>
00218 #include <time.h>
00219 
00220 #include "asterisk/network.h"
00221 #include "asterisk/paths.h"   /* need ast_config_AST_SYSTEM_NAME */
00222 
00223 #include "asterisk/lock.h"
00224 #include "asterisk/channel.h"
00225 #include "asterisk/config.h"
00226 #include "asterisk/module.h"
00227 #include "asterisk/pbx.h"
00228 #include "asterisk/sched.h"
00229 #include "asterisk/io.h"
00230 #include "asterisk/rtp.h"
00231 #include "asterisk/udptl.h"
00232 #include "asterisk/acl.h"
00233 #include "asterisk/manager.h"
00234 #include "asterisk/callerid.h"
00235 #include "asterisk/cli.h"
00236 #include "asterisk/app.h"
00237 #include "asterisk/musiconhold.h"
00238 #include "asterisk/dsp.h"
00239 #include "asterisk/features.h"
00240 #include "asterisk/srv.h"
00241 #include "asterisk/astdb.h"
00242 #include "asterisk/causes.h"
00243 #include "asterisk/utils.h"
00244 #include "asterisk/file.h"
00245 #include "asterisk/astobj.h"
00246 /* 
00247    Uncomment the define below,  if you are having refcount related memory leaks.
00248    With this uncommented, this module will generate a file, /tmp/refs, which contains
00249    a history of the ao2_ref() calls. To be useful, all calls to ao2_* functions should
00250    be modified to ao2_t_* calls, and include a tag describing what is happening with 
00251    enough detail, to make pairing up a reference count increment with its corresponding decrement.
00252    The refcounter program in utils/ can be invaluable in highlighting objects that are not
00253    balanced, along with the complete history for that object.
00254    In normal operation, the macros defined will throw away the tags, so they do not 
00255    affect the speed of the program at all. They can be considered to be documentation.
00256 */
00257 /* #define  REF_DEBUG 1 */
00258 #include "asterisk/astobj2.h"
00259 #include "asterisk/dnsmgr.h"
00260 #include "asterisk/devicestate.h"
00261 #include "asterisk/linkedlists.h"
00262 #include "asterisk/stringfields.h"
00263 #include "asterisk/monitor.h"
00264 #include "asterisk/netsock.h"
00265 #include "asterisk/localtime.h"
00266 #include "asterisk/abstract_jb.h"
00267 #include "asterisk/threadstorage.h"
00268 #include "asterisk/translate.h"
00269 #include "asterisk/ast_version.h"
00270 #include "asterisk/event.h"
00271 #include "asterisk/tcptls.h"
00272 #include "asterisk/strings.h"
00273 
00274 /*** DOCUMENTATION
00275    <application name="SIPDtmfMode" language="en_US">
00276       <synopsis>
00277          Change the dtmfmode for a SIP call.
00278       </synopsis>
00279       <syntax>
00280          <parameter name="mode" required="true">
00281             <enumlist>
00282                <enum name="inband" />
00283                <enum name="info" />
00284                <enum name="rfc2833" />
00285             </enumlist>
00286          </parameter>
00287       </syntax>
00288       <description>
00289          <para>Changes the dtmfmode for a SIP call.</para>
00290       </description>
00291    </application>
00292    <application name="SIPAddHeader" language="en_US">
00293       <synopsis>
00294          Add a SIP header to the outbound call.
00295       </synopsis>
00296       <syntax argsep=":">
00297          <parameter name="Header" required="true" />
00298          <parameter name="Content" required="true" />
00299       </syntax>
00300       <description>
00301          <para>Adds a header to a SIP call placed with DIAL.</para>
00302          <para>Remember to use the X-header if you are adding non-standard SIP
00303          headers, like <literal>X-Asterisk-Accountcode:</literal>. Use this with care.
00304          Adding the wrong headers may jeopardize the SIP dialog.</para>
00305          <para>Always returns <literal>0</literal>.</para>
00306       </description>
00307    </application>
00308    <application name="SIPRemoveHeader" language="en_US">
00309       <synopsis>
00310          Remove SIP headers previously added with SIPAddHeader
00311       </synopsis>
00312       <syntax>
00313          <parameter name="Header" required="false" />
00314       </syntax>
00315       <description>
00316          <para>SIPRemoveHeader() allows you to remove headers which were previously 
00317          added with SIPAddHeader(). If no parameter is supplied, all previously added 
00318          headers will be removed. If a parameter is supplied, only the matching headers 
00319          will be removed.</para>
00320          <para>For example you have added these 2 headers:</para>
00321          <para>SIPAddHeader(P-Asserted-Identity: sip:foo@bar);</para>
00322          <para>SIPAddHeader(P-Preferred-Identity: sip:bar@foo);</para>
00323          <para></para>
00324          <para>// remove all headers</para>
00325          <para>SIPRemoveHeader();</para>
00326          <para>// remove all P- headers</para>
00327          <para>SIPRemoveHeader(P-);</para>
00328          <para>// remove only the PAI header (note the : at the end)</para>
00329          <para>SIPRemoveHeader(P-Asserted-Identity:);</para>
00330          <para></para>
00331          <para>Always returns <literal>0</literal>.</para>
00332       </description>
00333    </application>
00334    <function name="SIP_HEADER" language="en_US">
00335       <synopsis>
00336          Gets the specified SIP header.
00337       </synopsis>
00338       <syntax>
00339          <parameter name="name" required="true" />
00340          <parameter name="number">
00341             <para>If not specified, defaults to <literal>1</literal>.</para>
00342          </parameter>
00343       </syntax>
00344       <description>
00345          <para>Since there are several headers (such as Via) which can occur multiple
00346          times, SIP_HEADER takes an optional second argument to specify which header with
00347          that name to retrieve. Headers start at offset <literal>1</literal>.</para>
00348       </description>
00349    </function>
00350    <function name="SIPPEER" language="en_US">
00351       <synopsis>
00352          Gets SIP peer information.
00353       </synopsis>
00354       <syntax>
00355          <parameter name="peername" required="true" />
00356          <parameter name="item">
00357             <enumlist>
00358                <enum name="ip">
00359                   <para>(default) The ip address.</para>
00360                </enum>
00361                <enum name="port">
00362                   <para>The port number.</para>
00363                </enum>
00364                <enum name="mailbox">
00365                   <para>The configured mailbox.</para>
00366                </enum>
00367                <enum name="context">
00368                   <para>The configured context.</para>
00369                </enum>
00370                <enum name="expire">
00371                   <para>The epoch time of the next expire.</para>
00372                </enum>
00373                <enum name="dynamic">
00374                   <para>Is it dynamic? (yes/no).</para>
00375                </enum>
00376                <enum name="callerid_name">
00377                   <para>The configured Caller ID name.</para>
00378                </enum>
00379                <enum name="callerid_num">
00380                   <para>The configured Caller ID number.</para>
00381                </enum>
00382                <enum name="callgroup">
00383                   <para>The configured Callgroup.</para>
00384                </enum>
00385                <enum name="pickupgroup">
00386                   <para>The configured Pickupgroup.</para>
00387                </enum>
00388                <enum name="codecs">
00389                   <para>The configured codecs.</para>
00390                </enum>
00391                <enum name="status">
00392                   <para>Status (if qualify=yes).</para>
00393                </enum>
00394                <enum name="regexten">
00395                   <para>Registration extension.</para>
00396                </enum>
00397                <enum name="limit">
00398                   <para>Call limit (call-limit).</para>
00399                </enum>
00400                <enum name="busylevel">
00401                   <para>Configured call level for signalling busy.</para>
00402                </enum>
00403                <enum name="curcalls">
00404                   <para>Current amount of calls. Only available if call-limit is set.</para>
00405                </enum>
00406                <enum name="language">
00407                   <para>Default language for peer.</para>
00408                </enum>
00409                <enum name="accountcode">
00410                   <para>Account code for this peer.</para>
00411                </enum>
00412                <enum name="useragent">
00413                   <para>Current user agent id for peer.</para>
00414                </enum>
00415                <enum name="chanvar[name]">
00416                   <para>A channel variable configured with setvar for this peer.</para>
00417                </enum>
00418                <enum name="codec[x]">
00419                   <para>Preferred codec index number <replaceable>x</replaceable> (beginning with zero).</para>
00420                </enum>
00421             </enumlist>
00422          </parameter>
00423       </syntax>
00424       <description></description>
00425    </function>
00426    <function name="SIPCHANINFO" language="en_US">
00427       <synopsis>
00428          Gets the specified SIP parameter from the current channel.
00429       </synopsis>
00430       <syntax>
00431          <parameter name="item" required="true">
00432             <enumlist>
00433                <enum name="peerip">
00434                   <para>The IP address of the peer.</para>
00435                </enum>
00436                <enum name="recvip">
00437                   <para>The source IP address of the peer.</para>
00438                </enum>
00439                <enum name="from">
00440                   <para>The URI from the <literal>From:</literal> header.</para>
00441                </enum>
00442                <enum name="uri">
00443                   <para>The URI from the <literal>Contact:</literal> header.</para>
00444                </enum>
00445                <enum name="useragent">
00446                   <para>The useragent.</para>
00447                </enum>
00448                <enum name="peername">
00449                   <para>The name of the peer.</para>
00450                </enum>
00451                <enum name="t38passthrough">
00452                   <para><literal>1</literal> if T38 is offered or enabled in this channel,
00453                   otherwise <literal>0</literal>.</para>
00454                </enum>
00455             </enumlist>
00456          </parameter>
00457       </syntax>
00458       <description></description>
00459    </function>
00460    <function name="CHECKSIPDOMAIN" language="en_US">
00461       <synopsis>
00462          Checks if domain is a local domain.
00463       </synopsis>
00464       <syntax>
00465          <parameter name="domain" required="true" />
00466       </syntax>
00467       <description>
00468          <para>This function checks if the <replaceable>domain</replaceable> in the argument is configured
00469          as a local SIP domain that this Asterisk server is configured to handle.
00470          Returns the domain name if it is locally handled, otherwise an empty string.
00471          Check the <literal>domain=</literal> configuration in <filename>sip.conf</filename>.</para>
00472       </description>
00473    </function>
00474  ***/
00475 
00476 #ifndef FALSE
00477 #define FALSE    0
00478 #endif
00479 
00480 #ifndef TRUE
00481 #define TRUE     1
00482 #endif
00483 
00484 /* Arguments for find_peer */
00485 #define FINDUSERS (1 << 0)
00486 #define FINDPEERS (1 << 1)
00487 #define FINDALLDEVICES (FINDUSERS | FINDPEERS)
00488 
00489 #define  SIPBUFSIZE     512      /*!< Buffer size for many operations */
00490 
00491 #define XMIT_ERROR      -2
00492 
00493 #define SIP_RESERVED ";/?:@&=+$,# "    /*!< Reserved characters in the username part of the URI */
00494 
00495 /* #define VOCAL_DATA_HACK */
00496 
00497 #define DEFAULT_DEFAULT_EXPIRY  120
00498 #define DEFAULT_MIN_EXPIRY      60
00499 #define DEFAULT_MAX_EXPIRY      3600
00500 #define DEFAULT_MWI_EXPIRY      3600
00501 #define DEFAULT_REGISTRATION_TIMEOUT 20
00502 #define DEFAULT_MAX_FORWARDS    "70"
00503 
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 Standard SIP unsecure port for UDP and TCP from RFC 3261. DO NOT CHANGE THIS */
00952 #define STANDARD_SIP_PORT  5060
00953 /*! \brief Standard SIP TLS port from RFC 3261. DO NOT CHANGE THIS */
00954 #define STANDARD_TLS_PORT  5061
00955 
00956 /*! \note in many SIP headers, absence of a port number implies port 5060,
00957  * and this is why we cannot change the above constant.
00958  * There is a limited number of places in asterisk where we could,
00959  * in principle, use a different "default" port number, but
00960  * we do not support this feature at the moment.
00961  * You can run Asterisk with SIP on a different port with a configuration
00962  * option. If you change this value, the signalling will be incorrect.
00963  */
00964 
00965 /*! \name DefaultValues Default values, set and reset in reload_config before reading configuration 
00966 
00967    These are default values in the source. There are other recommended values in the
00968    sip.conf.sample for new installations. These may differ to keep backwards compatibility,
00969    yet encouraging new behaviour on new installations 
00970  */
00971 /*@{*/ 
00972 #define DEFAULT_CONTEXT    "default"   /*!< The default context for [general] section as well as devices */
00973 #define DEFAULT_MOHINTERPRET    "default" /*!< The default music class */
00974 #define DEFAULT_MOHSUGGEST      ""
00975 #define DEFAULT_VMEXTEN    "asterisk"  /*!< Default voicemail extension */
00976 #define DEFAULT_CALLERID   "asterisk"  /*!< Default caller ID */
00977 #define DEFAULT_NOTIFYMIME    "application/simple-message-summary"
00978 #define DEFAULT_ALLOWGUEST TRUE
00979 #define DEFAULT_RTPKEEPALIVE  0     /*!< Default RTPkeepalive setting */
00980 #define DEFAULT_CALLCOUNTER   FALSE
00981 #define DEFAULT_SRVLOOKUP  TRUE     /*!< Recommended setting is ON */
00982 #define DEFAULT_COMPACTHEADERS   FALSE    /*!< Send compact (one-character) SIP headers. Default off */
00983 #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. */
00984 #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. */
00985 #define DEFAULT_TOS_VIDEO       0               /*!< Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions. */
00986 #define DEFAULT_TOS_TEXT        0               /*!< Text packets should be marked as XXXX XXXX, but the default is 0 to be compatible with previous versions. */
00987 #define DEFAULT_COS_SIP         4      /*!< Level 2 class of service for SIP signalling */
00988 #define DEFAULT_COS_AUDIO       5      /*!< Level 2 class of service for audio media  */
00989 #define DEFAULT_COS_VIDEO       6      /*!< Level 2 class of service for video media */
00990 #define DEFAULT_COS_TEXT        5      /*!< Level 2 class of service for text media (T.140) */
00991 #define DEFAULT_ALLOW_EXT_DOM TRUE     /*!< Allow external domains */
00992 #define DEFAULT_REALM      "asterisk"  /*!< Realm for HTTP digest authentication */
00993 #define DEFAULT_NOTIFYRINGING TRUE     /*!< Notify devicestate system on ringing state */
00994 #define DEFAULT_NOTIFYCID     DISABLED /*!< Include CID with ringing notifications */
00995 #define DEFAULT_PEDANTIC   FALSE    /*!< Avoid following SIP standards for dialog matching */
00996 #define DEFAULT_AUTOCREATEPEER   FALSE    /*!< Don't create peers automagically */
00997 #define  DEFAULT_MATCHEXTERNIPLOCALLY FALSE  /*!< Match extern IP locally default setting */
00998 #define DEFAULT_QUALIFY    FALSE    /*!< Don't monitor devices */
00999 #define DEFAULT_CALLEVENTS FALSE    /*!< Extra manager SIP call events */
01000 #define DEFAULT_ALWAYSAUTHREJECT FALSE /*!< Don't reject authentication requests always */
01001 #define DEFAULT_REGEXTENONQUALIFY FALSE
01002 #define DEFAULT_T1MIN      100      /*!< 100 MS for minimal roundtrip time */
01003 #define DEFAULT_MAX_CALL_BITRATE (384)    /*!< Max bitrate for video */
01004 #ifndef DEFAULT_USERAGENT
01005 #define DEFAULT_USERAGENT "Asterisk PBX"  /*!< Default Useragent: header unless re-defined in sip.conf */
01006 #define DEFAULT_SDPSESSION "Asterisk PBX" /*!< Default SDP session name, (s=) header unless re-defined in sip.conf */
01007 #define DEFAULT_SDPOWNER "root"        /*!< Default SDP username field in (o=) header unless re-defined in sip.conf */
01008 #endif
01009 /*@}*/ 
01010 
01011 /*! \name DefaultSettings
01012    Default setttings are used as a channel setting and as a default when
01013    configuring devices 
01014 */
01015 /*@{*/ 
01016 static char default_language[MAX_LANGUAGE];
01017 static char default_callerid[AST_MAX_EXTENSION];
01018 static char default_fromdomain[AST_MAX_EXTENSION];
01019 static char default_notifymime[AST_MAX_EXTENSION];
01020 static int default_qualify;      /*!< Default Qualify= setting */
01021 static char default_vmexten[AST_MAX_EXTENSION];
01022 static char default_mohinterpret[MAX_MUSICCLASS];  /*!< Global setting for moh class to use when put on hold */
01023 static char default_mohsuggest[MAX_MUSICCLASS];    /*!< Global setting for moh class to suggest when putting 
01024                                                     *   a bridged channel on hold */
01025 static char default_parkinglot[AST_MAX_CONTEXT]; /*!< Parkinglot */
01026 static int default_maxcallbitrate;  /*!< Maximum bitrate for call */
01027 static struct ast_codec_pref default_prefs;     /*!< Default codec prefs */
01028 static unsigned int default_transports;         /*!< Default Transports (enum sip_transport) that are acceptable */
01029 static unsigned int default_primary_transport;     /*!< Default primary Transport (enum sip_transport) for outbound connections to devices */
01030 
01031 /*@}*/ 
01032 
01033 /*! \name GlobalSettings
01034    Global settings apply to the channel (often settings you can change in the general section
01035    of sip.conf
01036 */
01037 /*@{*/ 
01038 /*! \brief a place to store all global settings for the sip channel driver 
01039    These are settings that will be possibly to apply on a group level later on.
01040    \note Do not add settings that only apply to the channel itself and can't
01041          be applied to devices (trunks, services, phones)
01042 */
01043 struct sip_settings {
01044    int peer_rtupdate;      /*!< G: Update database with registration data for peer? */
01045    int rtsave_sysname;     /*!< G: Save system name at registration? */
01046    int ignore_regexpire;      /*!< G: Ignore expiration of peer  */
01047    int rtautoclear;     /*!< Realtime ?? */
01048    int directrtpsetup;     /*!< Enable support for Direct RTP setup (no re-invites) */
01049    int pedanticsipchecking;   /*!< Extra checking ?  Default off */
01050    int autocreatepeer;     /*!< Auto creation of peers at registration? Default off. */
01051    int srvlookup;       /*!< SRV Lookup on or off. Default is on */
01052    int allowguest;         /*!< allow unauthenticated peers to connect? */
01053    int alwaysauthreject;      /*!< Send 401 Unauthorized for all failing requests */
01054    int compactheaders;     /*!< send compact sip headers */
01055    int allow_external_domains;   /*!< Accept calls to external SIP domains? */
01056    int callevents;         /*!< Whether we send manager events or not */
01057    int regextenonqualify;     /*!< Whether to add/remove regexten when qualifying peers */
01058    int matchexterniplocally;  /*!< Match externip/externhost setting against localnet setting */
01059    int notifyringing;      /*!< Send notifications on ringing */
01060    int notifyhold;         /*!< Send notifications on hold */
01061    enum notifycid_setting notifycid; /*!< Send CID with ringing notifications */
01062    enum transfermodes allowtransfer;   /*!< SIP Refer restriction scheme */
01063    int allowsubscribe;          /*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE 
01064                    the global setting is in globals_flags[1] */
01065    char realm[MAXHOSTNAMELEN];      /*!< Default realm */
01066    struct sip_proxy outboundproxy;  /*!< Outbound proxy */
01067    char default_context[AST_MAX_CONTEXT];
01068    char default_subscribecontext[AST_MAX_CONTEXT];
01069 };
01070 
01071 static struct sip_settings sip_cfg;
01072 
01073 static int global_match_auth_username;    /*!< Match auth username if available instead of From: Default off. */
01074 
01075 static int global_relaxdtmf;     /*!< Relax DTMF */
01076 static int global_prematuremediafilter;   /*!< Enable/disable premature frames in a call (causing 183 early media) */
01077 static int global_relaxdtmf;        /*!< Relax DTMF */
01078 static int global_rtptimeout;    /*!< Time out call if no RTP */
01079 static int global_rtpholdtimeout;   /*!< Time out call if no RTP during hold */
01080 static int global_rtpkeepalive;     /*!< Send RTP keepalives */
01081 static int global_reg_timeout;
01082 static int global_regattempts_max;  /*!< Registration attempts before giving up */
01083 static int global_shrinkcallerid;   /*!< enable or disable shrinking of caller id  */
01084 static int global_callcounter;      /*!< Enable call counters for all devices. This is currently enabled by setting the peer
01085                   call-limit to INT_MAX. When we remove the call-limit from the code, we can make it
01086                   with just a boolean flag in the device structure */
01087 static unsigned int global_tos_sip;    /*!< IP type of service for SIP packets */
01088 static unsigned int global_tos_audio;     /*!< IP type of service for audio RTP packets */
01089 static unsigned int global_tos_video;     /*!< IP type of service for video RTP packets */
01090 static unsigned int global_tos_text;      /*!< IP type of service for text RTP packets */
01091 static unsigned int global_cos_sip;    /*!< 802.1p class of service for SIP packets */
01092 static unsigned int global_cos_audio;     /*!< 802.1p class of service for audio RTP packets */
01093 static unsigned int global_cos_video;     /*!< 802.1p class of service for video RTP packets */
01094 static unsigned int global_cos_text;      /*!< 802.1p class of service for text RTP packets */
01095 static int recordhistory;     /*!< Record SIP history. Off by default */
01096 static int dumphistory;       /*!< Dump history to verbose before destroying SIP dialog */
01097 static char global_regcontext[AST_MAX_CONTEXT];    /*!< Context for auto-extensions */
01098 static char global_useragent[AST_MAX_EXTENSION];   /*!< Useragent for the SIP channel */
01099 static char global_sdpsession[AST_MAX_EXTENSION];  /*!< SDP session name for the SIP channel */
01100 static char global_sdpowner[AST_MAX_EXTENSION]; /*!< SDP owner name for the SIP channel */
01101 static int global_authfailureevents;      /*!< Whether we send authentication failure manager events or not. Default no. */
01102 static int global_t1;         /*!< T1 time */
01103 static int global_t1min;      /*!< T1 roundtrip time minimum */
01104 static int global_timer_b;             /*!< Timer B - RFC 3261 Section 17.1.1.2 */
01105 static int global_autoframing;            /*!< Turn autoframing on or off. */
01106 static int global_qualifyfreq;         /*!< Qualify frequency */
01107 static int global_qualify_gap;              /*!< Time between our group of peer pokes */
01108 static int global_qualify_peers;          /*!< Number of peers to poke at a given time */
01109 
01110 
01111 /*! \brief Codecs that we support by default: */
01112 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
01113 
01114 static enum st_mode global_st_mode;           /*!< Mode of operation for Session-Timers           */
01115 static enum st_refresher global_st_refresher; /*!< Session-Timer refresher                        */
01116 static int global_min_se;                     /*!< Lowest threshold for session refresh interval  */
01117 static int global_max_se;                     /*!< Highest threshold for session refresh interval */
01118 
01119 static int global_dynamic_exclude_static = 0;   /*!< Exclude static peers from contact registrations */
01120 /*@}*/
01121 
01122 /*! \brief Global list of addresses dynamic peers are not allowed to use */
01123 static struct ast_ha *global_contact_ha = NULL;
01124 
01125 /*! \name Object counters @{
01126  * \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
01127  * should be used to modify these values. */
01128 static int speerobjs = 0;                /*!< Static peers */
01129 static int rpeerobjs = 0;                /*!< Realtime peers */
01130 static int apeerobjs = 0;                /*!< Autocreated peer objects */
01131 static int regobjs = 0;                  /*!< Registry objects */
01132 /* }@ */
01133 
01134 static struct ast_flags global_flags[2] = {{0}};        /*!< global SIP_ flags */
01135 static int global_t38_maxdatagram;        /*!< global T.38 FaxMaxDatagram override */
01136 
01137 static char used_context[AST_MAX_CONTEXT];      /*!< name of automatically created context for unloading */
01138 
01139 
01140 AST_MUTEX_DEFINE_STATIC(netlock);
01141 
01142 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
01143    when it's doing something critical. */
01144 AST_MUTEX_DEFINE_STATIC(monlock);
01145 
01146 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
01147 
01148 /*! \brief This is the thread for the monitor which checks for input on the channels
01149    which are not currently in use.  */
01150 static pthread_t monitor_thread = AST_PTHREADT_NULL;
01151 
01152 static int sip_reloading = FALSE;                       /*!< Flag for avoiding multiple reloads at the same time */
01153 static enum channelreloadreason sip_reloadreason;       /*!< Reason for last reload/load of configuration */
01154 
01155 static struct sched_context *sched;     /*!< The scheduling context */
01156 static struct io_context *io;           /*!< The IO context */
01157 static int *sipsock_read_id;            /*!< ID of IO entry for sipsock FD */
01158 
01159 #define DEC_CALL_LIMIT  0
01160 #define INC_CALL_LIMIT  1
01161 #define DEC_CALL_RINGING 2
01162 #define INC_CALL_RINGING 3
01163 
01164 /*! \brief The SIP socket definition */
01165 struct sip_socket {
01166    enum sip_transport type;   /*!< UDP, TCP or TLS */
01167    int fd;           /*!< Filed descriptor, the actual socket */
01168    uint16_t port;
01169    struct ast_tcptls_session_instance *tcptls_session;   /* If tcp or tls, a socket manager */
01170 };
01171 
01172 /*! \brief sip_request: The data grabbed from the UDP socket
01173  *
01174  * \verbatim
01175  * Incoming messages: we first store the data from the socket in data[],
01176  * adding a trailing \0 to make string parsing routines happy.
01177  * Then call parse_request() and req.method = find_sip_method();
01178  * to initialize the other fields. The \r\n at the end of each line is   
01179  * replaced by \0, so that data[] is not a conforming SIP message anymore.
01180  * After this processing, rlPart1 is set to non-NULL to remember
01181  * that we can run get_header() on this kind of packet.
01182  *
01183  * parse_request() splits the first line as follows:
01184  * Requests have in the first line      method uri SIP/2.0
01185  *      rlPart1 = method; rlPart2 = uri;
01186  * Responses have in the first line     SIP/2.0 NNN description
01187  *      rlPart1 = SIP/2.0; rlPart2 = NNN + description;
01188  *
01189  * For outgoing packets, we initialize the fields with init_req() or init_resp()
01190  * (which fills the first line to "METHOD uri SIP/2.0" or "SIP/2.0 code text"),
01191  * and then fill the rest with add_header() and add_content().
01192  * The \r\n at the end of the line are still there, so the get_header()
01193  * and similar functions don't work on these packets. 
01194  * \endverbatim
01195  */
01196 struct sip_request {
01197    ptrdiff_t rlPart1;           /*!< Offset of the SIP Method Name or "SIP/2.0" protocol version */
01198    ptrdiff_t rlPart2;           /*!< Offset of the Request URI or Response Status */
01199    int len;                /*!< bytes used in data[], excluding trailing null terminator. Rarely used. */
01200    int headers;            /*!< # of SIP Headers */
01201    int method;             /*!< Method of this request */
01202    int lines;              /*!< Body Content */
01203    unsigned int sdp_start; /*!< the line number where the SDP begins */
01204    unsigned int sdp_count; /*!< the number of lines of SDP */
01205    char debug;    /*!< print extra debugging if non zero */
01206    char has_to_tag;  /*!< non-zero if packet has To: tag */
01207    char ignore;      /*!< if non-zero This is a re-transmit, ignore it */
01208    /* Array of offsets into the request string of each SIP header*/
01209    ptrdiff_t header[SIP_MAX_HEADERS];
01210    /* Array of offsets into the request string of each SDP line*/
01211    ptrdiff_t line[SIP_MAX_LINES];
01212    struct ast_str *data;   
01213    struct ast_str *content;
01214    /* XXX Do we need to unref socket.ser when the request goes away? */
01215    struct sip_socket socket;  /*!< The socket used for this request */
01216    AST_LIST_ENTRY(sip_request) next;
01217 };
01218 
01219 /* \brief given a sip_request and an offset, return the char * that resides there
01220  *
01221  * It used to be that rlPart1, rlPart2, and the header and line arrays were character
01222  * pointers. They are now offsets into the ast_str portion of the sip_request structure.
01223  * To avoid adding a bunch of redundant pointer arithmetic to the code, this macro is
01224  * provided to retrieve the string at a particular offset within the request's buffer
01225  */
01226 #define REQ_OFFSET_TO_STR(req,offset) (ast_str_buffer((req)->data) + ((req)->offset))
01227 
01228 /*! \brief structure used in transfers */
01229 struct sip_dual {
01230    struct ast_channel *chan1; /*!< First channel involved */
01231    struct ast_channel *chan2; /*!< Second channel involved */
01232    struct sip_request req;    /*!< Request that caused the transfer (REFER) */
01233    int seqno;        /*!< Sequence number */
01234 };
01235 
01236 struct sip_pkt;
01237 
01238 /*! \brief Parameters to the transmit_invite function */
01239 struct sip_invite_param {
01240    int addsipheaders;      /*!< Add extra SIP headers */
01241    const char *uri_options;   /*!< URI options to add to the URI */
01242    const char *vxml_url;      /*!< VXML url for Cisco phones */
01243    char *auth;       /*!< Authentication */
01244    char *authheader;    /*!< Auth header */
01245    enum sip_auth_type auth_type; /*!< Authentication type */
01246    const char *replaces;      /*!< Replaces header for call transfers */
01247    int transfer;        /*!< Flag - is this Invite part of a SIP transfer? (invite/replaces) */
01248 };
01249 
01250 /*! \brief Structure to save routing information for a SIP session */
01251 struct sip_route {
01252    struct sip_route *next;
01253    char hop[0];
01254 };
01255 
01256 /*! \brief Modes for SIP domain handling in the PBX */
01257 enum domain_mode {
01258    SIP_DOMAIN_AUTO,     /*!< This domain is auto-configured */
01259    SIP_DOMAIN_CONFIG,      /*!< This domain is from configuration */
01260 };
01261 
01262 /*! \brief Domain data structure. 
01263    \note In the future, we will connect this to a configuration tree specific
01264    for this domain
01265 */
01266 struct domain {
01267    char domain[MAXHOSTNAMELEN];     /*!< SIP domain we are responsible for */
01268    char context[AST_MAX_EXTENSION]; /*!< Incoming context for this domain */
01269    enum domain_mode mode;        /*!< How did we find this domain? */
01270    AST_LIST_ENTRY(domain) list;     /*!< List mechanics */
01271 };
01272 
01273 static AST_LIST_HEAD_STATIC(domain_list, domain);  /*!< The SIP domain list */
01274 
01275 
01276 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
01277 struct sip_history {
01278    AST_LIST_ENTRY(sip_history) list;
01279    char event[0]; /* actually more, depending on needs */
01280 };
01281 
01282 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
01283 
01284 /*! \brief sip_auth: Credentials for authentication to other SIP services */
01285 struct sip_auth {
01286    char realm[AST_MAX_EXTENSION];  /*!< Realm in which these credentials are valid */
01287    char username[256];             /*!< Username */
01288    char secret[256];               /*!< Secret */
01289    char md5secret[256];            /*!< MD5Secret */
01290    struct sip_auth *next;          /*!< Next auth structure in list */
01291 };
01292 
01293 /*! \name SIPflags
01294    Various flags for the flags field in the pvt structure 
01295    Trying to sort these up (one or more of the following):
01296    D: Dialog
01297    P: Peer/user
01298    G: Global flag
01299    When flags are used by multiple structures, it is important that
01300    they have a common layout so it is easy to copy them.
01301 */
01302 /*@{*/ 
01303 #define SIP_OUTGOING    (1 << 0) /*!< D: Direction of the last transaction in this dialog */
01304 #define SIP_RINGING     (1 << 2) /*!< D: Have sent 180 ringing */
01305 #define SIP_PROGRESS_SENT  (1 << 3) /*!< D: Have sent 183 message progress */
01306 #define SIP_NEEDREINVITE   (1 << 4) /*!< D: Do we need to send another reinvite? */
01307 #define SIP_PENDINGBYE     (1 << 5) /*!< D: Need to send bye after we ack? */
01308 #define SIP_GOTREFER    (1 << 6) /*!< D: Got a refer? */
01309 #define SIP_CALL_LIMIT     (1 << 7) /*!< D: Call limit enforced for this call */
01310 #define SIP_INC_COUNT      (1 << 8) /*!< D: Did this dialog increment the counter of in-use calls? */
01311 #define SIP_INC_RINGING    (1 << 9) /*!< D: Did this connection increment the counter of in-use calls? */
01312 #define SIP_DEFER_BYE_ON_TRANSFER   (1 << 10)   /*!< D: Do not hangup at first ast_hangup */
01313 
01314 #define SIP_PROMISCREDIR   (1 << 11)   /*!< DP: Promiscuous redirection */
01315 #define SIP_TRUSTRPID      (1 << 12)   /*!< DP: Trust RPID headers? */
01316 #define SIP_USEREQPHONE    (1 << 13)   /*!< DP: Add user=phone to numeric URI. Default off */
01317 #define SIP_USECLIENTCODE  (1 << 14)   /*!< DP: Trust X-ClientCode info message */
01318 
01319 /* DTMF flags - see str2dtmfmode() and dtmfmode2str() */
01320 #define SIP_DTMF     (7 << 15)   /*!< DP: DTMF Support: five settings, uses three bits */
01321 #define SIP_DTMF_RFC2833   (0 << 15)   /*!< DP: DTMF Support: RTP DTMF - "rfc2833" */
01322 #define SIP_DTMF_INBAND    (1 << 15)   /*!< DP: DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
01323 #define SIP_DTMF_INFO      (2 << 15)   /*!< DP: DTMF Support: SIP Info messages - "info" */
01324 #define SIP_DTMF_AUTO      (3 << 15)   /*!< DP: DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
01325 #define SIP_DTMF_SHORTINFO      (4 << 15)       /*!< DP: DTMF Support: SIP Info messages - "info" - short variant */
01326 
01327 /* NAT settings - see nat2str() */
01328 #define SIP_NAT         (3 << 18)   /*!< DP: four settings, uses two bits */
01329 #define SIP_NAT_NEVER      (0 << 18)   /*!< DP: No nat support */
01330 #define SIP_NAT_RFC3581    (1 << 18)   /*!< DP: NAT RFC3581 */
01331 #define SIP_NAT_ROUTE      (2 << 18)   /*!< DP: NAT Only ROUTE */
01332 #define SIP_NAT_ALWAYS     (3 << 18)   /*!< DP: NAT Both ROUTE and RFC3581 */
01333 
01334 /* re-INVITE related settings */
01335 #define SIP_REINVITE    (7 << 20)   /*!< DP: four settings, uses three bits */
01336 #define SIP_REINVITE_NONE  (0 << 20)   /*!< DP: no reinvite allowed */
01337 #define SIP_DIRECT_MEDIA   (1 << 20)   /*!< DP: allow peers to be reinvited to send media directly p2p */
01338 #define SIP_DIRECT_MEDIA_NAT  (2 << 20)   /*!< DP: allow media reinvite when new peer is behind NAT */
01339 #define SIP_REINVITE_UPDATE   (4 << 20)   /*!< DP: use UPDATE (RFC3311) when reinviting this peer */
01340 
01341 /* "insecure" settings - see insecure2str() */
01342 #define SIP_INSECURE    (3 << 23)   /*!< DP: three settings, uses two bits */
01343 #define SIP_INSECURE_NONE  (0 << 23)   /*!< DP: secure mode */
01344 #define SIP_INSECURE_PORT  (1 << 23)   /*!< DP: don't require matching port for incoming requests */
01345 #define SIP_INSECURE_INVITE   (1 << 24)   /*!< DP: don't require authentication for incoming INVITEs */
01346 
01347 /* Sending PROGRESS in-band settings */
01348 #define SIP_PROG_INBAND    (3 << 25)   /*!< DP: three settings, uses two bits */
01349 #define SIP_PROG_INBAND_NEVER (0 << 25)
01350 #define SIP_PROG_INBAND_NO (1 << 25)
01351 #define SIP_PROG_INBAND_YES   (2 << 25)
01352 
01353 #define SIP_SENDRPID    (1 << 29)   /*!< DP: Remote Party-ID Support */
01354 #define SIP_G726_NONSTANDARD  (1 << 31)   /*!< DP: Use non-standard packing for G726-32 data */
01355 
01356 /*! \brief Flags to copy from peer/user to dialog */
01357 #define SIP_FLAGS_TO_COPY \
01358    (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
01359     SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
01360     SIP_USEREQPHONE | SIP_INSECURE)
01361 /*@}*/ 
01362 
01363 /*! \name SIPflags2
01364    a second page of flags (for flags[1] */
01365 /*@{*/ 
01366 /* realtime flags */
01367 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0) /*!< GP: Should we keep RT objects in memory for extended time? */
01368 #define SIP_PAGE2_RTAUTOCLEAR    (1 << 2) /*!< GP: Should we clean memory from peers after expiry? */
01369 #define SIP_PAGE2_HAVEPEERCONTEXT   (1 << 3) /*< Are we associated with a configured peer context? */
01370 /* Space for addition of other realtime flags in the future */
01371 #define SIP_PAGE2_FORWARD_LOOP_DETECTED (1 << 8)/*!< 31: Do call forward when receiving 482 Loop Detected */
01372 #define SIP_PAGE2_STATECHANGEQUEUE  (1 << 9) /*!< D: Unsent state pending change exists */
01373 
01374 #define SIP_PAGE2_RPORT_PRESENT         (1 << 10)       /*!< Was rport received in the Via header? */
01375 #define SIP_PAGE2_VIDEOSUPPORT      (1 << 14)   /*!< DP: Video supported if offered? */
01376 #define SIP_PAGE2_TEXTSUPPORT    (1 << 15)   /*!< GDP: Global text enable */
01377 #define SIP_PAGE2_ALLOWSUBSCRIBE (1 << 16)   /*!< GP: Allow subscriptions from this peer? */
01378 #define SIP_PAGE2_ALLOWOVERLAP      (1 << 17)   /*!< DP: Allow overlap dialing ? */
01379 #define SIP_PAGE2_SUBSCRIBEMWIONLY  (1 << 18)   /*!< GP: Only issue MWI notification if subscribed to */
01380 #define SIP_PAGE2_IGNORESDPVERSION  (1 << 19)   /*!< GDP: Ignore the SDP session version number we receive and treat all sessions as new */
01381 
01382 #define SIP_PAGE2_T38SUPPORT             (3 << 20) /*!< GDP: T.38 Fax Support */
01383 #define SIP_PAGE2_T38SUPPORT_UDPTL          (1 << 20) /*!< GDP: T.38 Fax Support (no error correction) */
01384 #define SIP_PAGE2_T38SUPPORT_UDPTL_FEC         (2 << 20) /*!< GDP: T.38 Fax Support (FEC error correction) */
01385 #define SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY   (3 << 20)   /*!< GDP: T.38 Fax Support (redundancy error correction) */
01386 
01387 #define SIP_PAGE2_CALL_ONHOLD    (3 << 23)   /*!< D: Call hold states: */
01388 #define SIP_PAGE2_CALL_ONHOLD_ACTIVE    (1 << 23)       /*!< D: Active hold */
01389 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR   (2 << 23)   /*!< D: One directional hold */
01390 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE (3 << 23)   /*!< D: Inactive hold */
01391 
01392 #define SIP_PAGE2_RFC2833_COMPENSATE    (1 << 25)  /*!< DP: Compensate for buggy RFC2833 implementations */
01393 #define SIP_PAGE2_BUGGY_MWI      (1 << 26)   /*!< DP: Buggy CISCO MWI fix */
01394 #define SIP_PAGE2_DIALOG_ESTABLISHED    (1 << 27)       /*!< 29: Has a dialog been established? */
01395 #define SIP_PAGE2_FAX_DETECT     (3 << 28)   /*!< DP: Fax Detection support */
01396 #define SIP_PAGE2_FAX_DETECT_CNG (1 << 28)   /*!< DP: Fax Detection support - detect CNG in audio */
01397 #define SIP_PAGE2_FAX_DETECT_T38 (2 << 28)   /*!< DP: Fax Detection support - detect T.38 reinvite from peer */
01398 #define SIP_PAGE2_FAX_DETECT_BOTH   (3 << 28)   /*!< DP: Fax Detection support - detect both */
01399 #define SIP_PAGE2_REGISTERTRYING        (1 << 29)       /*!< DP: Send 100 Trying on REGISTER attempts */
01400 #define SIP_PAGE2_UDPTL_DESTINATION     (1 << 30)       /*!< DP: Use source IP of RTP as destination if NAT is enabled */
01401 #define SIP_PAGE2_VIDEOSUPPORT_ALWAYS  (1 << 31)       /*!< DP: Always set up video, even if endpoints don't support it */
01402 
01403 #define SIP_PAGE2_FLAGS_TO_COPY \
01404    (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_IGNORESDPVERSION | \
01405    SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | \
01406    SIP_PAGE2_BUGGY_MWI | SIP_PAGE2_TEXTSUPPORT | SIP_PAGE2_FAX_DETECT | \
01407    SIP_PAGE2_UDPTL_DESTINATION | SIP_PAGE2_VIDEOSUPPORT_ALWAYS | \
01408    SIP_PAGE2_HAVEPEERCONTEXT | SIP_PAGE2_FORWARD_LOOP_DETECTED)
01409 
01410 /*@}*/ 
01411 
01412 /*! \brief debugging state
01413  * We store separately the debugging requests from the config file
01414  * and requests from the CLI. Debugging is enabled if either is set
01415  * (which means that if sipdebug is set in the config file, we can
01416  * only turn it off by reloading the config).
01417  */
01418 enum sip_debug_e {
01419    sip_debug_none = 0,
01420    sip_debug_config = 1,
01421    sip_debug_console = 2,
01422 };
01423 
01424 static enum sip_debug_e sipdebug;
01425 
01426 /*! \brief extra debugging for 'text' related events.
01427  * At the moment this is set together with sip_debug_console.
01428  * \note It should either go away or be implemented properly.
01429  */
01430 static int sipdebug_text;
01431 
01432 /*! \brief T38 States for a call */
01433 enum t38state {
01434    T38_DISABLED = 0,                /*!< Not enabled */
01435    T38_LOCAL_REINVITE,              /*!< Offered from local - REINVITE */
01436    T38_PEER_REINVITE,               /*!< Offered from peer - REINVITE */
01437    T38_ENABLED                      /*!< Negotiated (enabled) */
01438 };
01439 
01440 /*! \brief T.38 channel settings (at some point we need to make this alloc'ed */
01441 struct t38properties {
01442    enum t38state state;    /*!< T.38 state */
01443    struct ast_control_t38_parameters our_parms;
01444    struct ast_control_t38_parameters their_parms;
01445 };
01446 
01447 /*! \brief Parameters to know status of transfer */
01448 enum referstatus {
01449    REFER_IDLE,                    /*!< No REFER is in progress */
01450    REFER_SENT,                    /*!< Sent REFER to transferee */
01451    REFER_RECEIVED,                /*!< Received REFER from transferrer */
01452    REFER_CONFIRMED,               /*!< Refer confirmed with a 100 TRYING (unused) */
01453    REFER_ACCEPTED,                /*!< Accepted by transferee */
01454    REFER_RINGING,                 /*!< Target Ringing */
01455    REFER_200OK,                   /*!< Answered by transfer target */
01456    REFER_FAILED,                  /*!< REFER declined - go on */
01457    REFER_NOAUTH                   /*!< We had no auth for REFER */
01458 };
01459 
01460 /*! \brief generic struct to map between strings and integers.
01461  * Fill it with x-s pairs, terminate with an entry with s = NULL;
01462  * Then you can call map_x_s(...) to map an integer to a string,
01463  * and map_s_x() for the string -> integer mapping.
01464  */
01465 struct _map_x_s {
01466    int x;
01467    const char *s;
01468 };              
01469 
01470 static const struct _map_x_s referstatusstrings[] = {
01471    { REFER_IDLE,     "<none>" },
01472    { REFER_SENT,     "Request sent" },
01473    { REFER_RECEIVED, "Request received" },
01474    { REFER_CONFIRMED,   "Confirmed" },
01475    { REFER_ACCEPTED, "Accepted" },
01476    { REFER_RINGING,  "Target ringing" },
01477    { REFER_200OK,    "Done" },
01478    { REFER_FAILED,      "Failed" },
01479    { REFER_NOAUTH,      "Failed - auth failure" },
01480    { -1,       NULL} /* terminator */
01481 };
01482 
01483 /*! \brief Structure to handle SIP transfers. Dynamically allocated when needed
01484    \note OEJ: Should be moved to string fields */
01485 struct sip_refer {
01486    char refer_to[AST_MAX_EXTENSION];      /*!< Place to store REFER-TO extension */
01487    char refer_to_domain[AST_MAX_EXTENSION];  /*!< Place to store REFER-TO domain */
01488    char refer_to_urioption[AST_MAX_EXTENSION];  /*!< Place to store REFER-TO uri options */
01489    char refer_to_context[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO context */
01490    char referred_by[AST_MAX_EXTENSION];      /*!< Place to store REFERRED-BY extension */
01491    char referred_by_name[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
01492    char refer_contact[AST_MAX_EXTENSION];    /*!< Place to store Contact info from a REFER extension */
01493    char replaces_callid[SIPBUFSIZE];         /*!< Replace info: callid */
01494    char replaces_callid_totag[SIPBUFSIZE/2];    /*!< Replace info: to-tag */
01495    char replaces_callid_fromtag[SIPBUFSIZE/2];     /*!< Replace info: from-tag */
01496    struct sip_pvt *refer_call;         /*!< Call we are referring. This is just a reference to a
01497                       * dialog owned by someone else, so we should not destroy
01498                       * it when the sip_refer object goes.
01499                       */
01500    int attendedtransfer;            /*!< Attended or blind transfer? */
01501    int localtransfer;            /*!< Transfer to local domain? */
01502    enum referstatus status;         /*!< REFER status */
01503 };
01504 
01505 
01506 /*! \brief Structure that encapsulates all attributes related to running 
01507  *   SIP Session-Timers feature on a per dialog basis.
01508  */
01509 struct sip_st_dlg {
01510    int st_active;                          /*!< Session-Timers on/off */ 
01511    int st_interval;                        /*!< Session-Timers negotiated session refresh interval */
01512    int st_schedid;                         /*!< Session-Timers ast_sched scheduler id */
01513    enum st_refresher st_ref;               /*!< Session-Timers session refresher */
01514    int st_expirys;                         /*!< Session-Timers number of expirys */
01515    int st_active_peer_ua;                  /*!< Session-Timers on/off in peer UA */
01516    int st_cached_min_se;                   /*!< Session-Timers cached Min-SE */
01517    int st_cached_max_se;                   /*!< Session-Timers cached Session-Expires */
01518    enum st_mode st_cached_mode;            /*!< Session-Timers cached M.O. */
01519    enum st_refresher st_cached_ref;        /*!< Session-Timers cached refresher */
01520    unsigned char quit_flag:1;              /*!< Stop trying to lock; just quit */
01521 };
01522 
01523 
01524 /*! \brief Structure that encapsulates all attributes related to configuration 
01525  *   of SIP Session-Timers feature on a per user/peer basis.
01526  */
01527 struct sip_st_cfg {
01528    enum st_mode st_mode_oper;      /*!< Mode of operation for Session-Timers           */
01529    enum st_refresher st_ref;       /*!< Session-Timer refresher                        */
01530    int st_min_se;                  /*!< Lowest threshold for session refresh interval  */
01531    int st_max_se;                  /*!< Highest threshold for session refresh interval */
01532 };
01533 
01534 struct offered_media {
01535    int offered;
01536    char text[128];
01537 };
01538 
01539 /*! \brief Structure used for each SIP dialog, ie. a call, a registration, a subscribe.
01540  * Created and initialized by sip_alloc(), the descriptor goes into the list of
01541  * descriptors (dialoglist).
01542  */
01543 struct sip_pvt {
01544    struct sip_pvt *next;         /*!< Next dialog in chain */
01545    enum invitestates invitestate;      /*!< Track state of SIP_INVITEs */
01546    int method;          /*!< SIP method that opened this dialog */
01547    AST_DECLARE_STRING_FIELDS(
01548       AST_STRING_FIELD(callid);  /*!< Global CallID */
01549       AST_STRING_FIELD(randdata);   /*!< Random data */
01550       AST_STRING_FIELD(accountcode);   /*!< Account code */
01551       AST_STRING_FIELD(realm);   /*!< Authorization realm */
01552       AST_STRING_FIELD(nonce);   /*!< Authorization nonce */
01553       AST_STRING_FIELD(opaque);  /*!< Opaque nonsense */
01554       AST_STRING_FIELD(qop);     /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
01555       AST_STRING_FIELD(domain);  /*!< Authorization domain */
01556       AST_STRING_FIELD(from);    /*!< The From: header */
01557       AST_STRING_FIELD(useragent);  /*!< User agent in SIP request */
01558       AST_STRING_FIELD(exten);   /*!< Extension where to start */
01559       AST_STRING_FIELD(context); /*!< Context for this call */
01560       AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
01561       AST_STRING_FIELD(subscribeuri); /*!< Subscribecontext */
01562       AST_STRING_FIELD(fromdomain); /*!< Domain to show in the from field */
01563       AST_STRING_FIELD(fromuser);   /*!< User to show in the user field */
01564       AST_STRING_FIELD(fromname);   /*!< Name to show in the user field */
01565       AST_STRING_FIELD(tohost);  /*!< Host we should put in the "to" field */
01566       AST_STRING_FIELD(todnid);  /*!< DNID of this call (overrides host) */
01567       AST_STRING_FIELD(language);   /*!< Default language for this call */
01568       AST_STRING_FIELD(mohinterpret);  /*!< MOH class to use when put on hold */
01569       AST_STRING_FIELD(mohsuggest); /*!< MOH class to suggest when putting a peer on hold */
01570       AST_STRING_FIELD(rdnis);   /*!< Referring DNIS */
01571       AST_STRING_FIELD(redircause); /*!< Referring cause */
01572       AST_STRING_FIELD(theirtag);   /*!< Their tag */
01573       AST_STRING_FIELD(username);   /*!< [user] name */
01574       AST_STRING_FIELD(peername);   /*!< [peer] name, not set if [user] */
01575       AST_STRING_FIELD(authname);   /*!< Who we use for authentication */
01576       AST_STRING_FIELD(uri);     /*!< Original requested URI */
01577       AST_STRING_FIELD(okcontacturi);  /*!< URI from the 200 OK on INVITE */
01578       AST_STRING_FIELD(peersecret); /*!< Password */
01579       AST_STRING_FIELD(peermd5secret);
01580       AST_STRING_FIELD(cid_num); /*!< Caller*ID number */
01581       AST_STRING_FIELD(cid_name);   /*!< Caller*ID name */
01582       AST_STRING_FIELD(fullcontact);   /*!< The Contact: that the UA registers with us */
01583          /* we only store the part in <brackets> in this field. */
01584       AST_STRING_FIELD(our_contact);   /*!< Our contact header */
01585       AST_STRING_FIELD(rpid);    /*!< Our RPID header */
01586       AST_STRING_FIELD(rpid_from);  /*!< Our RPID From header */
01587       AST_STRING_FIELD(url);     /*!< URL to be sent with next message to peer */
01588       AST_STRING_FIELD(parkinglot);    /*!< Parkinglot */
01589    );
01590    char via[128];                          /*!< Via: header */
01591    struct sip_socket socket;     /*!< The socket used for this dialog */
01592    unsigned int ocseq;        /*!< Current outgoing seqno */
01593    unsigned int icseq;        /*!< Current incoming seqno */
01594    ast_group_t callgroup;        /*!< Call group */
01595    ast_group_t pickupgroup;      /*!< Pickup group */
01596    int lastinvite;            /*!< Last Cseq of invite */
01597    struct ast_flags flags[2];    /*!< SIP_ flags */
01598 
01599    /* boolean or small integers that don't belong in flags */
01600    char do_history;        /*!< Set if we want to record history */
01601    char alreadygone;       /*!< already destroyed by our peer */
01602    char needdestroy;       /*!< need to be destroyed by the monitor thread */
01603    char outgoing_call;        /*!< this is an outgoing call */
01604    char answered_elsewhere;      /*!< This call is cancelled due to answer on another channel */
01605    char novideo;           /*!< Didn't get video in invite, don't offer */
01606    char notext;            /*!< Text not supported  (?) */
01607 
01608    int timer_t1;           /*!< SIP timer T1, ms rtt */
01609    int timer_b;                            /*!< SIP timer B, ms */
01610    unsigned int sipoptions;      /*!< Supported SIP options on the other end */
01611    unsigned int reqsipoptions;      /*!< Required SIP options on the other end */
01612    struct ast_codec_pref prefs;     /*!< codec prefs */
01613    int capability;            /*!< Special capability (codec) */
01614    int jointcapability;       /*!< Supported capability at both ends (codecs) */
01615    int peercapability;        /*!< Supported peer capability */
01616    int prefcodec;          /*!< Preferred codec (outbound only) */
01617    int noncodeccapability;       /*!< DTMF RFC2833 telephony-event */
01618    int jointnoncodeccapability;            /*!< Joint Non codec capability */
01619    int redircodecs;        /*!< Redirect codecs */
01620    int maxcallbitrate;        /*!< Maximum Call Bitrate for Video Calls */ 
01621    int t38_maxdatagram;       /*!< T.38 FaxMaxDatagram override */
01622    struct sip_proxy *outboundproxy; /*!< Outbound proxy for this dialog. Use ref_proxy to set this instead of setting it directly*/
01623    struct t38properties t38;     /*!< T38 settings */
01624    struct sockaddr_in udptlredirip; /*!< Where our T.38 UDPTL should be going if not to us */
01625    struct ast_udptl *udptl;      /*!< T.38 UDPTL session */
01626    int callingpres;        /*!< Calling presentation */
01627    int authtries;          /*!< Times we've tried to authenticate */
01628    int expiry;          /*!< How long we take to expire */
01629    long branch;            /*!< The branch identifier of this session */
01630    long invite_branch;        /*!< The branch used when we sent the initial INVITE */
01631    char tag[11];           /*!< Our tag for this session */
01632    int sessionid;          /*!< SDP Session ID */
01633    int sessionversion;        /*!< SDP Session Version */
01634    int64_t sessionversion_remote;      /*!< Remote UA's SDP Session Version */
01635    int session_modify;        /*!< Session modification request true/false  */
01636    unsigned int portinuri:1;     /*!< Non zero if a port has been specified, will also disable srv lookups */
01637    struct sockaddr_in sa;        /*!< Our peer */
01638    struct sockaddr_in redirip;      /*!< Where our RTP should be going if not to us */
01639    struct sockaddr_in vredirip;     /*!< Where our Video RTP should be going if not to us */
01640    struct sockaddr_in tredirip;     /*!< Where our Text RTP should be going if not to us */
01641    time_t lastrtprx;       /*!< Last RTP received */
01642    time_t lastrtptx;       /*!< Last RTP sent */
01643    int rtptimeout;            /*!< RTP timeout time */
01644    struct sockaddr_in recv;      /*!< Received as */
01645    struct sockaddr_in ourip;     /*!< Our IP (as seen from the outside) */
01646    struct ast_channel *owner;    /*!< Who owns us (if we have an owner) */
01647    struct sip_route *route;      /*!< Head of linked list of routing steps (fm Record-Route) */
01648    int route_persistant;         /*!< Is this the "real" route? */
01649    struct ast_variable *notify_headers;    /*!< Custom notify type */
01650    struct sip_auth *peerauth;    /*!< Realm authentication */
01651    int noncecount;            /*!< Nonce-count */
01652    unsigned int stalenonce:1; /*!< Marks the current nonce as responded too */
01653    char lastmsg[256];         /*!< Last Message sent/received */
01654    int amaflags;           /*!< AMA Flags */
01655    int pendinginvite;         /*!< Any pending INVITE or state NOTIFY (in subscribe pvt's) ? (seqno of this) */
01656    int glareinvite;        /*!< A invite received while a pending invite is already present is stored here.  Its seqno is the
01657                   value. Since this glare invite's seqno is not the same as the pending invite's, it must be 
01658                   held in order to properly process acknowledgements for our 491 response. */
01659    struct sip_request initreq;      /*!< Latest request that opened a new transaction
01660                      within this dialog.
01661                      NOT the request that opened the dialog */
01662 
01663    int initid;          /*!< Auto-congest ID if appropriate (scheduler) */
01664    int waitid;          /*!< Wait ID for scheduler after 491 or other delays */
01665    int autokillid;            /*!< Auto-kill ID (scheduler) */
01666    int t38id;                              /*!< T.38 Response ID */
01667    enum transfermodes allowtransfer;   /*!< REFER: restriction scheme */
01668    struct sip_refer *refer;      /*!< REFER: SIP transfer data structure */
01669    enum subscriptiontype subscribed;   /*!< SUBSCRIBE: Is this dialog a subscription?  */
01670    int stateid;            /*!< SUBSCRIBE: ID for devicestate subscriptions */
01671    int laststate;          /*!< SUBSCRIBE: Last known extension state */
01672    int dialogver;          /*!< SUBSCRIBE: Version for subscription dialog-info */
01673 
01674    struct ast_dsp *dsp;       /*!< A DSP for inband DTMF and fax CNG tone detection */
01675 
01676    struct sip_peer *relatedpeer;    /*!< If this dialog is related to a peer, which one 
01677                      Used in peerpoke, mwi subscriptions */
01678    struct sip_registry *registry;      /*!< If this is a REGISTER dialog, to which registry */
01679    struct ast_rtp *rtp;       /*!< RTP Session */
01680    struct ast_rtp *vrtp;         /*!< Video RTP session */
01681    struct ast_rtp *trtp;         /*!< Text RTP session */
01682    struct sip_pkt *packets;      /*!< Packets scheduled for re-transmission */
01683    struct sip_history_head *history;   /*!< History of this SIP dialog */
01684    size_t history_entries;       /*!< Number of entires in the history */
01685    struct ast_variable *chanvars;      /*!< Channel variables to set for inbound call */
01686    AST_LIST_HEAD_NOLOCK(request_queue, sip_request) request_queue; /*!< Requests that arrived but could not be processed immediately */
01687    int request_queue_sched_id;      /*!< Scheduler ID of any scheduled action to process queued requests */
01688    int provisional_keepalive_sched_id; /*!< Scheduler ID for provisional responses that need to be sent out to avoid cancellation */
01689    const char *last_provisional;   /*!< The last successfully transmitted provisonal response message */
01690    struct sip_invite_param *options;   /*!< Options for INVITE */
01691    int autoframing;        /*!< The number of Asters we group in a Pyroflax
01692                      before strolling to the Grokyzpå
01693                      (A bit unsure of this, please correct if
01694                      you know more) */
01695    struct sip_st_dlg *stimer;    /*!< SIP Session-Timers */              
01696   
01697    int red;             /*!< T.140 RTP Redundancy */
01698    int hangupcause;        /*!< Storage of hangupcause copied from our owner before we disconnect from the AST channel (only used at hangup) */
01699 
01700    struct sip_subscription_mwi *mwi;       /*!< If this is a subscription MWI dialog, to which subscription */
01701    /*! When receiving an SDP offer, it is important to take note of what media types were offered.
01702     * By doing this, even if we don't want to answer a particular media stream with something meaningful, we can
01703     * still put an m= line in our answer with the port set to 0.
01704     *
01705     * The reason for the length being 4 is that in this branch of Asterisk, the only media types supported are 
01706     * image, audio, text, and video. Therefore we need to keep track of which types of media were offered.
01707     *
01708     * Note that if we wanted to be 100% correct, we would keep a list of all media streams offered. That way we could respond
01709     * even to unknown media types, and we could respond to multiple streams of the same type. Such large-scale changes
01710     * are not a good idea for released branches, though, so we're compromising by just making sure that for the common cases:
01711     * audio and video, audio and T.38, and audio and text, we give the appropriate response to both media streams.
01712     *
01713     * The large-scale changes would be a good idea for implementing during an SDP rewrite.
01714     */
01715    struct offered_media offered_media[4];
01716 }; 
01717 
01718 
01719 /*! \brief
01720  * Here we implement the container for dialogs (sip_pvt), defining
01721  * generic wrapper functions to ease the transition from the current
01722  * implementation (a single linked list) to a different container.
01723  * In addition to a reference to the container, we need functions to lock/unlock
01724  * the container and individual items, and functions to add/remove
01725  * references to the individual items.
01726  */
01727 struct ao2_container *dialogs;
01728 
01729 #define sip_pvt_lock(x) ao2_lock(x)
01730 #define sip_pvt_trylock(x) ao2_trylock(x)
01731 #define sip_pvt_unlock(x) ao2_unlock(x)
01732 
01733 /*! \brief
01734  * when we create or delete references, make sure to use these
01735  * functions so we keep track of the refcounts.
01736  * To simplify the code, we allow a NULL to be passed to dialog_unref().
01737  */
01738 #ifdef REF_DEBUG
01739 #define dialog_ref(arg1,arg2) dialog_ref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
01740 #define dialog_unref(arg1,arg2) dialog_unref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
01741 
01742 static struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
01743 {
01744    if (p)
01745       _ao2_ref_debug(p, 1, tag, file, line, func);
01746    else
01747       ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
01748    return p;
01749 }
01750 
01751 static struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
01752 {
01753    if (p)
01754       _ao2_ref_debug(p, -1, tag, file, line, func);
01755    return NULL;
01756 }
01757 #else
01758 static struct sip_pvt *dialog_ref(struct sip_pvt *p, char *tag)
01759 {
01760    if (p)
01761       ao2_ref(p, 1);
01762    else
01763       ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
01764    return p;
01765 }
01766 
01767 static struct sip_pvt *dialog_unref(struct sip_pvt *p, char *tag)
01768 {
01769    if (p)
01770       ao2_ref(p, -1);
01771    return NULL;
01772 }
01773 #endif
01774 
01775 /*! \brief sip packet - raw format for outbound packets that are sent or scheduled for transmission
01776  * Packets are linked in a list, whose head is in the struct sip_pvt they belong to.
01777  * Each packet holds a reference to the parent struct sip_pvt.
01778  * This structure is allocated in __sip_reliable_xmit() and only for packets that
01779  * require retransmissions.
01780  */
01781 struct sip_pkt {
01782    struct sip_pkt *next;         /*!< Next packet in linked list */
01783    int retrans;            /*!< Retransmission number */
01784    int method;          /*!< SIP method for this packet */
01785    int seqno;           /*!< Sequence number */
01786    char is_resp;           /*!< 1 if this is a response packet (e.g. 200 OK), 0 if it is a request */
01787    char is_fatal;          /*!< non-zero if there is a fatal error */
01788    int response_code;      /*!< If this is a response, the response code */
01789    struct sip_pvt *owner;        /*!< Owner AST call */
01790    int retransid;          /*!< Retransmission ID */
01791    int timer_a;            /*!< SIP timer A, retransmission timer */
01792    int timer_t1;           /*!< SIP Timer T1, estimated RTT or 500 ms */
01793    int packetlen;          /*!< Length of packet */
01794    struct ast_str *data;
01795 }; 
01796 
01797 /*!
01798  * \brief A peer's mailbox
01799  *
01800  * We could use STRINGFIELDS here, but for only two strings, it seems like
01801  * too much effort ...
01802  */
01803 struct sip_mailbox {
01804    char *mailbox;
01805    char *context;
01806    unsigned int delme:1;
01807    /*! Associated MWI subscription */
01808    struct ast_event_sub *event_sub;
01809    AST_LIST_ENTRY(sip_mailbox) entry;
01810 };
01811 
01812 enum sip_peer_type {
01813    SIP_TYPE_PEER = (1 << 0),
01814    SIP_TYPE_USER = (1 << 1),
01815 };
01816 
01817 /*! \brief Structure for SIP peer data, we place calls to peers if registered  or fixed IP address (host) 
01818 */
01819 /* XXX field 'name' must be first otherwise sip_addrcmp() will fail, as will astobj2 hashing of the structure */
01820 struct sip_peer {
01821    char name[80];             /*!< the unique name of this object */
01822    AST_DECLARE_STRING_FIELDS(
01823       AST_STRING_FIELD(secret);     /*!< Password for inbound auth */
01824       AST_STRING_FIELD(md5secret);     /*!< Password in MD5 */
01825       AST_STRING_FIELD(remotesecret);     /*!< Remote secret (trunks, remote devices) */
01826       AST_STRING_FIELD(context);    /*!< Default context for incoming calls */
01827       AST_STRING_FIELD(subscribecontext); /*!< Default context for subscriptions */
01828       AST_STRING_FIELD(username);      /*!< Temporary username until registration */ 
01829       AST_STRING_FIELD(accountcode);      /*!< Account code */
01830       AST_STRING_FIELD(tohost);     /*!< If not dynamic, IP address */
01831       AST_STRING_FIELD(regexten);      /*!< Extension to register (if regcontext is used) */
01832       AST_STRING_FIELD(fromuser);      /*!< From: user when calling this peer */
01833       AST_STRING_FIELD(fromdomain);    /*!< From: domain when calling this peer */
01834       AST_STRING_FIELD(fullcontact);      /*!< Contact registered with us (not in sip.conf) */
01835       AST_STRING_FIELD(cid_num);    /*!< Caller ID num */
01836       AST_STRING_FIELD(cid_name);      /*!< Caller ID name */
01837       AST_STRING_FIELD(vmexten);       /*!< Dialplan extension for MWI notify message*/
01838       AST_STRING_FIELD(language);      /*!<  Default language for prompts */
01839       AST_STRING_FIELD(mohinterpret);     /*!<  Music on Hold class */
01840       AST_STRING_FIELD(mohsuggest);    /*!<  Music on Hold class */
01841       AST_STRING_FIELD(parkinglot);    /*!<  Parkinglot */
01842       AST_STRING_FIELD(useragent);     /*!<  User agent in SIP request (saved from registration) */
01843       );
01844    struct sip_socket socket;  /*!< Socket used for this peer */
01845    enum sip_transport default_outbound_transport;    /*!< Peer Registration may change the default outbound transport.
01846                                     If register expires, default should be reset. to this value */
01847    unsigned int transports:3;      /*!< Transports (enum sip_transport) that are acceptable for this peer */
01848    struct sip_auth *auth;     /*!< Realm authentication list */
01849    int amaflags;        /*!< AMA Flags (for billing) */
01850    int callingpres;     /*!< Calling id presentation */
01851    int inUse;        /*!< Number of calls in use */
01852    int inRinging;       /*!< Number of calls ringing */
01853    int onHold;                     /*!< Peer has someone on hold */
01854    int call_limit;         /*!< Limit of concurrent calls */
01855    int t38_maxdatagram;    /*!< T.38 FaxMaxDatagram override */
01856    int busy_level;         /*!< Level of active channels where we signal busy */
01857    enum transfermodes allowtransfer;   /*! SIP Refer restriction scheme */
01858    struct ast_codec_pref prefs;  /*!<  codec prefs */
01859    int lastmsgssent;
01860    unsigned int sipoptions;   /*!<  Supported SIP options */
01861    struct ast_flags flags[2]; /*!<  SIP_ flags */
01862 
01863    /*! Mailboxes that this peer cares about */
01864    AST_LIST_HEAD_NOLOCK(, sip_mailbox) mailboxes;
01865 
01866    /* things that don't belong in flags */
01867    char is_realtime;    /*!< this is a 'realtime' peer */
01868    char rt_fromcontact;    /*!< copy fromcontact from realtime */
01869    char host_dynamic;      /*!< Dynamic Peers register with Asterisk */
01870    char selfdestruct;      /*!< Automatic peers need to destruct themselves */
01871    char the_mark;       /*!< moved out of ASTOBJ into struct proper; That which bears the_mark should be deleted! */
01872 
01873    int expire;       /*!<  When to expire this peer registration */
01874    int capability;         /*!<  Codec capability */
01875    int rtptimeout;         /*!<  RTP timeout */
01876    int rtpholdtimeout;     /*!<  RTP Hold Timeout */
01877    int rtpkeepalive;    /*!<  Send RTP packets for keepalive */
01878    ast_group_t callgroup;     /*!<  Call group */
01879    ast_group_t pickupgroup;   /*!<  Pickup group */
01880    struct sip_proxy *outboundproxy; /*!< Outbound proxy for this peer */
01881    struct ast_dnsmgr_entry *dnsmgr;/*!<  DNS refresh manager for peer */
01882    struct sockaddr_in addr;   /*!<  IP address of peer */
01883    int maxcallbitrate;     /*!< Maximum Bitrate for a video call */
01884    unsigned int portinuri:1;  /*!< Whether the port should be included in the URI */
01885 
01886    /* Qualification */
01887    struct sip_pvt *call;      /*!<  Call pointer */
01888    int pokeexpire;         /*!<  When to expire poke (qualify= checking) */
01889    int lastms;       /*!<  How long last response took (in ms), or -1 for no response */
01890    int maxms;        /*!<  Max ms we will accept for the host to be up, 0 to not monitor */
01891    int qualifyfreq;     /*!<  Qualification: How often to check for the host to be up */
01892    struct timeval ps;      /*!<  Time for sending SIP OPTION in sip_pke_peer() */
01893    struct sockaddr_in defaddr;   /*!<  Default IP address, used until registration */
01894    struct ast_ha *ha;      /*!<  Access control list */
01895    struct ast_ha *contactha;       /*!<  Restrict what IPs are allowed in the Contact header (for registration) */
01896    struct ast_variable *chanvars;   /*!<  Variables to set for channel created by user */
01897    struct sip_pvt *mwipvt;    /*!<  Subscription for MWI */
01898    int autoframing;
01899    struct sip_st_cfg stimer;  /*!<  SIP Session-Timers */
01900    int timer_t1;        /*!<  The maximum T1 value for the peer */
01901    int timer_b;         /*!<  The maximum timer B (transaction timeouts) */
01902    int deprecated_username; /*!< If it's a realtime peer, are they using the deprecated "username" instead of "defaultuser" */
01903    
01904    /*XXX Seems like we suddenly have two flags with the same content. Why? To be continued... */
01905    enum sip_peer_type type; /*!< Distinguish between "user" and "peer" types. This is used solely for CLI and manager commands */
01906 };
01907 
01908 
01909 /*! 
01910  * \brief Registrations with other SIP proxies
01911  *
01912  * Created by sip_register(), the entry is linked in the 'regl' list,
01913  * and never deleted (other than at 'sip reload' or module unload times).
01914  * The entry always has a pending timeout, either waiting for an ACK to
01915  * the REGISTER message (in which case we have to retransmit the request),
01916  * or waiting for the next REGISTER message to be sent (either the initial one,
01917  * or once the previously completed registration one expires).
01918  * The registration can be in one of many states, though at the moment
01919  * the handling is a bit mixed.
01920  */
01921 struct sip_registry {
01922    ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
01923    AST_DECLARE_STRING_FIELDS(
01924       AST_STRING_FIELD(callid);  /*!< Global Call-ID */
01925       AST_STRING_FIELD(realm);   /*!< Authorization realm */
01926       AST_STRING_FIELD(nonce);   /*!< Authorization nonce */
01927       AST_STRING_FIELD(opaque);  /*!< Opaque nonsense */
01928       AST_STRING_FIELD(qop);     /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
01929       AST_STRING_FIELD(domain);  /*!< Authorization domain */
01930       AST_STRING_FIELD(username);   /*!< Who we are registering as */
01931       AST_STRING_FIELD(authuser);   /*!< Who we *authenticate* as */
01932       AST_STRING_FIELD(hostname);   /*!< Domain or host we register to */
01933       AST_STRING_FIELD(secret);  /*!< Password in clear text */   
01934       AST_STRING_FIELD(md5secret);  /*!< Password in md5 */
01935       AST_STRING_FIELD(callback);   /*!< Contact extension */
01936       AST_STRING_FIELD(random);
01937       AST_STRING_FIELD(peername);   /*!< Peer registering to */
01938    );
01939    enum sip_transport transport; /*!< Transport for this registration UDP, TCP or TLS */
01940    int portno;       /*!<  Optional port override */
01941    int expire;       /*!< Sched ID of expiration */
01942    int configured_expiry;     /*!< Configured value to use for the Expires header */
01943    int expiry;       /*!< Negotiated value used for the Expires header */
01944    int regattempts;     /*!< Number of attempts (since the last success) */
01945    int timeout;         /*!< sched id of sip_reg_timeout */
01946    int refresh;         /*!< How often to refresh */
01947    struct sip_pvt *call;      /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
01948    enum sipregistrystate regstate;  /*!< Registration state (see above) */
01949    struct timeval regtime;    /*!< Last successful registration time */
01950    int callid_valid;    /*!< 0 means we haven't chosen callid for this registry yet. */
01951    unsigned int ocseq;     /*!< Sequence number we got to for REGISTERs for this registry */
01952    struct ast_dnsmgr_entry *dnsmgr; /*!<  DNS refresh manager for register */
01953    struct sockaddr_in us;     /*!< Who the server thinks we are */
01954    int noncecount;         /*!< Nonce-count */
01955    char lastmsg[256];      /*!< Last Message sent/received */
01956 };
01957 
01958 enum sip_tcptls_alert {
01959    /*! \brief There is new data to be sent out */
01960    TCPTLS_ALERT_DATA,
01961    /*! \brief A request to stop the tcp_handler thread */
01962    TCPTLS_ALERT_STOP,
01963 };
01964 
01965 struct tcptls_packet {
01966    AST_LIST_ENTRY(tcptls_packet) entry;
01967    struct ast_str *data;
01968    size_t len;
01969 };
01970 /*! \brief Definition of a thread that handles a socket */
01971 struct sip_threadinfo {
01972    int stop;
01973    int alert_pipe[2]; /*! Used to alert tcptls thread when packet is ready to be written */
01974    pthread_t threadid;
01975    struct ast_tcptls_session_instance *tcptls_session;
01976    enum sip_transport type;   /*!< We keep a copy of the type here so we can display it in the connection list */
01977    AST_LIST_HEAD_NOLOCK(, tcptls_packet) packet_q;
01978 };
01979 
01980 /*! \brief Definition of an MWI subscription to another server */
01981 struct sip_subscription_mwi {
01982    ASTOBJ_COMPONENTS_FULL(struct sip_subscription_mwi,1,1);
01983    AST_DECLARE_STRING_FIELDS(
01984       AST_STRING_FIELD(username);     /*!< Who we are sending the subscription as */
01985       AST_STRING_FIELD(authuser);     /*!< Who we *authenticate* as */
01986       AST_STRING_FIELD(hostname);     /*!< Domain or host we subscribe to */
01987       AST_STRING_FIELD(secret);       /*!< Password in clear text */
01988       AST_STRING_FIELD(mailbox);      /*!< Mailbox store to put MWI into */
01989       );
01990    enum sip_transport transport;    /*!< Transport to use */
01991    int portno;                      /*!< Optional port override */
01992    int resub;                       /*!< Sched ID of resubscription */
01993    unsigned int subscribed:1;       /*!< Whether we are currently subscribed or not */
01994    struct sip_pvt *call;            /*!< Outbound subscription dialog */
01995    struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager for subscription */
01996    struct sockaddr_in us;           /*!< Who the server thinks we are */
01997 };
01998 
01999 /* --- Hash tables of various objects --------*/
02000 #ifdef LOW_MEMORY
02001 static const int HASH_PEER_SIZE = 17;
02002 static const int HASH_DIALOG_SIZE = 17;
02003 #else
02004 static const int HASH_PEER_SIZE = 563; /*!< Size of peer hash table, prime number preferred! */
02005 static const int HASH_DIALOG_SIZE = 563;
02006 #endif
02007 static struct ao2_container *threadt;
02008 
02009 /*! \brief  The peer list: Users, Peers and Friends */
02010 struct ao2_container *peers;
02011 struct ao2_container *peers_by_ip;
02012 
02013 /*! \brief  The register list: Other SIP proxies we register with and place calls to */
02014 static struct ast_register_list {
02015    ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
02016    int recheck;
02017 } regl;
02018 
02019 /*! \brief  The MWI subscription list */
02020 static struct ast_subscription_mwi_list {
02021    ASTOBJ_CONTAINER_COMPONENTS(struct sip_subscription_mwi);
02022 } submwil;
02023 
02024 /*! \brief
02025  * \note The only member of the peer used here is the name field
02026  */
02027 static int peer_hash_cb(const void *obj, const int flags)
02028 {
02029    const struct sip_peer *peer = obj;
02030 
02031    return ast_str_case_hash(peer->name);
02032 }
02033 
02034 /*!
02035  * \note The only member of the peer used here is the name field
02036  */
02037 static int peer_cmp_cb(void *obj, void *arg, int flags)
02038 {
02039    struct sip_peer *peer = obj, *peer2 = arg;
02040 
02041    return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
02042 }
02043 
02044 /*!
02045  * \note the peer's ip address field is used to create key.
02046  */
02047 static int peer_iphash_cb(const void *obj, const int flags)
02048 {
02049    const struct sip_peer *peer = obj;
02050    int ret1 = peer->addr.sin_addr.s_addr;
02051    if (ret1 < 0)
02052       ret1 = -ret1;
02053 
02054    return ret1;
02055 }
02056 
02057 /*!
02058  * Match Peers by IP and Port number.
02059  *
02060  * This function has two modes.
02061  *  - If the peer arg does not have INSECURE_PORT set, then we will only return
02062  *    a match for a peer that matches both the IP and port.
02063  *  - If the peer arg does have the INSECURE_PORT flag set, then we will only
02064  *    return a match for a peer that matches the IP and has insecure=port
02065  *    in its configuration.
02066  *
02067  * This callback will be used twice when doing peer matching.  There is a first
02068  * pass for full IP+port matching, and a second pass in case there is a match
02069  * that meets the insecure=port criteria.
02070  *
02071  * \note Connections coming in over TCP or TLS should never be matched by port.
02072  *
02073  * \note the peer's addr struct provides to fields combined to make a key: the sin_addr.s_addr and sin_port fields.
02074  */
02075 static int peer_ipcmp_cb(void *obj, void *arg, int flags)
02076 {
02077    struct sip_peer *peer = obj, *peer2 = arg;
02078 
02079    if (peer->addr.sin_addr.s_addr != peer2->addr.sin_addr.s_addr) {
02080       /* IP doesn't match */
02081       return 0;
02082    }
02083 
02084    /* We matched the IP, check to see if we need to match by port as well. */
02085    if ((peer->transports & peer2->transports) & (SIP_TRANSPORT_TLS | SIP_TRANSPORT_TCP)) {
02086       /* peer matching on port is not possible with TCP/TLS */
02087       return CMP_MATCH | CMP_STOP;
02088    } else if (ast_test_flag(&peer2->flags[0], SIP_INSECURE_PORT)) {
02089       /* We are allowing match without port for peers configured that
02090        * way in this pass through the peers. */
02091       return ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT) ?
02092             (CMP_MATCH | CMP_STOP) : 0;
02093    }
02094 
02095    /* Now only return a match if the port matches, as well. */
02096    return peer->addr.sin_port == peer2->addr.sin_port ? (CMP_MATCH | CMP_STOP) : 0;
02097 }
02098 
02099 
02100 static int threadt_hash_cb(const void *obj, const int flags)
02101 {
02102    const struct sip_threadinfo *th = obj;
02103 
02104    return (int) th->tcptls_session->remote_address.sin_addr.s_addr;
02105 }
02106 
02107 static int threadt_cmp_cb(void *obj, void *arg, int flags)
02108 {
02109    struct sip_threadinfo *th = obj, *th2 = arg;
02110 
02111    return (th->tcptls_session == th2->tcptls_session) ? CMP_MATCH | CMP_STOP : 0;
02112 }
02113 
02114 /*!
02115  * \note The only member of the dialog used here callid string
02116  */
02117 static int dialog_hash_cb(const void *obj, const int flags)
02118 {
02119    const struct sip_pvt *pvt = obj;
02120 
02121    return ast_str_case_hash(pvt->callid);
02122 }
02123 
02124 /*!
02125  * \note The only member of the dialog used here callid string
02126  */
02127 static int dialog_cmp_cb(void *obj, void *arg, int flags)
02128 {
02129    struct sip_pvt *pvt = obj, *pvt2 = arg;
02130    
02131    return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH | CMP_STOP : 0;
02132 }
02133 
02134 static int temp_pvt_init(void *);
02135 static void temp_pvt_cleanup(void *);
02136 
02137 /*! \brief A per-thread temporary pvt structure */
02138 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
02139 
02140 #ifdef LOW_MEMORY
02141 static void ts_ast_rtp_destroy(void *);
02142 
02143 AST_THREADSTORAGE_CUSTOM(ts_audio_rtp, NULL, ts_ast_rtp_destroy);
02144 AST_THREADSTORAGE_CUSTOM(ts_video_rtp, NULL, ts_ast_rtp_destroy);
02145 AST_THREADSTORAGE_CUSTOM(ts_text_rtp, NULL, ts_ast_rtp_destroy);
02146 #endif
02147 
02148 /*! \brief Authentication list for realm authentication 
02149  * \todo Move the sip_auth list to AST_LIST */
02150 static struct sip_auth *authl = NULL;
02151 
02152 
02153 /* --- Sockets and networking --------------*/
02154 
02155 /*! \brief Main socket for UDP SIP communication.
02156  *
02157  * sipsock is shared between the SIP manager thread (which handles reload
02158  * requests), the udp io handler (sipsock_read()) and the user routines that
02159  * issue udp writes (using __sip_xmit()).
02160  * The socket is -1 only when opening fails (this is a permanent condition),
02161  * or when we are handling a reload() that changes its address (this is
02162  * a transient situation during which we might have a harmless race, see
02163  * below). Because the conditions for the race to be possible are extremely
02164  * rare, we don't want to pay the cost of locking on every I/O.
02165  * Rather, we remember that when the race may occur, communication is
02166  * bound to fail anyways, so we just live with this event and let
02167  * the protocol handle this above us.
02168  */
02169 static int sipsock  = -1;
02170 
02171 static struct sockaddr_in bindaddr; /*!< UDP: The address we bind to */
02172 
02173 /*! \brief our (internal) default address/port to put in SIP/SDP messages
02174  *  internip is initialized picking a suitable address from one of the
02175  * interfaces, and the same port number we bind to. It is used as the
02176  * default address/port in SIP messages, and as the default address
02177  * (but not port) in SDP messages.
02178  */
02179 static struct sockaddr_in internip;
02180 
02181 /*! \brief our external IP address/port for SIP sessions.
02182  * externip.sin_addr is only set when we know we might be behind
02183  * a NAT, and this is done using a variety of (mutually exclusive)
02184  * ways from the config file:
02185  *
02186  * + with "externip = host[:port]" we specify the address/port explicitly.
02187  *   The address is looked up only once when (re)loading the config file;
02188  * 
02189  * + with "externhost = host[:port]" we do a similar thing, but the
02190  *   hostname is stored in externhost, and the hostname->IP mapping
02191  *   is refreshed every 'externrefresh' seconds;
02192  * 
02193  * + with "stunaddr = host[:port]" we run queries every externrefresh seconds
02194  *   to the specified server, and store the result in externip.
02195  *
02196  * Other variables (externhost, externexpire, externrefresh) are used
02197  * to support the above functions.
02198  */
02199 static struct sockaddr_in externip;    /*!< External IP address if we are behind NAT */
02200 
02201 static char externhost[MAXHOSTNAMELEN];      /*!< External host name */
02202 static time_t externexpire;         /*!< Expiration counter for re-resolving external host name in dynamic DNS */
02203 static int externrefresh = 10;
02204 static struct sockaddr_in stunaddr;    /*!< stun server address */
02205 
02206 /*! \brief  List of local networks
02207  * We store "localnet" addresses from the config file into an access list,
02208  * marked as 'DENY', so the call to ast_apply_ha() will return
02209  * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
02210  * (i.e. presumably public) addresses.
02211  */
02212 static struct ast_ha *localaddr;    /*!< List of local networks, on the same side of NAT as this Asterisk */
02213 
02214 static int ourport_tcp;          /*!< The port used for TCP connections */
02215 static int ourport_tls;          /*!< The port used for TCP/TLS connections */
02216 static struct sockaddr_in debugaddr;
02217 
02218 static struct ast_config *notify_types = NULL;     /*!< The list of manual NOTIFY types we know how to send */
02219 
02220 /*! some list management macros. */
02221  
02222 #define UNLINK(element, head, prev) do {  \
02223    if (prev)            \
02224       (prev)->next = (element)->next;  \
02225    else              \
02226       (head) = (element)->next;  \
02227    } while (0)
02228 
02229 enum t38_action_flag {
02230    SDP_T38_NONE = 0, /*!< Do not modify T38 information at all */
02231    SDP_T38_INITIATE, /*!< Remote side has requested T38 with us */
02232    SDP_T38_ACCEPT,   /*!< Remote side accepted our T38 request */
02233 };
02234 
02235 /*---------------------------- Forward declarations of functions in chan_sip.c */
02236 /* Note: This is added to help splitting up chan_sip.c into several files
02237    in coming releases. */
02238 
02239 /*--- PBX interface functions */
02240 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
02241 static int sip_devicestate(void *data);
02242 static int sip_sendtext(struct ast_channel *ast, const char *text);
02243 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
02244 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
02245 static int sip_hangup(struct ast_channel *ast);
02246 static int sip_answer(struct ast_channel *ast);
02247 static struct ast_frame *sip_read(struct ast_channel *ast);
02248 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
02249 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
02250 static int sip_transfer(struct ast_channel *ast, const char *dest);
02251 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
02252 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
02253 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
02254 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
02255 static const char *sip_get_callid(struct ast_channel *chan);
02256 
02257 static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin);
02258 static int sip_standard_port(enum sip_transport type, int port);
02259 static int sip_prepare_socket(struct sip_pvt *p);
02260 static int sip_parse_host(char *line, int lineno, char **hostname, int *portnum, enum sip_transport *transport);
02261 
02262 /*--- Transmitting responses and requests */
02263 static int sipsock_read(int *id, int fd, short events, void *ignore);
02264 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len);
02265 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod);
02266 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
02267 static int retrans_pkt(const void *data);
02268 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);
02269 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
02270 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
02271 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
02272 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp);
02273 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
02274 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);
02275 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
02276 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
02277 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable);
02278 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
02279 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
02280 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
02281 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
02282 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
02283 static int transmit_info_with_vidupdate(struct sip_pvt *p);
02284 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
02285 static int transmit_refer(struct sip_pvt *p, const char *dest);
02286 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
02287 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
02288 static int transmit_notify_custom(struct sip_pvt *p, struct ast_variable *vars);
02289 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
02290 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
02291 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
02292 static void copy_request(struct sip_request *dst, const struct sip_request *src);
02293 static void receive_message(struct sip_pvt *p, struct sip_request *req);
02294 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req);
02295 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only);
02296 
02297 /*--- Dialog management */
02298 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
02299              int useglobal_nat, const int intended_method, struct sip_request *req);
02300 static int __sip_autodestruct(const void *data);
02301 static void sip_scheddestroy(struct sip_pvt *p, int ms);
02302 static int sip_cancel_destroy(struct sip_pvt *p);
02303 static struct sip_pvt *sip_destroy(struct sip_pvt *p);
02304 static void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist);
02305 static void *registry_unref(struct sip_registry *reg, char *tag);
02306 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist);
02307 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
02308 static void __sip_pretend_ack(struct sip_pvt *p);
02309 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
02310 static int auto_congest(const void *arg);
02311 static int update_call_counter(struct sip_pvt *fup, int event);
02312 static int hangup_sip2cause(int cause);
02313 static const char *hangup_cause2sip(int cause);
02314 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
02315 static void free_old_route(struct sip_route *route);
02316 static void list_route(struct sip_route *route);
02317 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
02318 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
02319                      struct sip_request *req, char *uri);
02320 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
02321 static void check_pendings(struct sip_pvt *p);
02322 static void *sip_park_thread(void *stuff);
02323 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
02324 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
02325 
02326 /*--- Codec handling / SDP */
02327 static void try_suggested_sip_codec(struct sip_pvt *p);
02328 static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
02329 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
02330 static int find_sdp(struct sip_request *req);
02331 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
02332 static int process_sdp_o(const char *o, struct sip_pvt *p);
02333 static int process_sdp_c(const char *c, struct ast_hostent *hp);
02334 static int process_sdp_a_sendonly(const char *a, int *sendonly);
02335 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp *newaudiortp, int *last_rtpmap_codec);
02336 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp *newvideortp, int *last_rtpmap_codec);
02337 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);
02338 static int process_sdp_a_image(const char *a, struct sip_pvt *p);
02339 static void add_codec_to_sdp(const struct sip_pvt *p, int codec,
02340               struct ast_str **m_buf, struct ast_str **a_buf,
02341               int debug, int *min_packet_size);
02342 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
02343             struct ast_str **m_buf, struct ast_str **a_buf,
02344             int debug);
02345 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
02346 static void do_setnat(struct sip_pvt *p, int natflags);
02347 static void stop_media_flows(struct sip_pvt *p);
02348 
02349 /*--- Authentication stuff */
02350 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
02351 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
02352 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
02353                 const char *secret, const char *md5secret, int sipmethod,
02354                 char *uri, enum xmittype reliable, int ignore);
02355 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
02356                      int sipmethod, char *uri, enum xmittype reliable,
02357                      struct sockaddr_in *sin, struct sip_peer **authpeer);
02358 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);
02359 
02360 /*--- Domain handling */
02361 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
02362 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
02363 static void clear_sip_domains(void);
02364 
02365 /*--- SIP realm authentication */
02366 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno);
02367 static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */
02368 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
02369 
02370 /*--- Misc functions */
02371 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t);
02372 static int sip_do_reload(enum channelreloadreason reason);
02373 static int reload_config(enum channelreloadreason reason);
02374 static int expire_register(const void *data);
02375 static void *do_monitor(void *data);
02376 static int restart_monitor(void);
02377 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
02378 static struct ast_variable *copy_vars(struct ast_variable *src);
02379 /* static int sip_addrcmp(char *name, struct sockaddr_in *sin);   Support for peer matching */
02380 static int sip_refer_allocate(struct sip_pvt *p);
02381 static void ast_quiet_chan(struct ast_channel *chan);
02382 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
02383 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
02384 
02385 /*!
02386  * \brief generic function for determining if a correct transport is being 
02387  * used to contact a peer
02388  *
02389  * this is done as a macro so that the "tmpl" var can be passed either a 
02390  * sip_request or a sip_peer 
02391  */
02392 #define check_request_transport(peer, tmpl) ({ \
02393    int ret = 0; \
02394    if (peer->socket.type == tmpl->socket.type) \
02395       ; \
02396    else if (!(peer->transports & tmpl->socket.type)) {\
02397       ast_log(LOG_ERROR, \
02398          "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
02399          get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
02400          ); \
02401       ret = 1; \
02402    } else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
02403       ast_log(LOG_WARNING, \
02404          "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
02405          peer->name, get_transport(tmpl->socket.type) \
02406       ); \
02407    } else { \
02408       ast_debug(1, \
02409          "peer '%s' has contacted us over %s even though we prefer %s.\n", \
02410          peer->name, get_transport(tmpl->socket.type), get_transport(peer->socket.type) \
02411       ); \
02412    }\
02413    (ret); \
02414 })
02415 
02416 
02417 /*--- Device monitoring and Device/extension state/event handling */
02418 static int cb_extensionstate(char *context, char* exten, int state, void *data);
02419 static int sip_devicestate(void *data);
02420 static int sip_poke_noanswer(const void *data);
02421 static int sip_poke_peer(struct sip_peer *peer, int force);
02422 static void sip_poke_all_peers(void);
02423 static void sip_peer_hold(struct sip_pvt *p, int hold);
02424 static void mwi_event_cb(const struct ast_event *, void *);
02425 
02426 /*--- Applications, functions, CLI and manager command helpers */
02427 static const char *sip_nat_mode(const struct sip_pvt *p);
02428 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02429 static char *transfermode2str(enum transfermodes mode) attribute_const;
02430 static const char *nat2str(int nat) attribute_const;
02431 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
02432 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02433 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02434 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02435 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02436 static void  print_group(int fd, ast_group_t group, int crlf);
02437 static const char *dtmfmode2str(int mode) attribute_const;
02438 static int str2dtmfmode(const char *str) attribute_unused;
02439 static const char *insecure2str(int mode) attribute_const;
02440 static void cleanup_stale_contexts(char *new, char *old);
02441 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
02442 static const char *domain_mode_to_text(const enum domain_mode mode);
02443 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02444 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02445 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02446 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02447 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02448 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02449 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02450 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02451 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02452 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
02453 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
02454 static char *complete_sip_peer(const char *word, int state, int flags2);
02455 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
02456 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
02457 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
02458 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
02459 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
02460 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02461 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02462 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02463 static char *sip_do_debug_ip(int fd, char *arg);
02464 static char *sip_do_debug_peer(int fd, char *arg);
02465 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02466 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02467 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02468 static int sip_dtmfmode(struct ast_channel *chan, void *data);
02469 static int sip_addheader(struct ast_channel *chan, void *data);
02470 static int sip_do_reload(enum channelreloadreason reason);
02471 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02472 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
02473 
02474 /*--- Debugging 
02475    Functions for enabling debug per IP or fully, or enabling history logging for
02476    a SIP dialog
02477 */
02478 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to debuglog at end of dialog, before destroying data */
02479 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
02480 static inline int sip_debug_test_pvt(struct sip_pvt *p);
02481 
02482 
02483 /*! \brief Append to SIP dialog history 
02484    \return Always returns 0 */
02485 #define append_history(p, event, fmt , args... )   append_history_full(p, "%-15s " fmt, event, ## args)
02486 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
02487 static void sip_dump_history(struct sip_pvt *dialog);
02488 
02489 /*--- Device object handling */
02490 static struct sip_peer *temp_peer(const char *name);
02491 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
02492 static int update_call_counter(struct sip_pvt *fup, int event);
02493 static void sip_destroy_peer(struct sip_peer *peer);
02494 static void sip_destroy_peer_fn(void *peer);
02495 static void set_peer_defaults(struct sip_peer *peer);
02496 static struct sip_peer *temp_peer(const char *name);
02497 static void register_peer_exten(struct sip_peer *peer, int onoff);
02498 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int forcenamematch, int devstate_only, int transport);
02499 static int sip_poke_peer_s(const void *data);
02500 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
02501 static void reg_source_db(struct sip_peer *peer);
02502 static void destroy_association(struct sip_peer *peer);
02503 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
02504 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
02505 static void set_socket_transport(struct sip_socket *socket, int transport);
02506 
02507 /* Realtime device support */
02508 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);
02509 static void update_peer(struct sip_peer *p, int expire);
02510 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
02511 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername);
02512 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin, int devstate_only);
02513 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02514 
02515 /*--- Internal UA client handling (outbound registrations) */
02516 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p);
02517 static void sip_registry_destroy(struct sip_registry *reg);
02518 static int sip_register(const char *value, int lineno);
02519 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
02520 static int sip_reregister(const void *data);
02521 static int __sip_do_register(struct sip_registry *r);
02522 static int sip_reg_timeout(const void *data);
02523 static void sip_send_all_registers(void);
02524 static int sip_reinvite_retry(const void *data);
02525 
02526 /*--- Parsing SIP requests and responses */
02527 static void append_date(struct sip_request *req);  /* Append date to SIP packet */
02528 static int determine_firstline_parts(struct sip_request *req);
02529 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
02530 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
02531 static int find_sip_method(const char *msg);
02532 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
02533 static int parse_request(struct sip_request *req);
02534 static const char *get_header(const struct sip_request *req, const char *name);
02535 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
02536 static int method_match(enum sipmethod id, const char *name);
02537 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
02538 static char *get_in_brackets(char *tmp);
02539 static const char *find_alias(const char *name, const char *_default);
02540 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
02541 static int lws2sws(char *msgbuf, int len);
02542 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
02543 static char *remove_uri_parameters(char *uri);
02544 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
02545 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
02546 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
02547 static int set_address_from_contact(struct sip_pvt *pvt);
02548 static void check_via(struct sip_pvt *p, struct sip_request *req);
02549 static char *get_calleridname(const char *input, char *output, size_t outputsize);
02550 static int get_rpid_num(const char *input, char *output, int maxlen);
02551 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
02552 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
02553 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline);
02554 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
02555 
02556 /*-- TCP connection handling ---*/
02557 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session);
02558 static void *sip_tcp_worker_fn(void *);
02559 
02560 /*--- Constructing requests and responses */
02561 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
02562 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
02563 static void deinit_req(struct sip_request *req);
02564 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
02565 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
02566 static int init_resp(struct sip_request *resp, const char *msg);
02567 static inline int resp_needs_contact(const char *msg, enum sipmethod method);
02568 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
02569 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
02570 static void build_via(struct sip_pvt *p);
02571 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
02572 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog);
02573 static char *generate_random_string(char *buf, size_t size);
02574 static void build_callid_pvt(struct sip_pvt *pvt);
02575 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
02576 static void make_our_tag(char *tagbuf, size_t len);
02577 static int add_header(struct sip_request *req, const char *var, const char *value);
02578 static int add_content(struct sip_request *req, const char *line);
02579 static int finalize_content(struct sip_request *req);
02580 static int add_text(struct sip_request *req, const char *text);
02581 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
02582 static int add_vidupdate(struct sip_request *req);
02583 static void add_route(struct sip_request *req, struct sip_route *route);
02584 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
02585 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
02586 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
02587 static void set_destination(struct sip_pvt *p, char *uri);
02588 static void append_date(struct sip_request *req);
02589 static void build_contact(struct sip_pvt *p);
02590 static void build_rpid(struct sip_pvt *p);
02591 
02592 /*------Request handling functions */
02593 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
02594 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);
02595 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
02596 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
02597 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
02598 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
02599 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
02600 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
02601 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
02602 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
02603 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *nounlock);
02604 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
02605 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);
02606 
02607 /*------Response handling functions */
02608 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02609 static void handle_response_notify(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02610 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02611 static void handle_response_subscribe(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02612 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02613 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02614 
02615 /*----- RTP interface functions */
02616 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);
02617 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02618 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02619 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02620 static int sip_get_codec(struct ast_channel *chan);
02621 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);
02622 
02623 /*------ T38 Support --------- */
02624 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
02625 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
02626 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
02627 static void change_t38_state(struct sip_pvt *p, int state);
02628 
02629 /*------ Session-Timers functions --------- */
02630 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
02631 static int  proc_session_timer(const void *vp);
02632 static void stop_session_timer(struct sip_pvt *p);
02633 static void start_session_timer(struct sip_pvt *p);
02634 static void restart_session_timer(struct sip_pvt *p);
02635 static const char *strefresher2str(enum st_refresher r);
02636 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
02637 static int parse_minse(const char *p_hdrval, int *const p_interval);
02638 static int st_get_se(struct sip_pvt *, int max);
02639 static enum st_refresher st_get_refresher(struct sip_pvt *);
02640 static enum st_mode st_get_mode(struct sip_pvt *);
02641 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
02642 
02643 /*!--- SIP MWI Subscription support */
02644 static int sip_subscribe_mwi(const char *value, int lineno);
02645 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
02646 static void sip_send_all_mwi_subscriptions(void);
02647 static int sip_subscribe_mwi_do(const void *data);
02648 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
02649 
02650 /*! \brief Definition of this channel for PBX channel registration */
02651 static const struct ast_channel_tech sip_tech = {
02652    .type = "SIP",
02653    .description = "Session Initiation Protocol (SIP)",
02654    .capabilities = AST_FORMAT_AUDIO_MASK, /* all audio formats */
02655    .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
02656    .requester = sip_request_call,         /* called with chan unlocked */
02657    .devicestate = sip_devicestate,        /* called with chan unlocked (not chan-specific) */
02658    .call = sip_call,       /* called with chan locked */
02659    .send_html = sip_sendhtml,
02660    .hangup = sip_hangup,         /* called with chan locked */
02661    .answer = sip_answer,         /* called with chan locked */
02662    .read = sip_read,       /* called with chan locked */
02663    .write = sip_write,        /* called with chan locked */
02664    .write_video = sip_write,     /* called with chan locked */
02665    .write_text = sip_write,
02666    .indicate = sip_indicate,     /* called with chan locked */
02667    .transfer = sip_transfer,     /* called with chan locked */
02668    .fixup = sip_fixup,        /* called with chan locked */
02669    .send_digit_begin = sip_senddigit_begin,  /* called with chan unlocked */
02670    .send_digit_end = sip_senddigit_end,
02671    .bridge = ast_rtp_bridge,        /* XXX chan unlocked ? */
02672    .early_bridge = ast_rtp_early_bridge,
02673    .send_text = sip_sendtext,    /* called with chan locked */
02674    .func_channel_read = acf_channel_read,
02675    .queryoption = sip_queryoption,
02676    .get_pvt_uniqueid = sip_get_callid,
02677 };
02678 
02679 /*! \brief This version of the sip channel tech has no send_digit_begin
02680  * callback so that the core knows that the channel does not want
02681  * DTMF BEGIN frames.
02682  * The struct is initialized just before registering the channel driver,
02683  * and is for use with channels using SIP INFO DTMF.
02684  */
02685 static struct ast_channel_tech sip_tech_info;
02686 
02687 
02688 /*! \brief Working TLS connection configuration */
02689 static struct ast_tls_config sip_tls_cfg;
02690 
02691 /*! \brief Default TLS connection configuration */
02692 static struct ast_tls_config default_tls_cfg;
02693 
02694 /*! \brief The TCP server definition */
02695 static struct ast_tcptls_session_args sip_tcp_desc = {
02696    .accept_fd = -1,
02697    .master = AST_PTHREADT_NULL,
02698    .tls_cfg = NULL,
02699    .poll_timeout = -1,
02700    .name = "SIP TCP server",
02701    .accept_fn = ast_tcptls_server_root,
02702    .worker_fn = sip_tcp_worker_fn,
02703 };
02704 
02705 /*! \brief The TCP/TLS server definition */
02706 static struct ast_tcptls_session_args sip_tls_desc = {
02707    .accept_fd = -1,
02708    .master = AST_PTHREADT_NULL,
02709    .tls_cfg = &sip_tls_cfg,
02710    .poll_timeout = -1,
02711    .name = "SIP TLS server",
02712    .accept_fn = ast_tcptls_server_root,
02713    .worker_fn = sip_tcp_worker_fn,
02714 };
02715 
02716 /* wrapper macro to tell whether t points to one of the sip_tech descriptors */
02717 #define IS_SIP_TECH(t)  ((t) == &sip_tech || (t) == &sip_tech_info)
02718 
02719 /*! \brief map from an integer value to a string.
02720  * If no match is found, return errorstring
02721  */
02722 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
02723 {
02724    const struct _map_x_s *cur;
02725 
02726    for (cur = table; cur->s; cur++)
02727       if (cur->x == x)
02728          return cur->s;
02729    return errorstring;
02730 }
02731 
02732 /*! \brief map from a string to an integer value, case insensitive.
02733  * If no match is found, return errorvalue.
02734  */
02735 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
02736 {
02737    const struct _map_x_s *cur;
02738 
02739    for (cur = table; cur->s; cur++)
02740       if (!strcasecmp(cur->s, s))
02741          return cur->x;
02742    return errorvalue;
02743 }
02744 
02745 
02746 /*! \brief Interface structure with callbacks used to connect to RTP module */
02747 static struct ast_rtp_protocol sip_rtp = {
02748    .type = "SIP",
02749    .get_rtp_info = sip_get_rtp_peer,
02750    .get_vrtp_info = sip_get_vrtp_peer,
02751    .get_trtp_info = sip_get_trtp_peer,
02752    .set_rtp_peer = sip_set_rtp_peer,
02753    .get_codec = sip_get_codec,
02754 };
02755 
02756 /*!
02757  * duplicate a list of channel variables, \return the copy.
02758  */
02759 static struct ast_variable *copy_vars(struct ast_variable *src)
02760 {
02761    struct ast_variable *res = NULL, *tmp, *v = NULL;
02762 
02763    for (v = src ; v ; v = v->next) {
02764       if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
02765          tmp->next = res;
02766          res = tmp;
02767       }
02768    }
02769    return res;
02770 }
02771 
02772 static void tcptls_packet_destructor(void *obj)
02773 {
02774    struct tcptls_packet *packet = obj;
02775 
02776    ast_free(packet->data);
02777 }
02778 
02779 static void sip_tcptls_client_args_destructor(void *obj)
02780 {
02781    struct ast_tcptls_session_args *args = obj;
02782    if (args->tls_cfg) {
02783       ast_free(args->tls_cfg->certfile);
02784       ast_free(args->tls_cfg->cipher);
02785       ast_free(args->tls_cfg->cafile);
02786       ast_free(args->tls_cfg->capath);
02787    }
02788    ast_free(args->tls_cfg);
02789    ast_free((char *) args->name);
02790 }
02791 
02792 static void sip_threadinfo_destructor(void *obj)
02793 {
02794    struct sip_threadinfo *th = obj;
02795    struct tcptls_packet *packet;
02796    if (th->alert_pipe[1] > -1) {
02797       close(th->alert_pipe[0]);
02798    }
02799    if (th->alert_pipe[1] > -1) {
02800       close(th->alert_pipe[1]);
02801    }
02802    th->alert_pipe[0] = th->alert_pipe[1] = -1;
02803 
02804    while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
02805       ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
02806    }
02807 
02808    if (th->tcptls_session) {
02809       ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
02810    }
02811 }
02812 
02813 /*! \brief creates a sip_threadinfo object and links it into the threadt table. */
02814 static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
02815 {
02816    struct sip_threadinfo *th;
02817 
02818    if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
02819       return NULL;
02820    }
02821 
02822    th->alert_pipe[0] = th->alert_pipe[1] = -1;
02823 
02824    if (pipe(th->alert_pipe) == -1) {
02825       ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
02826       ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
02827       return NULL;
02828    }
02829    ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
02830    th->tcptls_session = tcptls_session;
02831    th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
02832    ao2_t_link(threadt, th, "Adding new tcptls helper thread");
02833    ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
02834    return th;
02835 }
02836 
02837 /*! \brief used to indicate to a tcptls thread that data is ready to be written */
02838 static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
02839 {
02840    int res = len;
02841    struct sip_threadinfo *th = NULL;
02842    struct tcptls_packet *packet = NULL;
02843    struct sip_threadinfo tmp = {
02844       .tcptls_session = tcptls_session,
02845    };
02846    enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
02847 
02848    if (!tcptls_session) {
02849       return XMIT_ERROR;
02850    }
02851 
02852    ast_mutex_lock(&tcptls_session->lock);
02853 
02854    if ((tcptls_session->fd == -1) ||
02855       !(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
02856       !(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
02857       !(packet->data = ast_str_create(len))) {
02858       goto tcptls_write_setup_error;
02859    }
02860 
02861    /* goto tcptls_write_error should _NOT_ be used beyond this point */
02862    ast_str_set(&packet->data, 0, "%s", (char *) buf);
02863    packet->len = len;
02864 
02865    /* alert tcptls thread handler that there is a packet to be sent.
02866     * must lock the thread info object to guarantee control of the
02867     * packet queue */
02868    ao2_lock(th);
02869    if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
02870       ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
02871       ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
02872       packet = NULL;
02873       res = XMIT_ERROR;
02874    } else { /* it is safe to queue the frame after issuing the alert when we hold the threadinfo lock */
02875       AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
02876    }
02877    ao2_unlock(th);
02878 
02879    ast_mutex_unlock(&tcptls_session->lock);
02880    ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
02881    return res;
02882 
02883 tcptls_write_setup_error:
02884    if (th) {
02885       ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
02886    }
02887    if (packet) {
02888       ao2_t_ref(packet, -1, "could not allocate packet's data");
02889    }
02890    ast_mutex_unlock(&tcptls_session->lock);
02891 
02892    return XMIT_ERROR;
02893 }
02894 
02895 /*! \brief SIP TCP connection handler */
02896 static void *sip_tcp_worker_fn(void *data)
02897 {
02898    struct ast_tcptls_session_instance *tcptls_session = data;
02899 
02900    return _sip_tcp_helper_thread(NULL, tcptls_session);
02901 }
02902 
02903 /*! \brief SIP TCP thread management function 
02904    This function reads from the socket, parses the packet into a request
02905 */
02906 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session) 
02907 {
02908    int res, cl;
02909    struct sip_request req = { 0, } , reqcpy = { 0, };
02910    struct sip_threadinfo *me = NULL;
02911    char buf[1024] = "";
02912    struct pollfd fds[2] = { { 0 }, { 0 }, };
02913    struct ast_tcptls_session_args *ca = NULL;
02914 
02915    /* If this is a server session, then the connection has already been setup,
02916     * simply create the threadinfo object so we can access this thread for writing.
02917     * 
02918     * if this is a client connection more work must be done.
02919     * 1. We own the parent session args for a client connection.  This pointer needs
02920     *    to be held on to so we can decrement it's ref count on thread destruction.
02921     * 2. The threadinfo object was created before this thread was launched, however
02922     *    it must be found within the threadt table.
02923     * 3. Last, the tcptls_session must be started.
02924     */
02925    if (!tcptls_session->client) {
02926       if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
02927          goto cleanup;
02928       }
02929       ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
02930    } else {
02931       struct sip_threadinfo tmp = {
02932          .tcptls_session = tcptls_session,
02933       };
02934 
02935       if ((!(ca = tcptls_session->parent)) ||
02936          (!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
02937          (!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
02938          goto cleanup;
02939       }
02940    }
02941 
02942    me->threadid = pthread_self();
02943    ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
02944 
02945    /* set up pollfd to watch for reads on both the socket and the alert_pipe */
02946    fds[0].fd = tcptls_session->fd;
02947    fds[1].fd = me->alert_pipe[0];
02948    fds[0].events = fds[1].events = POLLIN | POLLPRI;
02949 
02950    if (!(req.data = ast_str_create(SIP_MIN_PACKET)))
02951       goto cleanup;
02952    if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET)))
02953       goto cleanup;
02954 
02955    for (;;) {
02956       struct ast_str *str_save;
02957 
02958       res = ast_poll(fds, 2, -1); /* polls for both socket and alert_pipe */
02959 
02960       if (res < 0) {
02961          ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
02962          goto cleanup;
02963       }
02964 
02965       /* handle the socket event, check for both reads from the socket fd,
02966        * and writes from alert_pipe fd */
02967       if (fds[0].revents) { /* there is data on the socket to be read */
02968 
02969          fds[0].revents = 0;
02970 
02971          /* clear request structure */
02972          str_save = req.data;
02973          memset(&req, 0, sizeof(req));
02974          req.data = str_save;
02975          ast_str_reset(req.data);
02976 
02977          str_save = reqcpy.data;
02978          memset(&reqcpy, 0, sizeof(reqcpy));
02979          reqcpy.data = str_save;
02980          ast_str_reset(reqcpy.data);
02981 
02982          memset(buf, 0, sizeof(buf));
02983 
02984          if (tcptls_session->ssl) {
02985             set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
02986             req.socket.port = htons(ourport_tls);
02987          } else {
02988             set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
02989             req.socket.port = htons(ourport_tcp);
02990          }
02991          req.socket.fd = tcptls_session->fd;
02992 
02993          /* Read in headers one line at a time */
02994          while (req.len < 4 || strncmp(REQ_OFFSET_TO_STR(&req, len - 4), "\r\n\r\n", 4)) {
02995             ast_mutex_lock(&tcptls_session->lock);
02996             if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
02997                ast_mutex_unlock(&tcptls_session->lock);
02998                goto cleanup;
02999             }
03000             ast_mutex_unlock(&tcptls_session->lock);
03001             if (me->stop)
03002                 goto cleanup;
03003             ast_str_append(&req.data, 0, "%s", buf);
03004             req.len = req.data->used;
03005          }
03006          copy_request(&reqcpy, &req);
03007          parse_request(&reqcpy);
03008          /* In order to know how much to read, we need the content-length header */
03009          if (sscanf(get_header(&reqcpy, "Content-Length"), "%30d", &cl)) {
03010             while (cl > 0) {
03011                size_t bytes_read;
03012                ast_mutex_lock(&tcptls_session->lock);
03013                if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, cl), tcptls_session->f))) {
03014                   ast_mutex_unlock(&tcptls_session->lock);
03015                   goto cleanup;
03016                }
03017                buf[bytes_read] = '\0';
03018                ast_mutex_unlock(&tcptls_session->lock);
03019                if (me->stop)
03020                   goto cleanup;
03021                cl -= strlen(buf);
03022                ast_str_append(&req.data, 0, "%s", buf);
03023                req.len = req.data->used;
03024             }
03025          }
03026          /*! \todo XXX If there's no Content-Length or if the content-length and what
03027                we receive is not the same - we should generate an error */
03028 
03029          req.socket.tcptls_session = tcptls_session;
03030          handle_request_do(&req, &tcptls_session->remote_address);
03031       }
03032 
03033       if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
03034          enum sip_tcptls_alert alert;
03035          struct tcptls_packet *packet;
03036 
03037          fds[1].revents = 0;
03038 
03039          if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
03040             ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
03041             continue;
03042          }
03043 
03044          switch (alert) {
03045          case TCPTLS_ALERT_STOP:
03046             goto cleanup;
03047          case TCPTLS_ALERT_DATA:
03048             ao2_lock(me);
03049             if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
03050                ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty");
03051             } else if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
03052                ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
03053             }
03054 
03055             if (packet) {
03056                ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
03057             }
03058             ao2_unlock(me);
03059             break;
03060          default:
03061             ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
03062          }
03063       }
03064    }
03065 
03066    ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
03067 
03068 cleanup:
03069    if (me) {
03070       ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
03071       ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
03072    }
03073    deinit_req(&reqcpy);
03074    deinit_req(&req);
03075 
03076    /* if client, we own the parent session arguments and must decrement ref */
03077    if (ca) {
03078       ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
03079    }
03080 
03081    if (tcptls_session) {
03082       ast_mutex_lock(&tcptls_session->lock);
03083       if (tcptls_session->f) {
03084          fclose(tcptls_session->f);
03085          tcptls_session->f = NULL;
03086       }
03087       if (tcptls_session->fd != -1) {
03088          close(tcptls_session->fd);
03089          tcptls_session->fd = -1;
03090       }
03091       tcptls_session->parent = NULL;
03092       ast_mutex_unlock(&tcptls_session->lock);
03093 
03094       ao2_ref(tcptls_session, -1);
03095       tcptls_session = NULL;
03096    }
03097    return NULL;
03098 }
03099 
03100 /* this func is used with ao2_callback to unlink/delete all marked
03101    peers */
03102 static int peer_is_marked(void *peerobj, void *arg, int flags)
03103 {
03104    struct sip_peer *peer = peerobj;
03105    if (peer->the_mark && peer->pokeexpire != -1) {
03106       AST_SCHED_DEL(sched, peer->pokeexpire);
03107    }
03108    return peer->the_mark ? CMP_MATCH : 0;
03109 }
03110 
03111 
03112 /* \brief Unlink all marked peers from ao2 containers */
03113 static void unlink_marked_peers_from_tables(void)
03114 {
03115    ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, NULL,
03116                   "initiating callback to remove marked peers");
03117    ao2_t_callback(peers_by_ip, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, NULL,
03118                   "initiating callback to remove marked peers");
03119 }
03120 
03121 /* \brief Unlink single peer from all ao2 containers */
03122 static void unlink_peer_from_tables(struct sip_peer *peer)
03123 {
03124    ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
03125    if (peer->addr.sin_addr.s_addr) {
03126       ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
03127    }
03128 }
03129 
03130 /*!
03131  * helper functions to unreference various types of objects.
03132  * By handling them this way, we don't have to declare the
03133  * destructor on each call, which removes the chance of errors.
03134  */
03135 static void *unref_peer(struct sip_peer *peer, char *tag)
03136 {
03137    ao2_t_ref(peer, -1, tag);
03138    return NULL;
03139 }
03140 
03141 static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
03142 {
03143    ao2_t_ref(peer, 1, tag);
03144    return peer;
03145 }
03146 
03147 /*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
03148  *
03149  * This function sets pvt's outboundproxy pointer to the one referenced
03150  * by the proxy parameter. Because proxy may be a refcounted object, and
03151  * because pvt's old outboundproxy may also be a refcounted object, we need
03152  * to maintain the proper refcounts.
03153  *
03154  * \param pvt The sip_pvt for which we wish to set the outboundproxy
03155  * \param proxy The sip_proxy which we will point pvt towards.
03156  * \return Returns void
03157  */
03158 static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
03159 {
03160    struct sip_proxy *old_obproxy = pvt->outboundproxy;
03161    /* The sip_cfg.outboundproxy is statically allocated, and so
03162     * we don't ever need to adjust refcounts for it
03163     */
03164    if (proxy && proxy != &sip_cfg.outboundproxy) {
03165       ao2_ref(proxy, +1);
03166    }
03167    pvt->outboundproxy = proxy;
03168    if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
03169       ao2_ref(old_obproxy, -1);
03170    }
03171 }
03172 
03173 /*!
03174  * \brief Unlink a dialog from the dialogs container, as well as any other places
03175  * that it may be currently stored.
03176  *
03177  * \note A reference to the dialog must be held before calling this function, and this
03178  * function does not release that reference.
03179  */
03180 static void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist)
03181 {
03182    struct sip_pkt *cp;
03183 
03184    dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
03185 
03186    ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
03187 
03188    /* Unlink us from the owner (channel) if we have one */
03189    if (dialog->owner) {
03190       if (lockowner)
03191          ast_channel_lock(dialog->owner);
03192       ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
03193       dialog->owner->tech_pvt = dialog_unref(dialog->owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
03194       if (lockowner)
03195          ast_channel_unlock(dialog->owner);
03196    }
03197    if (dialog->registry) {
03198       if (dialog->registry->call == dialog)
03199          dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
03200       dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
03201    }
03202    if (dialog->stateid > -1) {
03203       ast_extension_state_del(dialog->stateid, NULL);
03204       dialog_unref(dialog, "removing extension_state, should unref the associated dialog ptr that was stored there.");
03205       dialog->stateid = -1; /* shouldn't we 'zero' this out? */
03206    }
03207    /* Remove link from peer to subscription of MWI */
03208    if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog)
03209       dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
03210    if (dialog->relatedpeer && dialog->relatedpeer->call == dialog)
03211       dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
03212 
03213    /* remove all current packets in this dialog */
03214    while((cp = dialog->packets)) {
03215       dialog->packets = dialog->packets->next;
03216       AST_SCHED_DEL(sched, cp->retransid);
03217       dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
03218       if (cp->data) {
03219          ast_free(cp->data);
03220       }
03221       ast_free(cp);
03222    }
03223 
03224    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"));
03225 
03226    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"));
03227    
03228    if (dialog->autokillid > -1)
03229       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"));
03230 
03231    if (dialog->request_queue_sched_id > -1) {
03232       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"));
03233    }
03234 
03235    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"));
03236 
03237    if (dialog->t38id > -1) {
03238       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"));
03239    }
03240 
03241    dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
03242    return NULL;
03243 }
03244 
03245 static void *registry_unref(struct sip_registry *reg, char *tag)
03246 {
03247    ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
03248    ASTOBJ_UNREF(reg, sip_registry_destroy);
03249    return NULL;
03250 }
03251 
03252 /*! \brief Add object reference to SIP registry */
03253 static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
03254 {
03255    ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
03256    return ASTOBJ_REF(reg); /* Add pointer to registry in packet */
03257 }
03258 
03259 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
03260 static struct ast_udptl_protocol sip_udptl = {
03261    type: "SIP",
03262    get_udptl_info: sip_get_udptl_peer,
03263    set_udptl_peer: sip_set_udptl_peer,
03264 };
03265 
03266 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03267    __attribute__((format(printf, 2, 3)));
03268 
03269 
03270 /*! \brief Convert transfer status to string */
03271 static const char *referstatus2str(enum referstatus rstatus)
03272 {
03273    return map_x_s(referstatusstrings, rstatus, "");
03274 }
03275 
03276 static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
03277 {
03278    append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
03279    pvt->needdestroy = 1;
03280 }
03281 
03282 /*! \brief Initialize the initital request packet in the pvt structure.
03283    This packet is used for creating replies and future requests in
03284    a dialog */
03285 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
03286 {
03287    if (p->initreq.headers)
03288       ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
03289    else
03290       ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
03291    /* Use this as the basis */
03292    copy_request(&p->initreq, req);
03293    parse_request(&p->initreq);
03294    if (req->debug)
03295       ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
03296 }
03297 
03298 /*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
03299 static void sip_alreadygone(struct sip_pvt *dialog)
03300 {
03301    ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
03302    dialog->alreadygone = 1;
03303 }
03304 
03305 /*! Resolve DNS srv name or host name in a sip_proxy structure */
03306 static int proxy_update(struct sip_proxy *proxy)
03307 {
03308    /* if it's actually an IP address and not a name,
03309            there's no need for a managed lookup */
03310    if (!inet_aton(proxy->name, &proxy->ip.sin_addr)) {
03311       /* Ok, not an IP address, then let's check if it's a domain or host */
03312       /* XXX Todo - if we have proxy port, don't do SRV */
03313       if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
03314          ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
03315          return FALSE;
03316       }
03317    }
03318    proxy->last_dnsupdate = time(NULL);
03319    return TRUE;
03320 }
03321 
03322 /*! \brief converts ascii port to int representation. If no
03323  *  pt buffer is provided or the pt has errors when being converted
03324  *  to an int value, the port provided as the standard is used.
03325  */
03326 static int port_str2int(const char *pt, unsigned int standard)
03327 {
03328    int port = standard;
03329    if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
03330       port = standard;
03331    }
03332 
03333    return port;
03334 }
03335 
03336 /*! \brief Allocate and initialize sip proxy */
03337 static struct sip_proxy *proxy_allocate(char *name, char *port, int force)
03338 {
03339    struct sip_proxy *proxy;
03340 
03341    if (ast_strlen_zero(name)) {
03342       return NULL;
03343    }
03344 
03345    proxy = ao2_alloc(sizeof(*proxy), NULL);
03346    if (!proxy)
03347       return NULL;
03348    proxy->force = force;
03349    ast_copy_string(proxy->name, name, sizeof(proxy->name));
03350    proxy->ip.sin_port = htons(port_str2int(port, STANDARD_SIP_PORT));
03351    proxy->ip.sin_family = AF_INET;
03352    proxy_update(proxy);
03353    return proxy;
03354 }
03355 
03356 /*! \brief Get default outbound proxy or global proxy */
03357 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
03358 {
03359    if (peer && peer->outboundproxy) {
03360       if (sipdebug)
03361          ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
03362       append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
03363       return peer->outboundproxy;
03364    }
03365    if (sip_cfg.outboundproxy.name[0]) {
03366       if (sipdebug)
03367          ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
03368       append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
03369       return &sip_cfg.outboundproxy;
03370    }
03371    if (sipdebug)
03372       ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
03373    return NULL;
03374 }
03375 
03376 /*! \brief returns true if 'name' (with optional trailing whitespace)
03377  * matches the sip method 'id'.
03378  * Strictly speaking, SIP methods are case SENSITIVE, but we do
03379  * a case-insensitive comparison to be more tolerant.
03380  * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
03381  */
03382 static int method_match(enum sipmethod id, const char *name)
03383 {
03384    int len = strlen(sip_methods[id].text);
03385    int l_name = name ? strlen(name) : 0;
03386    /* true if the string is long enough, and ends with whitespace, and matches */
03387    return (l_name >= len && name[len] < 33 &&
03388       !strncasecmp(sip_methods[id].text, name, len));
03389 }
03390 
03391 /*! \brief  find_sip_method: Find SIP method from header */
03392 static int find_sip_method(const char *msg)
03393 {
03394    int i, res = 0;
03395    
03396    if (ast_strlen_zero(msg))
03397       return 0;
03398    for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
03399       if (method_match(i, msg))
03400          res = sip_methods[i].id;
03401    }
03402    return res;
03403 }
03404 
03405 /*! \brief Parse supported header in incoming packet */
03406 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
03407 {
03408    char *next, *sep;
03409    char *temp;
03410    unsigned int profile = 0;
03411    int i, found;
03412 
03413    if (ast_strlen_zero(supported) )
03414       return 0;
03415    temp = ast_strdupa(supported);
03416 
03417    if (sipdebug)
03418       ast_debug(3, "Begin: parsing SIP \"Supported: %s\"\n", supported);
03419 
03420    for (next = temp; next; next = sep) {
03421       found = FALSE;
03422       if ( (sep = strchr(next, ',')) != NULL)
03423          *sep++ = '\0';
03424       next = ast_skip_blanks(next);
03425       if (sipdebug)
03426          ast_debug(3, "Found SIP option: -%s-\n", next);
03427       for (i = 0; i < ARRAY_LEN(sip_options); i++) {
03428          if (!strcasecmp(next, sip_options[i].text)) {
03429             profile |= sip_options[i].id;
03430             found = TRUE;
03431             if (sipdebug)
03432                ast_debug(3, "Matched SIP option: %s\n", next);
03433             break;
03434          }
03435       }
03436 
03437       /* This function is used to parse both Suported: and Require: headers.
03438       Let the caller of this function know that an unknown option tag was 
03439       encountered, so that if the UAC requires it then the request can be 
03440       rejected with a 420 response. */
03441       if (!found)
03442          profile |= SIP_OPT_UNKNOWN;
03443 
03444       if (!found && sipdebug) {
03445          if (!strncasecmp(next, "x-", 2))
03446             ast_debug(3, "Found private SIP option, not supported: %s\n", next);
03447          else
03448             ast_debug(3, "Found no match for SIP option: %s (Please file bug report!)\n", next);
03449       }
03450    }
03451 
03452    if (pvt)
03453       pvt->sipoptions = profile;
03454    return profile;
03455 }
03456 
03457 /*! \brief See if we pass debug IP filter */
03458 static inline int sip_debug_test_addr(const struct sockaddr_in *addr) 
03459 {
03460    if (!sipdebug)
03461       return 0;
03462    if (debugaddr.sin_addr.s_addr) {
03463       if (((ntohs(debugaddr.sin_port) != 0)
03464          && (debugaddr.sin_port != addr->sin_port))
03465          || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
03466          return 0;
03467    }
03468    return 1;
03469 }
03470 
03471 /*! \brief The real destination address for a write */
03472 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
03473 {
03474    if (p->outboundproxy)
03475       return &p->outboundproxy->ip;
03476 
03477    return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
03478 }
03479 
03480 /*! \brief Display SIP nat mode */
03481 static const char *sip_nat_mode(const struct sip_pvt *p)
03482 {
03483    return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
03484 }
03485 
03486 /*! \brief Test PVT for debugging output */
03487 static inline int sip_debug_test_pvt(struct sip_pvt *p) 
03488 {
03489    if (!sipdebug)
03490       return 0;
03491    return sip_debug_test_addr(sip_real_dst(p));
03492 }
03493 
03494 /*! \brief Return int representing a bit field of transport types found in const char *transport */
03495 static int get_transport_str2enum(const char *transport)
03496 {
03497    int res = 0;
03498 
03499    if (ast_strlen_zero(transport)) {
03500       return res;
03501    }
03502 
03503    if (!strcasecmp(transport, "udp")) {
03504       res |= SIP_TRANSPORT_UDP;
03505    }
03506    if (!strcasecmp(transport, "tcp")) {
03507       res |= SIP_TRANSPORT_TCP;
03508    }
03509    if (!strcasecmp(transport, "tls")) {
03510       res |= SIP_TRANSPORT_TLS;
03511    }
03512 
03513    return res;
03514 }
03515 
03516 /*! \brief Return configuration of transports for a device */
03517 static inline const char *get_transport_list(unsigned int transports) {
03518    switch (transports) {
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       case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
03526          return "TCP,UDP";
03527       case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
03528          return "TLS,UDP";
03529       case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
03530          return "TLS,TCP";
03531       default:
03532          return transports ? 
03533             "TLS,TCP,UDP" : "UNKNOWN"; 
03534    }
03535 }
03536 
03537 /*! \brief Return transport as string */
03538 static inline const char *get_transport(enum sip_transport t)
03539 {
03540    switch (t) {
03541    case SIP_TRANSPORT_UDP:
03542       return "UDP";
03543    case SIP_TRANSPORT_TCP:
03544       return "TCP";
03545    case SIP_TRANSPORT_TLS:
03546       return "TLS";
03547    }
03548 
03549    return "UNKNOWN";
03550 }
03551 
03552 /*! \brief Return protocol string for srv dns query */
03553 static inline const char *get_srv_protocol(enum sip_transport t)
03554 {
03555    switch (t) {
03556    case SIP_TRANSPORT_UDP:
03557       return "udp";
03558    case SIP_TRANSPORT_TLS:
03559    case SIP_TRANSPORT_TCP:
03560       return "tcp";
03561    }
03562 
03563    return "udp";
03564 }
03565 
03566 /*! \brief Return service string for srv dns query */
03567 static inline const char *get_srv_service(enum sip_transport t)
03568 {
03569    switch (t) {
03570    case SIP_TRANSPORT_TCP:
03571    case SIP_TRANSPORT_UDP:
03572       return "sip";
03573    case SIP_TRANSPORT_TLS:
03574       return "sips";
03575    }
03576    return "sip";
03577 }
03578 
03579 /*! \brief Return transport of dialog.
03580    \note this is based on a false assumption. We don't always use the
03581    outbound proxy for all requests in a dialog. It depends on the
03582    "force" parameter. The FIRST request is always sent to the ob proxy.
03583    \todo Fix this function to work correctly
03584 */
03585 static inline const char *get_transport_pvt(struct sip_pvt *p)
03586 {
03587    if (p->outboundproxy && p->outboundproxy->transport) {
03588       set_socket_transport(&p->socket, p->outboundproxy->transport);
03589    }
03590 
03591    return get_transport(p->socket.type);
03592 }
03593 
03594 /*! \brief Transmit SIP message 
03595    Sends a SIP request or response on a given socket (in the pvt)
03596    Called by retrans_pkt, send_request, send_response and 
03597    __sip_reliable_xmit
03598 */
03599 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len)
03600 {
03601    int res = 0;
03602    const struct sockaddr_in *dst = sip_real_dst(p);
03603 
03604    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));
03605 
03606    if (sip_prepare_socket(p) < 0)
03607       return XMIT_ERROR;
03608 
03609    if (p->socket.type == SIP_TRANSPORT_UDP) {
03610       res = sendto(p->socket.fd, data->str, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
03611    } else if (p->socket.tcptls_session) {
03612       res = sip_tcptls_write(p->socket.tcptls_session, data->str, len);
03613    } else {
03614       ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
03615       return XMIT_ERROR;
03616    }
03617 
03618    if (res == -1) {
03619       switch (errno) {
03620       case EBADF:       /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
03621       case EHOSTUNREACH:   /* Host can't be reached */
03622       case ENETDOWN:       /* Inteface down */
03623       case ENETUNREACH: /* Network failure */
03624       case ECONNREFUSED:      /* ICMP port unreachable */ 
03625          res = XMIT_ERROR; /* Don't bother with trying to transmit again */
03626       }
03627    }
03628    if (res != len)
03629       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));
03630 
03631    return res;
03632 }
03633 
03634 /*! \brief Build a Via header for a request */
03635 static void build_via(struct sip_pvt *p)
03636 {
03637    /* Work around buggy UNIDEN UIP200 firmware */
03638    const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
03639 
03640    /* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
03641    snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s:%d;branch=z9hG4bK%08x%s",
03642        get_transport_pvt(p),
03643        ast_inet_ntoa(p->ourip.sin_addr),
03644        ntohs(p->ourip.sin_port), (int) p->branch, rport);
03645 }
03646 
03647 /*! \brief NAT fix - decide which IP address to use for Asterisk server?
03648  *
03649  * Using the localaddr structure built up with localnet statements in sip.conf
03650  * apply it to their address to see if we need to substitute our
03651  * externip or can get away with our internal bindaddr
03652  * 'us' is always overwritten.
03653  */
03654 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p)
03655 {
03656    struct sockaddr_in theirs;
03657    /* Set want_remap to non-zero if we want to remap 'us' to an externally
03658     * reachable IP address and port. This is done if:
03659     * 1. we have a localaddr list (containing 'internal' addresses marked
03660     *    as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
03661     *    and AST_SENSE_ALLOW on 'external' ones);
03662     * 2. either stunaddr or externip is set, so we know what to use as the
03663     *    externally visible address;
03664     * 3. the remote address, 'them', is external;
03665     * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
03666     *    when passed to ast_apply_ha() so it does need to be remapped.
03667     *    This fourth condition is checked later.
03668     */
03669    int want_remap;
03670 
03671    *us = internip;      /* starting guess for the internal address */
03672    /* now ask the system what would it use to talk to 'them' */
03673    ast_ouraddrfor(them, &us->sin_addr);
03674    theirs.sin_addr = *them;
03675 
03676    want_remap = localaddr &&
03677       (externip.sin_addr.s_addr || stunaddr.sin_addr.s_addr) &&
03678       ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
03679 
03680    if (want_remap &&
03681        (!sip_cfg.matchexterniplocally || !ast_apply_ha(localaddr, us)) ) {
03682       /* if we used externhost or stun, see if it is time to refresh the info */
03683       if (externexpire && time(NULL) >= externexpire) {
03684          if (stunaddr.sin_addr.s_addr) {
03685             ast_stun_request(sipsock, &stunaddr, NULL, &externip);
03686          } else {
03687             if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
03688                ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
03689          }
03690          externexpire = time(NULL) + externrefresh;
03691       }
03692       if (externip.sin_addr.s_addr)
03693          *us = externip;
03694       else
03695          ast_log(LOG_WARNING, "stun failed\n");
03696       ast_debug(1, "Target address %s is not local, substituting externip\n", 
03697          ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
03698    } else if (p) {
03699       /* no remapping, but we bind to a specific address, so use it. */
03700       switch (p->socket.type) {
03701       case SIP_TRANSPORT_TCP:
03702          if (sip_tcp_desc.local_address.sin_addr.s_addr) {
03703             *us = sip_tcp_desc.local_address;
03704          } else {
03705             us->sin_port = sip_tcp_desc.local_address.sin_port;
03706          }
03707          break;
03708       case SIP_TRANSPORT_TLS:
03709          if (sip_tls_desc.local_address.sin_addr.s_addr) {
03710             *us = sip_tls_desc.local_address;
03711          } else {
03712             us->sin_port = sip_tls_desc.local_address.sin_port;
03713          }
03714             break;
03715       case SIP_TRANSPORT_UDP:
03716          /* fall through on purpose */
03717       default:
03718          if (bindaddr.sin_addr.s_addr) {
03719             *us = bindaddr;
03720          }
03721       }
03722    } else if (bindaddr.sin_addr.s_addr) {
03723       *us = bindaddr;
03724    }
03725    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));
03726 }
03727 
03728 /*! \brief Append to SIP dialog history with arg list  */
03729 static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
03730 {
03731    char buf[80], *c = buf; /* max history length */
03732    struct sip_history *hist;
03733    int l;
03734 
03735    vsnprintf(buf, sizeof(buf), fmt, ap);
03736    strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
03737    l = strlen(buf) + 1;
03738    if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
03739       return;
03740    if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
03741       ast_free(hist);
03742       return;
03743    }
03744    memcpy(hist->event, buf, l);
03745    if (p->history_entries == MAX_HISTORY_ENTRIES) {
03746       struct sip_history *oldest;
03747       oldest = AST_LIST_REMOVE_HEAD(p->history, list);
03748       p->history_entries--;
03749       ast_free(oldest);
03750    }
03751    AST_LIST_INSERT_TAIL(p->history, hist, list);
03752    p->history_entries++;
03753 }
03754 
03755 /*! \brief Append to SIP dialog history with arg list  */
03756 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03757 {
03758    va_list ap;
03759 
03760    if (!p)
03761       return;
03762 
03763    if (!p->do_history && !recordhistory && !dumphistory)
03764       return;
03765 
03766    va_start(ap, fmt);
03767    append_history_va(p, fmt, ap);
03768    va_end(ap);
03769 
03770    return;
03771 }
03772 
03773 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
03774 static int retrans_pkt(const void *data)
03775 {
03776    struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
03777    int reschedule = DEFAULT_RETRANS;
03778    int xmitres = 0;
03779 
03780    /* Lock channel PVT */
03781    sip_pvt_lock(pkt->owner);
03782 
03783    if (pkt->retrans < MAX_RETRANS) {
03784       pkt->retrans++;
03785       if (!pkt->timer_t1) {   /* Re-schedule using timer_a and timer_t1 */
03786          if (sipdebug)
03787             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);
03788       } else {
03789          int siptimer_a;
03790 
03791          if (sipdebug)
03792             ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
03793          if (!pkt->timer_a)
03794             pkt->timer_a = 2 ;
03795          else
03796             pkt->timer_a = 2 * pkt->timer_a;
03797 
03798          /* For non-invites, a maximum of 4 secs */
03799          siptimer_a = pkt->timer_t1 * pkt->timer_a;   /* Double each time */
03800          if (pkt->method != SIP_INVITE && siptimer_a > 4000)
03801             siptimer_a = 4000;
03802 
03803          /* Reschedule re-transmit */
03804          reschedule = siptimer_a;
03805          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);
03806       }
03807 
03808       if (sip_debug_test_pvt(pkt->owner)) {
03809          const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
03810          ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
03811             pkt->retrans, sip_nat_mode(pkt->owner),
03812             ast_inet_ntoa(dst->sin_addr),
03813             ntohs(dst->sin_port), pkt->data->str);
03814       }
03815 
03816       append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
03817       xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
03818       if (xmitres == XMIT_ERROR) {
03819          ast_log(LOG_WARNING, "Network error on retransmit in dialog %s\n", pkt->owner->callid);
03820       } else {
03821          sip_pvt_unlock(pkt->owner);
03822          return  reschedule;
03823       }
03824    }
03825    /* Too many retries */
03826    if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
03827       if (pkt->is_fatal || sipdebug)   /* Tell us if it's critical or if we're debugging */
03828          ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s) -- See doc/sip-retransmit.txt.\n",
03829             pkt->owner->callid, pkt->seqno,
03830             pkt->is_fatal ? "Critical" : "Non-critical", pkt->is_resp ? "Response" : "Request");
03831    } else if (pkt->method == SIP_OPTIONS && sipdebug) {
03832          ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s)  -- See doc/sip-retransmit.txt.\n", pkt->owner->callid);
03833 
03834    }
03835    if (xmitres == XMIT_ERROR) {
03836       ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
03837       append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03838    } else {
03839       append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03840    }
03841    pkt->retransid = -1;
03842 
03843    if (pkt->is_fatal) {
03844       while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
03845          sip_pvt_unlock(pkt->owner);   /* SIP_PVT, not channel */
03846          usleep(1);
03847          sip_pvt_lock(pkt->owner);
03848       }
03849 
03850       if (pkt->owner->owner && !pkt->owner->owner->hangupcause)
03851          pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
03852 
03853       if (pkt->owner->owner) {
03854          sip_alreadygone(pkt->owner);
03855          ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet (see doc/sip-retransmit.txt).\n", pkt->owner->callid);
03856          ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_PROTOCOL_ERROR);
03857          ast_channel_unlock(pkt->owner->owner);
03858       } else {
03859          /* If no channel owner, destroy now */
03860 
03861          /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
03862          if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
03863             pvt_set_needdestroy(pkt->owner, "no response to critical packet");
03864             sip_alreadygone(pkt->owner);
03865             append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
03866          }
03867       }
03868    }
03869 
03870    if (pkt->method == SIP_BYE) {
03871       /* We're not getting answers on SIP BYE's.  Tear down the call anyway. */
03872       if (pkt->owner->owner)
03873          ast_channel_unlock(pkt->owner->owner);
03874       append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
03875       pvt_set_needdestroy(pkt->owner, "no response to BYE");
03876    }
03877 
03878    /* Remove the packet */
03879    for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
03880       if (cur == pkt) {
03881          UNLINK(cur, pkt->owner->packets, prev);
03882          sip_pvt_unlock(pkt->owner);
03883          if (pkt->owner)
03884             pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03885          if (pkt->data)
03886             ast_free(pkt->data);
03887          pkt->data = NULL;
03888          ast_free(pkt);
03889          return 0;
03890       }
03891    }
03892    /* error case */
03893    ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
03894    sip_pvt_unlock(pkt->owner);
03895    return 0;
03896 }
03897 
03898 /*! \brief Transmit packet with retransmits 
03899    \return 0 on success, -1 on failure to allocate packet 
03900 */
03901 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)
03902 {
03903    struct sip_pkt *pkt = NULL;
03904    int siptimer_a = DEFAULT_RETRANS;
03905    int xmitres = 0;
03906    int respid;
03907 
03908    if (sipmethod == SIP_INVITE) {
03909       /* Note this is a pending invite */
03910       p->pendinginvite = seqno;
03911    }
03912 
03913    /* If the transport is something reliable (TCP or TLS) then don't really send this reliably */
03914    /* I removed the code from retrans_pkt that does the same thing so it doesn't get loaded into the scheduler */
03915    /*! \todo According to the RFC some packets need to be retransmitted even if its TCP, so this needs to get revisited */
03916    if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
03917       xmitres = __sip_xmit(p, data, len); /* Send packet */
03918       if (xmitres == XMIT_ERROR) {  /* Serious network trouble, no need to try again */
03919          append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
03920          return AST_FAILURE;
03921       } else {
03922          return AST_SUCCESS;
03923       }
03924    }
03925 
03926    if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
03927       return AST_FAILURE;
03928    /* copy data, add a terminator and save length */
03929    if (!(pkt->data = ast_str_create(len))) {
03930       ast_free(pkt);
03931       return AST_FAILURE;
03932    }
03933    ast_str_set(&pkt->data, 0, "%s%s", data->str, "\0");
03934    pkt->packetlen = len;
03935    /* copy other parameters from the caller */
03936    pkt->method = sipmethod;
03937    pkt->seqno = seqno;
03938    pkt->is_resp = resp;
03939    pkt->is_fatal = fatal;
03940    pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
03941    pkt->next = p->packets;
03942    p->packets = pkt; /* Add it to the queue */
03943    if (resp) {
03944       /* Parse out the response code */
03945       if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
03946          pkt->response_code = respid;
03947       }
03948    }
03949    pkt->timer_t1 = p->timer_t1;  /* Set SIP timer T1 */
03950    pkt->retransid = -1;
03951    if (pkt->timer_t1)
03952       siptimer_a = pkt->timer_t1 * 2;
03953 
03954    /* Schedule retransmission */
03955    AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
03956    if (sipdebug)
03957       ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id  #%d\n", pkt->retransid);
03958 
03959    xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);   /* Send packet */
03960 
03961    if (xmitres == XMIT_ERROR) {  /* Serious network trouble, no need to try again */
03962       append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03963       ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
03964       AST_SCHED_DEL(sched, pkt->retransid);
03965       p->packets = pkt->next;
03966       pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03967       ast_free(pkt->data);
03968       ast_free(pkt);
03969       return AST_FAILURE;
03970    } else {
03971       return AST_SUCCESS;
03972    }
03973 }
03974 
03975 /*! \brief Kill a SIP dialog (called only by the scheduler)
03976  * The scheduler has a reference to this dialog when p->autokillid != -1,
03977  * and we are called using that reference. So if the event is not
03978  * rescheduled, we need to call dialog_unref().
03979  */
03980 static int __sip_autodestruct(const void *data)
03981 {
03982    struct sip_pvt *p = (struct sip_pvt *)data;
03983 
03984    /* If this is a subscription, tell the phone that we got a timeout */
03985    if (p->subscribed) {
03986       transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);  /* Send last notification */
03987       p->subscribed = NONE;
03988       append_history(p, "Subscribestatus", "timeout");
03989       ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
03990       return 10000;  /* Reschedule this destruction so that we know that it's gone */
03991    }
03992 
03993    /* If there are packets still waiting for delivery, delay the destruction */
03994    if (p->packets) {
03995       if (!p->needdestroy) {
03996          char method_str[31];
03997          ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
03998          append_history(p, "ReliableXmit", "timeout");
03999          if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
04000             if (method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
04001                pvt_set_needdestroy(p, "autodestruct");
04002             }
04003          }
04004          return 10000;
04005       } else {
04006          /* They've had their chance to respond. Time to bail */
04007          __sip_pretend_ack(p);
04008       }
04009    }
04010 
04011    /* Reset schedule ID */
04012    p->autokillid = -1;
04013 
04014 
04015    /*
04016     * Lock both the pvt and the channel safely so that we can queue up a frame.
04017     */
04018    sip_pvt_lock(p);
04019    while (p->owner && ast_channel_trylock(p->owner)) {
04020       sip_pvt_unlock(p);
04021       sched_yield();
04022       sip_pvt_lock(p);
04023    }
04024 
04025    if (p->owner) {
04026       ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
04027       ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
04028       ast_channel_unlock(p->owner);
04029    } else if (p->refer && !p->alreadygone) {
04030       ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
04031       transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
04032       append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
04033       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
04034    } else {
04035       append_history(p, "AutoDestroy", "%s", p->callid);
04036       ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
04037       dialog_unlink_all(p, TRUE, TRUE); /* once it's unlinked and unrefd everywhere, it'll be freed automagically */
04038       /* dialog_unref(p, "unref dialog-- no other matching conditions"); -- unlink all now should finish off the dialog's references and free it. */
04039       /* sip_destroy(p); */      /* Go ahead and destroy dialog. All attempts to recover is done */
04040       /* sip_destroy also absorbs the reference */
04041    }
04042 
04043    sip_pvt_unlock(p);
04044 
04045    dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
04046 
04047    return 0;
04048 }
04049 
04050 /*! \brief Schedule destruction of SIP dialog */
04051 static void sip_scheddestroy(struct sip_pvt *p, int ms)
04052 {
04053    if (ms < 0) {
04054       if (p->timer_t1 == 0) {
04055          p->timer_t1 = global_t1;   /* Set timer T1 if not set (RFC 3261) */
04056          p->timer_b = global_timer_b;  /* Set timer B if not set (RFC 3261) */
04057       }
04058       ms = p->timer_t1 * 64;
04059    }
04060    if (sip_debug_test_pvt(p))
04061       ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
04062    if (sip_cancel_destroy(p))
04063       ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
04064 
04065    if (p->do_history)
04066       append_history(p, "SchedDestroy", "%d ms", ms);
04067    p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
04068 
04069    if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0)
04070       stop_session_timer(p);
04071 }
04072 
04073 /*! \brief Cancel destruction of SIP dialog.
04074  * Be careful as this also absorbs the reference - if you call it
04075  * from within the scheduler, this might be the last reference.
04076  */
04077 static int sip_cancel_destroy(struct sip_pvt *p)
04078 {
04079    int res = 0;
04080    if (p->autokillid > -1) {
04081       int res3;
04082 
04083       if (!(res3 = ast_sched_del(sched, p->autokillid))) {
04084          append_history(p, "CancelDestroy", "");
04085          p->autokillid = -1;
04086          dialog_unref(p, "dialog unrefd because autokillid is de-sched'd");
04087       }
04088    }
04089    return res;
04090 }
04091 
04092 /*! \brief Acknowledges receipt of a packet and stops retransmission 
04093  * called with p locked*/
04094 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
04095 {
04096    struct sip_pkt *cur, *prev = NULL;
04097    const char *msg = "Not Found";   /* used only for debugging */
04098    int res = FALSE;
04099 
04100    /* If we have an outbound proxy for this dialog, then delete it now since
04101      the rest of the requests in this dialog needs to follow the routing.
04102      If obforcing is set, we will keep the outbound proxy during the whole
04103      dialog, regardless of what the SIP rfc says
04104    */
04105    if (p->outboundproxy && !p->outboundproxy->force){
04106       ref_proxy(p, NULL);
04107    }
04108 
04109    for (cur = p->packets; cur; prev = cur, cur = cur->next) {
04110       if (cur->seqno != seqno || cur->is_resp != resp)
04111          continue;
04112       if (cur->is_resp || cur->method == sipmethod) {
04113          res = TRUE;
04114          msg = "Found";
04115          if (!resp && (seqno == p->pendinginvite)) {
04116             ast_debug(1, "Acked pending invite %d\n", p->pendinginvite);
04117             p->pendinginvite = 0;
04118          }
04119          if (cur->retransid > -1) {
04120             if (sipdebug)
04121                ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
04122          }
04123          /* This odd section is designed to thwart a 
04124           * race condition in the packet scheduler. There are
04125           * two conditions under which deleting the packet from the
04126           * scheduler can fail.
04127           *
04128           * 1. The packet has been removed from the scheduler because retransmission
04129           * is being attempted. The problem is that if the packet is currently attempting
04130           * retransmission and we are at this point in the code, then that MUST mean
04131           * that retrans_pkt is waiting on p's lock. Therefore we will relinquish the
04132           * lock temporarily to allow retransmission.
04133           *
04134           * 2. The packet has reached its maximum number of retransmissions and has
04135           * been permanently removed from the packet scheduler. If this is the case, then
04136           * the packet's retransid will be set to -1. The atomicity of the setting and checking
04137           * of the retransid to -1 is ensured since in both cases p's lock is held.
04138           */
04139          while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
04140             sip_pvt_unlock(p);
04141             usleep(1);
04142             sip_pvt_lock(p);
04143          }
04144          UNLINK(cur, p->packets, prev);
04145          dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
04146          if (cur->data)
04147             ast_free(cur->data);
04148          ast_free(cur);
04149          break;
04150       }
04151    }
04152    ast_debug(1, "Stopping retransmission on '%s' of %s %d: Match %s\n",
04153       p->callid, resp ? "Response" : "Request", seqno, msg);
04154    return res;
04155 }
04156 
04157 /*! \brief Pretend to ack all packets
04158  * called with p locked */
04159 static void __sip_pretend_ack(struct sip_pvt *p)
04160 {
04161    struct sip_pkt *cur = NULL;
04162 
04163    while (p->packets) {
04164       int method;
04165       if (cur == p->packets) {
04166          ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
04167          return;
04168       }
04169       cur = p->packets;
04170       method = (cur->method) ? cur->method : find_sip_method(cur->data->str);
04171       __sip_ack(p, cur->seqno, cur->is_resp, method);
04172    }
04173 }
04174 
04175 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
04176 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
04177 {
04178    struct sip_pkt *cur;
04179    int res = FALSE;
04180 
04181    for (cur = p->packets; cur; cur = cur->next) {
04182       if (cur->seqno == seqno && cur->is_resp == resp &&
04183          (cur->is_resp || method_match(sipmethod, cur->data->str))) {
04184          /* this is our baby */
04185          if (cur->retransid > -1) {
04186             if (sipdebug)
04187                ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
04188          }
04189          AST_SCHED_DEL(sched, cur->retransid);
04190          res = TRUE;
04191          break;
04192       }
04193    }
04194    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");
04195    return res;
04196 }
04197 
04198 
04199 /*! \brief Copy SIP request, parse it */
04200 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
04201 {
04202    copy_request(dst, src);
04203    parse_request(dst);
04204 }
04205 
04206 /*! \brief add a blank line if no body */
04207 static void add_blank(struct sip_request *req)
04208 {
04209    if (!req->lines) {
04210       /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
04211       ast_str_append(&req->data, 0, "\r\n");
04212       req->len = ast_str_strlen(req->data);
04213    }
04214 }
04215 
04216 static int send_provisional_keepalive_full(struct sip_pvt *pvt, int with_sdp)
04217 {
04218    const char *msg = NULL;
04219 
04220    if (!pvt->last_provisional || !strncasecmp(pvt->last_provisional, "100", 3)) {
04221       msg = "183 Session Progress";
04222    }
04223 
04224    if (pvt->invitestate < INV_COMPLETED) {
04225       if (with_sdp) {
04226          transmit_response_with_sdp(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq, XMIT_UNRELIABLE, FALSE);
04227       } else {
04228          transmit_response(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq);
04229       }
04230       return PROVIS_KEEPALIVE_TIMEOUT;
04231    }
04232 
04233    return 0;
04234 }
04235 
04236 static int send_provisional_keepalive(const void *data) {
04237    struct sip_pvt *pvt = (struct sip_pvt *) data;
04238 
04239    return send_provisional_keepalive_full(pvt, 0);
04240 }
04241 
04242 static int send_provisional_keepalive_with_sdp(const void *data) {
04243    struct sip_pvt *pvt = (void *)data;
04244 
04245    return send_provisional_keepalive_full(pvt, 1);
04246 }
04247 
04248 static void update_provisional_keepalive(struct sip_pvt *pvt, int with_sdp)
04249 {
04250    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"));
04251 
04252    pvt->provisional_keepalive_sched_id = ast_sched_add(sched, PROVIS_KEEPALIVE_TIMEOUT,
04253       with_sdp ? send_provisional_keepalive_with_sdp : send_provisional_keepalive, dialog_ref(pvt, "Increment refcount to pass dialog pointer to sched callback"));
04254 }
04255 
04256 /*! \brief Transmit response on SIP request*/
04257 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
04258 {
04259    int res;
04260 
04261    finalize_content(req);
04262    add_blank(req);
04263    if (sip_debug_test_pvt(p)) {
04264       const struct sockaddr_in *dst = sip_real_dst(p);
04265 
04266       ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
04267          reliable ? "Reliably " : "", sip_nat_mode(p),
04268          ast_inet_ntoa(dst->sin_addr),
04269          ntohs(dst->sin_port), req->data->str);
04270    }
04271    if (p->do_history) {
04272       struct sip_request tmp = { .rlPart1 = 0, };
04273       parse_copy(&tmp, req);
04274       append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), 
04275          (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlPart2) : sip_methods[tmp.method].text);
04276       deinit_req(&tmp);
04277    }
04278 
04279    /* If we are sending a final response to an INVITE, stop retransmitting provisional responses */
04280    if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
04281       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"));
04282    }
04283 
04284    res = (reliable) ?
04285        __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
04286       __sip_xmit(p, req->data, req->len);
04287    deinit_req(req);
04288    if (res > 0)
04289       return 0;
04290    return res;
04291 }
04292 
04293 /*! \brief Send SIP Request to the other part of the dialogue */
04294 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
04295 {
04296    int res;
04297 
04298    /* If we have an outbound proxy, reset peer address 
04299       Only do this once.
04300    */
04301    if (p->outboundproxy) {
04302       p->sa = p->outboundproxy->ip;
04303    }
04304 
04305    finalize_content(req);
04306    add_blank(req);
04307    if (sip_debug_test_pvt(p)) {
04308       if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
04309          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);
04310       else
04311          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);
04312    }
04313    if (p->do_history) {
04314       struct sip_request tmp = { .rlPart1 = 0, };
04315       parse_copy(&tmp, req);
04316       append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
04317       deinit_req(&tmp);
04318    }
04319    res = (reliable) ?
04320       __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
04321       __sip_xmit(p, req->data, req->len);
04322    deinit_req(req);
04323    return res;
04324 }
04325 
04326 /*! \brief Query an option on a SIP dialog */
04327 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
04328 {
04329    int res = -1;
04330    enum ast_t38_state state = T38_STATE_UNAVAILABLE;
04331    struct sip_pvt *p = (struct sip_pvt *) chan->tech_pvt;
04332 
04333    switch (option) {
04334    case AST_OPTION_T38_STATE:
04335       /* Make sure we got an ast_t38_state enum passed in */
04336       if (*datalen != sizeof(enum ast_t38_state)) {
04337          ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
04338          return -1;
04339       }
04340 
04341       sip_pvt_lock(p);
04342 
04343       /* 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 */
04344       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
04345          switch (p->t38.state) {
04346          case T38_LOCAL_REINVITE:
04347          case T38_PEER_REINVITE:
04348             state = T38_STATE_NEGOTIATING;
04349             break;
04350          case T38_ENABLED:
04351             state = T38_STATE_NEGOTIATED;
04352             break;
04353          default:
04354             state = T38_STATE_UNKNOWN;
04355          }
04356       }
04357 
04358       sip_pvt_unlock(p);
04359 
04360       *((enum ast_t38_state *) data) = state;
04361       res = 0;
04362 
04363       break;
04364    default:
04365       break;
04366    }
04367 
04368    return res;
04369 }
04370 
04371 /*! \brief Locate closing quote in a string, skipping escaped quotes.
04372  * optionally with a limit on the search.
04373  * start must be past the first quote.
04374  */
04375 static const char *find_closing_quote(const char *start, const char *lim)
04376 {
04377    char last_char = '\0';
04378    const char *s;
04379    for (s = start; *s && s != lim; last_char = *s++) {
04380       if (*s == '"' && last_char != '\\')
04381          break;
04382    }
04383    return s;
04384 }
04385 
04386 /*! \brief Pick out text in brackets from character string
04387    \return pointer to terminated stripped string
04388    \param tmp input string that will be modified
04389    Examples:
04390 \verbatim
04391    "foo" <bar> valid input, returns bar
04392    foo      returns the whole string
04393    < "foo ... >   returns the string between brackets
04394    < "foo...   bogus (missing closing bracket), returns the whole string
04395          XXX maybe should still skip the opening bracket
04396 \endverbatim
04397  */
04398 static char *get_in_brackets(char *tmp)
04399 {
04400    const char *parse = tmp;
04401    char *first_bracket;
04402 
04403    /*
04404     * Skip any quoted text until we find the part in brackets.
04405    * On any error give up and return the full string.
04406    */
04407    while ( (first_bracket = strchr(parse, '<')) ) {
04408       char *first_quote = strchr(parse, '"');
04409 
04410       if (!first_quote || first_quote > first_bracket)
04411          break; /* no need to look at quoted part */
04412       /* the bracket is within quotes, so ignore it */
04413       parse = find_closing_quote(first_quote + 1, NULL);
04414       if (!*parse) { /* not found, return full string ? */
04415          /* XXX or be robust and return in-bracket part ? */
04416          ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
04417          break;
04418       }
04419       parse++;
04420    }
04421    if (first_bracket) {
04422       char *second_bracket = strchr(first_bracket + 1, '>');
04423       if (second_bracket) {
04424          *second_bracket = '\0';
04425          tmp = first_bracket + 1;
04426       } else {
04427          ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
04428       }
04429    }
04430    
04431    return tmp;
04432 }
04433 
04434 /*! \brief * parses a URI in its components.
04435  *
04436  * \note 
04437  * - If scheme is specified, drop it from the top.
04438  * - If a component is not requested, do not split around it.
04439  * - Multiple scheme's can be specified ',' delimited. ex: "sip:,sips:"
04440  *
04441  * This means that if we don't have domain, we cannot split
04442  * name:pass and domain:port.
04443  * It is safe to call with ret_name, pass, domain, port
04444  * pointing all to the same place.
04445  * Init pointers to empty string so we never get NULL dereferencing.
04446  * Overwrites the string.
04447  * return 0 on success, other values on error.
04448  * \verbatim 
04449  * general form we are expecting is sip[s]:username[:password][;parameter]@host[:port][;...] 
04450  * \endverbatim
04451  * 
04452  */
04453 static int parse_uri(char *uri, const char *scheme,
04454    char **ret_name, char **pass, char **domain, char **port, char **options, char **transport)
04455 {
04456    char *name = NULL;
04457    int error = 0;
04458 
04459    /* init field as required */
04460    if (pass)
04461       *pass = "";
04462    if (port)
04463       *port = "";
04464    if (scheme) {
04465       int l;
04466       char *scheme2 = ast_strdupa(scheme);
04467       char *cur = strsep(&scheme2, ",");
04468       for (; !ast_strlen_zero(cur); cur = strsep(&scheme2, ",")) {
04469          l = strlen(cur);
04470          if (!strncasecmp(uri, cur, l)) {
04471             uri += l;
04472             break;
04473          }
04474       }
04475       if (ast_strlen_zero(cur)) {
04476          ast_debug(1, "No supported scheme found in '%s' using the scheme[s] %s\n", uri, scheme);
04477          error = -1;
04478       }
04479    }
04480    if (transport) {
04481       char *t, *type = "";
04482       *transport = "";
04483       if ((t = strstr(uri, "transport="))) {
04484          strsep(&t, "=");
04485          if ((type = strsep(&t, ";"))) {
04486             *transport = type;
04487          }
04488       }
04489    }
04490 
04491    if (!domain) {
04492       /* if we don't want to split around domain, keep everything as a name,
04493        * so we need to do nothing here, except remember why.
04494        */
04495    } else {
04496       /* store the result in a temp. variable to avoid it being
04497        * overwritten if arguments point to the same place.
04498        */
04499       char *c, *dom = "";
04500 
04501       if ((c = strchr(uri, '@')) == NULL) {
04502          /* domain-only URI, according to the SIP RFC. */
04503          dom = uri;
04504          name = "";
04505       } else {
04506          *c++ = '\0';
04507          dom = c;
04508          name = uri;
04509       }
04510 
04511       /* Remove options in domain and name */
04512       dom = strsep(&dom, ";");
04513       name = strsep(&name, ";");
04514 
04515       if (port && (c = strchr(dom, ':'))) { /* Remove :port */
04516          *c++ = '\0';
04517          *port = c;
04518       }
04519       if (pass && (c = strchr(name, ':'))) { /* user:password */
04520          *c++ = '\0';
04521          *pass = c;
04522       }
04523       *domain = dom;
04524    }
04525    if (ret_name)  /* same as for domain, store the result only at the end */
04526       *ret_name = name;
04527    if (options)
04528       *options = uri ? uri : "";
04529 
04530    return error;
04531 }
04532 
04533 /*! \brief Send message with Access-URL header, if this is an HTML URL only! */
04534 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
04535 {
04536    struct sip_pvt *p = chan->tech_pvt;
04537 
04538    if (subclass != AST_HTML_URL)
04539       return -1;
04540 
04541    ast_string_field_build(p, url, "<%s>;mode=active", data);
04542 
04543    if (sip_debug_test_pvt(p))
04544       ast_debug(1, "Send URL %s, state = %d!\n", data, chan->_state);
04545 
04546    switch (chan->_state) {
04547    case AST_STATE_RING:
04548       transmit_response(p, "100 Trying", &p->initreq);
04549       break;
04550    case AST_STATE_RINGING:
04551       transmit_response(p, "180 Ringing", &p->initreq);
04552       break;
04553    case AST_STATE_UP:
04554       if (!p->pendinginvite) {      /* We are up, and have no outstanding invite */
04555          transmit_reinvite_with_sdp(p, FALSE, FALSE);
04556       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
04557          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);   
04558       }  
04559       break;
04560    default:
04561       ast_log(LOG_WARNING, "Don't know how to send URI when state is %d!\n", chan->_state);
04562    }
04563 
04564    return 0;
04565 }
04566 
04567 /*! \brief Deliver SIP call ID for the call */
04568 static const char *sip_get_callid(struct ast_channel *chan)
04569 {
04570    return chan->tech_pvt ? ((struct sip_pvt *) chan->tech_pvt)->callid : "";
04571 }
04572 
04573 /*! \brief Send SIP MESSAGE text within a call
04574    Called from PBX core sendtext() application */
04575 static int sip_sendtext(struct ast_channel *ast, const char *text)
04576 {
04577    struct sip_pvt *p = ast->tech_pvt;
04578    int debug = sip_debug_test_pvt(p);
04579 
04580    if (debug)
04581       ast_verbose("Sending text %s on %s\n", text, ast->name);
04582    if (!p)
04583       return -1;
04584    /* NOT ast_strlen_zero, because a zero-length message is specifically
04585     * allowed by RFC 3428 (See section 10, Examples) */
04586    if (!text)
04587       return 0;
04588    if (debug)
04589       ast_verbose("Really sending text %s on %s\n", text, ast->name);
04590    transmit_message_with_text(p, text);
04591    return 0;   
04592 }
04593 
04594 /*! \brief Update peer object in realtime storage 
04595    If the Asterisk system name is set in asterisk.conf, we will use
04596    that name and store that in the "regserver" field in the sippeers
04597    table to facilitate multi-server setups.
04598 */
04599 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)
04600 {
04601    char port[10];
04602    char ipaddr[INET_ADDRSTRLEN];
04603    char regseconds[20];
04604    char *tablename = NULL;
04605    char str_lastms[20];
04606 
04607    const char *sysname = ast_config_AST_SYSTEM_NAME;
04608    char *syslabel = NULL;
04609 
04610    time_t nowtime = time(NULL) + expirey;
04611    const char *fc = fullcontact ? "fullcontact" : NULL;
04612 
04613    int realtimeregs = ast_check_realtime("sipregs");
04614 
04615    tablename = realtimeregs ? "sipregs" : "sippeers";
04616    
04617 
04618    snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
04619    snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);  /* Expiration time */
04620    ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
04621    snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
04622    
04623    if (ast_strlen_zero(sysname)) /* No system name, disable this */
04624       sysname = NULL;
04625    else if (sip_cfg.rtsave_sysname)
04626       syslabel = "regserver";
04627 
04628    /* XXX IMPORTANT: Anytime you add a new parameter to be updated, you
04629          *  must also add it to contrib/scripts/asterisk.ldap-schema,
04630          *  contrib/scripts/asterisk.ldif,
04631          *  and to configs/res_ldap.conf.sample as described in
04632          *  bugs 15156 and 15895 
04633          */
04634    if (fc) {
04635       ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04636          "port", port, "regseconds", regseconds,
04637          deprecated_username ? "username" : "defaultuser", defaultuser,
04638          "useragent", useragent, "lastms", str_lastms,
04639          fc, fullcontact, syslabel, sysname, SENTINEL); /* note fc and syslabel _can_ be NULL */
04640    } else {
04641       ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04642          "port", port, "regseconds", regseconds,
04643          "useragent", useragent, "lastms", str_lastms,
04644          deprecated_username ? "username" : "defaultuser", defaultuser,
04645          syslabel, sysname, SENTINEL); /* note syslabel _can_ be NULL */
04646    }
04647 }
04648 
04649 /*! \brief Automatically add peer extension to dial plan */
04650 static void register_peer_exten(struct sip_peer *peer, int onoff)
04651 {
04652    char multi[256];
04653    char *stringp, *ext, *context;
04654    struct pbx_find_info q = { .stacklen = 0 };
04655 
04656    /* XXX note that global_regcontext is both a global 'enable' flag and
04657     * the name of the global regexten context, if not specified
04658     * individually.
04659     */
04660    if (ast_strlen_zero(global_regcontext))
04661       return;
04662 
04663    ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
04664    stringp = multi;
04665    while ((ext = strsep(&stringp, "&"))) {
04666       if ((context = strchr(ext, '@'))) {
04667          *context++ = '\0';   /* split ext@context */
04668          if (!ast_context_find(context)) {
04669             ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
04670             continue;
04671          }
04672       } else {
04673          context = global_regcontext;
04674       }
04675       if (onoff) {
04676          if (!ast_exists_extension(NULL, context, ext, 1, NULL)) {
04677             ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
04678                 ast_strdup(peer->name), ast_free_ptr, "SIP");
04679          }
04680       } else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
04681          ast_context_remove_extension(context, ext, 1, NULL);
04682       }
04683    }
04684 }
04685 
04686 /*! Destroy mailbox subscriptions */
04687 static void destroy_mailbox(struct sip_mailbox *mailbox)
04688 {
04689    if (mailbox->mailbox)
04690       ast_free(mailbox->mailbox);
04691    if (mailbox->context)
04692       ast_free(mailbox->context);
04693    if (mailbox->event_sub)
04694       ast_event_unsubscribe(mailbox->event_sub);
04695    ast_free(mailbox);
04696 }
04697 
04698 /*! Destroy all peer-related mailbox subscriptions */
04699 static void clear_peer_mailboxes(struct sip_peer *peer)
04700 {
04701    struct sip_mailbox *mailbox;
04702 
04703    while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
04704       destroy_mailbox(mailbox);
04705 }
04706 
04707 static void sip_destroy_peer_fn(void *peer)
04708 {
04709    sip_destroy_peer(peer);
04710 }
04711 
04712 /*! \brief Destroy peer object from memory */
04713 static void sip_destroy_peer(struct sip_peer *peer)
04714 {
04715    ast_debug(3, "Destroying SIP peer %s\n", peer->name);
04716    if (peer->outboundproxy)
04717       ao2_ref(peer->outboundproxy, -1);
04718    peer->outboundproxy = NULL;
04719 
04720    /* Delete it, it needs to disappear */
04721    if (peer->call) {
04722       dialog_unlink_all(peer->call, TRUE, TRUE);
04723       peer->call = dialog_unref(peer->call, "peer->call is being unset");
04724    }
04725    
04726 
04727    if (peer->mwipvt) {  /* We have an active subscription, delete it */
04728       dialog_unlink_all(peer->mwipvt, TRUE, TRUE);
04729       peer->mwipvt = dialog_unref(peer->mwipvt, "unreffing peer->mwipvt");
04730    }
04731    
04732    if (peer->chanvars) {
04733       ast_variables_destroy(peer->chanvars);
04734       peer->chanvars = NULL;
04735    }
04736    
04737    register_peer_exten(peer, FALSE);
04738    ast_free_ha(peer->ha);
04739    if (peer->selfdestruct)
04740       ast_atomic_fetchadd_int(&apeerobjs, -1);
04741    else if (peer->is_realtime) {
04742       ast_atomic_fetchadd_int(&rpeerobjs, -1);
04743       ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
04744    } else
04745       ast_atomic_fetchadd_int(&speerobjs, -1);
04746    clear_realm_authentication(peer->auth);
04747    peer->auth = NULL;
04748    if (peer->dnsmgr)
04749       ast_dnsmgr_release(peer->dnsmgr);
04750    clear_peer_mailboxes(peer);
04751 
04752    if (peer->socket.tcptls_session) {
04753       ao2_ref(peer->socket.tcptls_session, -1);
04754       peer->socket.tcptls_session = NULL;
04755    }
04756 
04757    ast_string_field_free_memory(peer);
04758 }
04759 
04760 /*! \brief Update peer data in database (if used) */
04761 static void update_peer(struct sip_peer *p, int expire)
04762 {
04763    int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
04764    if (sip_cfg.peer_rtupdate &&
04765        (p->is_realtime || rtcachefriends)) {
04766       realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, p->useragent, expire, p->deprecated_username, p->lastms);
04767    }
04768 }
04769 
04770 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *cfg)
04771 {
04772    struct ast_variable *var = NULL;
04773    struct ast_flags flags = {0};
04774    char *cat = NULL;
04775    const char *insecure;
04776    while ((cat = ast_category_browse(cfg, cat))) {
04777       insecure = ast_variable_retrieve(cfg, cat, "insecure");
04778       set_insecure_flags(&flags, insecure, -1);
04779       if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
04780          var = ast_category_root(cfg, cat);
04781          break;
04782       }
04783    }
04784    return var;
04785 }
04786 
04787 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername)
04788 {
04789    struct ast_variable *tmp;
04790    for (tmp = var; tmp; tmp = tmp->next) {
04791       if (!newpeername && !strcasecmp(tmp->name, "name"))
04792          newpeername = tmp->value;
04793    }
04794    return newpeername;
04795 }
04796 
04797 /*! \brief  realtime_peer: Get peer from realtime storage
04798  * Checks the "sippeers" realtime family from extconfig.conf 
04799  * Checks the "sipregs" realtime family from extconfig.conf if it's configured.
04800  * This returns a pointer to a peer and because we use build_peer, we can rest
04801  * assured that the refcount is bumped.
04802 */
04803 static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin, int devstate_only)
04804 {
04805    struct sip_peer *peer;
04806    struct ast_variable *var = NULL;
04807    struct ast_variable *varregs = NULL;
04808    struct ast_variable *tmp;
04809    struct ast_config *peerlist = NULL;
04810    char ipaddr[INET_ADDRSTRLEN];
04811    char portstring[6]; /*up to 5 digits plus null terminator*/
04812    char *cat = NULL;
04813    unsigned short portnum;
04814    int realtimeregs = ast_check_realtime("sipregs");
04815 
04816    /* First check on peer name */
04817    if (newpeername) {
04818       if (realtimeregs)
04819          varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04820 
04821       var = ast_load_realtime("sippeers", "name", newpeername, "host", "dynamic", SENTINEL);
04822       if (!var && sin)
04823          var = ast_load_realtime("sippeers", "name", newpeername, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
04824       if (!var) {
04825          var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04826          /*!\note
04827           * If this one loaded something, then we need to ensure that the host
04828           * field matched.  The only reason why we can't have this as a criteria
04829           * is because we only have the IP address and the host field might be
04830           * set as a name (and the reverse PTR might not match).
04831           */
04832          if (var && sin) {
04833             for (tmp = var; tmp; tmp = tmp->next) {
04834                if (!strcasecmp(tmp->name, "host")) {
04835                   struct hostent *hp;
04836                   struct ast_hostent ahp;
04837                   if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
04838                      /* No match */
04839                      ast_variables_destroy(var);
04840                      var = NULL;
04841                   }
04842                   break;
04843                }
04844             }
04845          }
04846       }
04847    }
04848 
04849    if (!var && sin) {   /* Then check on IP address for dynamic peers */
04850       ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
04851       portnum = ntohs(sin->sin_port);
04852       sprintf(portstring, "%u", portnum);
04853       var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, SENTINEL);  /* First check for fixed IP hosts */
04854       if (var) {
04855          if (realtimeregs) {
04856             newpeername = get_name_from_variable(var, newpeername);
04857             varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04858          }
04859       } else {
04860          if (realtimeregs)
04861             varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, "port", portstring, SENTINEL); /* Then check for registered hosts */
04862          else
04863             var = ast_load_realtime("sippeers", "ipaddr", ipaddr, "port", portstring, SENTINEL); /* Then check for registered hosts */
04864          if (varregs) {
04865             newpeername = get_name_from_variable(varregs, newpeername);
04866             var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04867          }
04868       }
04869       if (!var) { /*We couldn't match on ipaddress and port, so we need to check if port is insecure*/
04870          peerlist = ast_load_realtime_multientry("sippeers", "host", ipaddr, SENTINEL);
04871          if (peerlist) {
04872             var = get_insecure_variable_from_config(peerlist);
04873             if(var) {
04874                if (realtimeregs) {
04875                   newpeername = get_name_from_variable(var, newpeername);
04876                   varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04877                }
04878             } else { /*var wasn't found in the list of "hosts", so try "ipaddr"*/
04879                peerlist = NULL;
04880                cat = NULL;
04881                peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, SENTINEL);
04882                if(peerlist) {
04883                   var = get_insecure_variable_from_config(peerlist);
04884                   if(var) {
04885                      if (realtimeregs) {
04886                         newpeername = get_name_from_variable(var, newpeername);
04887                         varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04888                      }
04889                   }
04890                }
04891             }
04892          } else {
04893             if (realtimeregs) {
04894                peerlist = ast_load_realtime_multientry("sipregs", "ipaddr", ipaddr, SENTINEL);
04895                if (peerlist) {
04896                   varregs = get_insecure_variable_from_config(peerlist);
04897                   if (varregs) {
04898                      newpeername = get_name_from_variable(varregs, newpeername);
04899                      var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04900                   }
04901                }
04902             } else {
04903                peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, SENTINEL);
04904                if (peerlist) {
04905                   var = get_insecure_variable_from_config(peerlist);
04906                   if (var) {
04907                      newpeername = get_name_from_variable(var, newpeername);
04908                      varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04909                   }
04910                }
04911             }
04912          }
04913       }
04914    }
04915 
04916    if (!var) {
04917       if (peerlist)
04918          ast_config_destroy(peerlist);
04919       return NULL;
04920    }
04921 
04922    for (tmp = var; tmp; tmp = tmp->next) {
04923       if (!newpeername && !strcasecmp(tmp->name, "name")) {
04924          newpeername = tmp->value;
04925       }
04926    }
04927    
04928    if (!newpeername) {  /* Did not find peer in realtime */
04929       ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", ipaddr);
04930       if(peerlist)
04931          ast_config_destroy(peerlist);
04932       else
04933          ast_variables_destroy(var);
04934       return NULL;
04935    }
04936 
04937 
04938    /* Peer found in realtime, now build it in memory */
04939    peer = build_peer(newpeername, var, varregs, TRUE, devstate_only);
04940    if (!peer) {
04941       if(peerlist)
04942          ast_config_destroy(peerlist);
04943       else {
04944          ast_variables_destroy(var);
04945          ast_variables_destroy(varregs);
04946       }
04947       return NULL;
04948    }
04949 
04950    ast_debug(3, "-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
04951 
04952    if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && !devstate_only) {
04953       /* Cache peer */
04954       ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
04955       if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
04956          AST_SCHED_REPLACE_UNREF(peer->expire, sched, sip_cfg.rtautoclear * 1000, expire_register, peer,
04957                unref_peer(_data, "remove registration ref"),
04958                unref_peer(peer, "remove registration ref"),
04959                ref_peer(peer, "add registration ref"));
04960       }
04961       ao2_t_link(peers, peer, "link peer into peers table");
04962       if (peer->addr.sin_addr.s_addr) {
04963          ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
04964       }
04965    }
04966    peer->is_realtime = 1;
04967    if (peerlist)
04968       ast_config_destroy(peerlist);
04969    else {
04970       ast_variables_destroy(var);
04971       ast_variables_destroy(varregs);
04972    }
04973 
04974    return peer;
04975 }
04976 
04977 /* Function to assist finding peers by name only */
04978 static int find_by_name(void *obj, void *arg, void *data, int flags)
04979 {
04980    struct sip_peer *search = obj, *match = arg;
04981    int *which_objects = data;
04982 
04983    /* Usernames in SIP uri's are case sensitive. Domains are not */
04984    if (strcmp(search->name, match->name)) {
04985       return 0;
04986    }
04987 
04988    switch (*which_objects) {
04989    case FINDUSERS:
04990       if (!(search->type & SIP_TYPE_USER)) {
04991          return 0;
04992       }
04993       break;
04994    case FINDPEERS:
04995       if (!(search->type & SIP_TYPE_PEER)) {
04996          return 0;
04997       }
04998       break;
04999    case FINDALLDEVICES:
05000       break;
05001    }
05002 
05003    return CMP_MATCH | CMP_STOP;
05004 }
05005 
05006 /*! 
05007  * \brief Locate device by name or ip address 
05008  *
05009  * \param which_objects Define which objects should be matched when doing a lookup
05010  *        by name.  Valid options are FINDUSERS, FINDPEERS, or FINDALLDEVICES.
05011  *        Note that this option is not used at all when doing a lookup by IP.
05012  *
05013  * This is used on find matching device on name or ip/port.
05014  * If the device was declared as type=peer, we don't match on peer name on incoming INVITEs.
05015  *
05016  * \note Avoid using this function in new functions if there is a way to avoid it,
05017  * since it might cause a database lookup.
05018  */
05019 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int which_objects, int devstate_only, int transport)
05020 {
05021    struct sip_peer *p = NULL;
05022    struct sip_peer tmp_peer;
05023 
05024    if (peer) {
05025       ast_copy_string(tmp_peer.name, peer, sizeof(tmp_peer.name));
05026       p = ao2_t_callback_data(peers, OBJ_POINTER, find_by_name, &tmp_peer, &which_objects, "ao2_find in peers table");
05027    } else if (sin) { /* search by addr? */
05028       tmp_peer.addr.sin_addr.s_addr = sin->sin_addr.s_addr;
05029       tmp_peer.addr.sin_port = sin->sin_port;
05030       tmp_peer.flags[0].flags = 0;
05031       tmp_peer.transports = transport;
05032       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); */
05033       if (!p) {
05034          ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
05035          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); */
05036          if (p) {
05037             return p;
05038          }
05039       }
05040    }
05041 
05042    if (!p && (realtime || devstate_only)) {
05043       p = realtime_peer(peer, sin, devstate_only);
05044       if (p) {
05045          switch (which_objects) {
05046          case FINDUSERS:
05047             if (!(p->type & SIP_TYPE_USER)) {
05048                unref_peer(p, "Wrong type of realtime SIP endpoint");
05049                return NULL;
05050             }
05051             break;
05052          case FINDPEERS:
05053             if (!(p->type & SIP_TYPE_PEER)) {
05054                unref_peer(p, "Wrong type of realtime SIP endpoint");
05055                return NULL;
05056             }
05057             break;
05058          case FINDALLDEVICES:
05059             break;
05060          }
05061       }
05062    }
05063 
05064    return p;
05065 }
05066 
05067 /*! \brief Set nat mode on the various data sockets */
05068 static void do_setnat(struct sip_pvt *p, int natflags)
05069 {
05070    const char *mode = natflags ? "On" : "Off";
05071 
05072    if (p->rtp) {
05073       ast_debug(1, "Setting NAT on RTP to %s\n", mode);
05074       ast_rtp_setnat(p->rtp, natflags);
05075    }
05076    if (p->vrtp) {
05077       ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
05078       ast_rtp_setnat(p->vrtp, natflags);
05079    }
05080    if (p->udptl) {
05081       ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
05082       ast_udptl_setnat(p->udptl, natflags);
05083    }
05084    if (p->trtp) {
05085       ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
05086       ast_rtp_setnat(p->trtp, natflags);
05087    }
05088 }
05089 
05090 /*! \brief Change the T38 state on a SIP dialog */
05091 static void change_t38_state(struct sip_pvt *p, int state)
05092 {
05093    int old = p->t38.state;
05094    struct ast_channel *chan = p->owner;
05095    struct ast_control_t38_parameters parameters = { .request_response = 0 };
05096 
05097    /* Don't bother changing if we are already in the state wanted */
05098    if (old == state)
05099       return;
05100 
05101    p->t38.state = state;
05102    ast_debug(2, "T38 state changed to %d on channel %s\n", p->t38.state, chan ? chan->name : "<none>");
05103 
05104    /* If no channel was provided we can't send off a control frame */
05105    if (!chan)
05106       return;
05107 
05108    /* Given the state requested and old state determine what control frame we want to queue up */
05109    switch (state) {
05110    case T38_PEER_REINVITE:
05111       parameters = p->t38.their_parms;
05112       parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05113       parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
05114       ast_udptl_set_tag(p->udptl, "SIP/%s", p->username);
05115       break;
05116    case T38_ENABLED:
05117       parameters = p->t38.their_parms;
05118       parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05119       parameters.request_response = AST_T38_NEGOTIATED;
05120       ast_udptl_set_tag(p->udptl, "SIP/%s", p->username);
05121       break;
05122    case T38_DISABLED:
05123       if (old == T38_ENABLED) {
05124          parameters.request_response = AST_T38_TERMINATED;
05125       } else if (old == T38_LOCAL_REINVITE) {
05126          parameters.request_response = AST_T38_REFUSED;
05127       }
05128       break;
05129    case T38_LOCAL_REINVITE:
05130       /* wait until we get a peer response before responding to local reinvite */
05131       break;
05132    }
05133 
05134    /* Woot we got a message, create a control frame and send it on! */
05135    if (parameters.request_response)
05136       ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
05137 }
05138 
05139 /*! \brief Set the global T38 capabilities on a SIP dialog structure */
05140 static void set_t38_capabilities(struct sip_pvt *p)
05141 {
05142    if (p->udptl) {
05143       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY) {
05144                         ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
05145       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_FEC) {
05146          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
05147       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL) {
05148          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
05149       }
05150    }
05151 }
05152 
05153 static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
05154 {
05155    if (to_sock->tcptls_session) {
05156       ao2_ref(to_sock->tcptls_session, -1);
05157       to_sock->tcptls_session = NULL;
05158    }
05159 
05160    if (from_sock->tcptls_session) {
05161       ao2_ref(from_sock->tcptls_session, +1);
05162    }
05163 
05164    *to_sock = *from_sock;
05165 }
05166 
05167 /*! \brief Create address structure from peer reference.
05168  * This function copies data from peer to the dialog, so we don't have to look up the peer
05169  * again from memory or database during the life time of the dialog.
05170  *
05171  * \return -1 on error, 0 on success.
05172  *
05173  */
05174 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
05175 {
05176 
05177    /* this checks that the dialog is contacting the peer on a valid
05178     * transport type based on the peers transport configuration,
05179     * otherwise, this function bails out */
05180    if (dialog->socket.type && check_request_transport(peer, dialog))
05181       return -1;
05182    copy_socket_data(&dialog->socket, &peer->socket);
05183 
05184    if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
05185        (!peer->maxms || ((peer->lastms >= 0)  && (peer->lastms <= peer->maxms)))) {
05186       dialog->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
05187       dialog->recv = dialog->sa;
05188    } else 
05189       return -1;
05190 
05191    ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
05192    ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
05193    dialog->capability = peer->capability;
05194    if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) &&
05195          (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
05196             !(dialog->capability & AST_FORMAT_VIDEO_MASK)) &&
05197          dialog->vrtp) {
05198       ast_rtp_destroy(dialog->vrtp);
05199       dialog->vrtp = NULL;
05200    }
05201    if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT) && dialog->trtp) {
05202       ast_rtp_destroy(dialog->trtp);
05203       dialog->trtp = NULL;
05204    }
05205    dialog->prefs = peer->prefs;
05206    if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
05207       /* t38pt_udptl was enabled in the peer and not in [general] */
05208       if (dialog->udptl || (!dialog->udptl && (dialog->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr)))) {
05209          dialog->t38_maxdatagram = peer->t38_maxdatagram;
05210          set_t38_capabilities(dialog);
05211       } else {
05212          /* It is impossible to support T38 without udptl */
05213          ast_debug(1, "UDPTL creation failed on dialog.\n");
05214          ast_clear_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT);
05215       }
05216    } else if (dialog->udptl) {
05217       ast_udptl_destroy(dialog->udptl);
05218       dialog->udptl = NULL;
05219    }
05220    do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
05221 
05222    if (dialog->rtp) { /* Audio */
05223       ast_rtp_setdtmf(dialog->rtp, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
05224       ast_rtp_setdtmfcompensate(dialog->rtp, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
05225       ast_rtp_set_rtptimeout(dialog->rtp, peer->rtptimeout);
05226       ast_rtp_set_rtpholdtimeout(dialog->rtp, peer->rtpholdtimeout);
05227       ast_rtp_set_rtpkeepalive(dialog->rtp, peer->rtpkeepalive);
05228       /* Set Frame packetization */
05229       ast_rtp_codec_setpref(dialog->rtp, &dialog->prefs);
05230       dialog->autoframing = peer->autoframing;
05231    }
05232    if (dialog->vrtp) { /* Video */
05233       ast_rtp_setdtmf(dialog->vrtp, 0);
05234       ast_rtp_setdtmfcompensate(dialog->vrtp, 0);
05235       ast_rtp_set_rtptimeout(dialog->vrtp, peer->rtptimeout);
05236       ast_rtp_set_rtpholdtimeout(dialog->vrtp, peer->rtpholdtimeout);
05237       ast_rtp_set_rtpkeepalive(dialog->vrtp, peer->rtpkeepalive);
05238    }
05239    if (dialog->trtp) { /* Realtime text */
05240       ast_rtp_setdtmf(dialog->trtp, 0);
05241       ast_rtp_setdtmfcompensate(dialog->trtp, 0);
05242       ast_rtp_set_rtptimeout(dialog->trtp, peer->rtptimeout);
05243       ast_rtp_set_rtpholdtimeout(dialog->trtp, peer->rtpholdtimeout);
05244       ast_rtp_set_rtpkeepalive(dialog->trtp, peer->rtpkeepalive);
05245    }
05246 
05247    ast_string_field_set(dialog, peername, peer->name);
05248    ast_string_field_set(dialog, authname, peer->username);
05249    ast_string_field_set(dialog, username, peer->username);
05250    ast_string_field_set(dialog, peersecret, peer->secret);
05251    ast_string_field_set(dialog, peermd5secret, peer->md5secret);
05252    ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
05253    ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
05254    ast_string_field_set(dialog, tohost, peer->tohost);
05255    ast_string_field_set(dialog, fullcontact, peer->fullcontact);
05256    ast_string_field_set(dialog, context, peer->context);
05257    ast_string_field_set(dialog, parkinglot, peer->parkinglot);
05258    ref_proxy(dialog, obproxy_get(dialog, peer));
05259    dialog->callgroup = peer->callgroup;
05260    dialog->pickupgroup = peer->pickupgroup;
05261    dialog->allowtransfer = peer->allowtransfer;
05262    dialog->jointnoncodeccapability = dialog->noncodeccapability;
05263    dialog->rtptimeout = peer->rtptimeout;
05264    dialog->peerauth = peer->auth;
05265    dialog->maxcallbitrate = peer->maxcallbitrate;
05266    if (ast_strlen_zero(dialog->tohost))
05267       ast_string_field_set(dialog, tohost, ast_inet_ntoa(dialog->sa.sin_addr));
05268    if (!ast_strlen_zero(peer->fromdomain)) {
05269       ast_string_field_set(dialog, fromdomain, peer->fromdomain);
05270       if (!dialog->initreq.headers) {
05271          char *c;
05272          char *tmpcall = ast_strdupa(dialog->callid);
05273          /* this sure looks to me like we are going to change the callid on this dialog!! */
05274          c = strchr(tmpcall, '@');
05275          if (c) {
05276             *c = '\0';
05277             ao2_t_unlink(dialogs, dialog, "About to change the callid -- remove the old name");
05278             ast_string_field_build(dialog, callid, "%s@%s", tmpcall, peer->fromdomain);
05279             ao2_t_link(dialogs, dialog, "New dialog callid -- inserted back into table");
05280          }
05281       }
05282    }
05283    if (!ast_strlen_zero(peer->fromuser)) 
05284       ast_string_field_set(dialog, fromuser, peer->fromuser);
05285    if (!ast_strlen_zero(peer->language))
05286       ast_string_field_set(dialog, language, peer->language);
05287    /* Set timer T1 to RTT for this peer (if known by qualify=) */
05288    /* Minimum is settable or default to 100 ms */
05289    /* If there is a maxms and lastms from a qualify use that over a manual T1
05290       value. Otherwise, use the peer's T1 value. */
05291    if (peer->maxms && peer->lastms)
05292       dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
05293    else
05294       dialog->timer_t1 = peer->timer_t1;
05295 
05296    /* Set timer B to control transaction timeouts, the peer setting is the default and overrides
05297       the known timer */
05298    if (peer->timer_b)
05299       dialog->timer_b = peer->timer_b;
05300    else
05301       dialog->timer_b = 64 * dialog->timer_t1;
05302 
05303    if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
05304        (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
05305       dialog->noncodeccapability |= AST_RTP_DTMF;
05306    else
05307       dialog->noncodeccapability &= ~AST_RTP_DTMF;
05308    if (peer->call_limit)
05309       ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
05310    if (!dialog->portinuri)
05311       dialog->portinuri = peer->portinuri;
05312    
05313    dialog->chanvars = copy_vars(peer->chanvars);
05314 
05315    return 0;
05316 }
05317 
05318 /*! \brief create address structure from device name
05319  *      Or, if peer not found, find it in the global DNS 
05320  *      returns TRUE (-1) on failure, FALSE on success */
05321 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog)
05322 {
05323    struct hostent *hp;
05324    struct ast_hostent ahp;
05325    struct sip_peer *peer;
05326    char *port;
05327    int portno = 0;
05328    char host[MAXHOSTNAMELEN], *hostn;
05329    char peername[256];
05330    int srv_ret = 0;
05331 
05332    ast_copy_string(peername, opeer, sizeof(peername));
05333    port = strchr(peername, ':');
05334    if (port) {
05335       *port++ = '\0';
05336       dialog->portinuri = 1;
05337    }
05338    dialog->sa.sin_family = AF_INET;
05339    dialog->timer_t1 = global_t1; /* Default SIP retransmission timer T1 (RFC 3261) */
05340    dialog->timer_b = global_timer_b; /* Default SIP transaction timer B (RFC 3261) */
05341    peer = find_peer(peername, NULL, TRUE, FINDPEERS, FALSE, 0);
05342 
05343    if (peer) {
05344       int res;
05345       if (newdialog) {
05346          set_socket_transport(&dialog->socket, 0);
05347       }
05348       res = create_addr_from_peer(dialog, peer);
05349       if (!ast_strlen_zero(port)) {
05350          if ((portno = atoi(port))) {
05351             dialog->sa.sin_port = dialog->recv.sin_port = htons(portno);
05352          }
05353       }
05354       unref_peer(peer, "create_addr: unref peer from find_peer hashtab lookup");
05355       return res;
05356    }
05357 
05358    do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
05359 
05360    ast_string_field_set(dialog, tohost, peername);
05361 
05362    /* Get the outbound proxy information */
05363    ref_proxy(dialog, obproxy_get(dialog, NULL));
05364 
05365    if (sin) {
05366       /* This address should be updated using dnsmgr */
05367       memcpy(&dialog->sa.sin_addr, &sin->sin_addr, sizeof(dialog->sa.sin_addr));
05368       if (!sin->sin_port) {
05369          portno = port_str2int(port, (dialog->socket.type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
05370       } else {
05371          portno = ntohs(sin->sin_port);
05372       }
05373    } else {
05374 
05375       /* Let's see if we can find the host in DNS. First try DNS SRV records,
05376          then hostname lookup */
05377       /*! \todo Fix this function. When we ask for SRV, we should check all transports 
05378            In the future, we should first check NAPTR to find out transport preference
05379        */
05380       hostn = peername;
05381       /* Section 4.2 of RFC 3263 specifies that if a port number is specified, then
05382        * an A record lookup should be used instead of SRV.
05383        */
05384       if (!port && sip_cfg.srvlookup) {
05385          char service[MAXHOSTNAMELEN];
05386          int tportno;
05387          snprintf(service, sizeof(service), "_%s._%s.%s",
05388              get_srv_service(dialog->socket.type),
05389              get_srv_protocol(dialog->socket.type), peername);
05390          srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
05391          if (srv_ret > 0) {
05392             hostn = host;
05393             portno = tportno;
05394          }
05395       }
05396       if (!portno)
05397          portno = port_str2int(port, (dialog->socket.type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
05398       hp = ast_gethostbyname(hostn, &ahp);
05399       if (!hp) {
05400          ast_log(LOG_WARNING, "No such host: %s\n", peername);
05401          return -1;
05402       }
05403       memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
05404    }
05405 
05406    if (!dialog->socket.type)
05407       set_socket_transport(&dialog->socket, SIP_TRANSPORT_UDP);
05408    if (!dialog->socket.port)
05409       dialog->socket.port = bindaddr.sin_port;
05410    dialog->sa.sin_port = htons(portno);
05411    dialog->recv = dialog->sa;
05412    return 0;
05413 }
05414 
05415 /*! \brief Scheduled congestion on a call.
05416  * Only called by the scheduler, must return the reference when done.
05417  */
05418 static int auto_congest(const void *arg)
05419 {
05420    struct sip_pvt *p = (struct sip_pvt *)arg;
05421 
05422    sip_pvt_lock(p);
05423    p->initid = -1;   /* event gone, will not be rescheduled */
05424    if (p->owner) {
05425       /* XXX fails on possible deadlock */
05426       if (!ast_channel_trylock(p->owner)) {
05427          append_history(p, "Cong", "Auto-congesting (timer)");
05428          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
05429          ast_channel_unlock(p->owner);
05430       }
05431 
05432       /* Give the channel a chance to act before we proceed with destruction */
05433       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05434    }
05435    sip_pvt_unlock(p);
05436    dialog_unref(p, "unreffing arg passed into auto_congest callback (p->initid)");
05437    return 0;
05438 }
05439 
05440 
05441 /*! \brief Initiate SIP call from PBX 
05442  *      used from the dial() application      */
05443 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
05444 {
05445    int res;
05446    struct sip_pvt *p = ast->tech_pvt;  /* chan is locked, so the reference cannot go away */
05447    struct varshead *headp;
05448    struct ast_var_t *current;
05449    const char *referer = NULL;   /* SIP referrer */
05450 
05451    if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
05452       ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
05453       return -1;
05454    }
05455 
05456    /* Check whether there is vxml_url, distinctive ring variables */
05457    headp=&ast->varshead;
05458    AST_LIST_TRAVERSE(headp, current, entries) {
05459       /* Check whether there is a VXML_URL variable */
05460       if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
05461          p->options->vxml_url = ast_var_value(current);
05462       } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
05463          p->options->uri_options = ast_var_value(current);
05464       } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
05465          /* Check whether there is a variable with a name starting with SIPADDHEADER */
05466          p->options->addsipheaders = 1;
05467       } else if (!strcasecmp(ast_var_name(current), "SIPFROMDOMAIN")) {
05468          ast_string_field_set(p, fromdomain, ast_var_value(current));
05469       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
05470          /* This is a transfered call */
05471          p->options->transfer = 1;
05472       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
05473          /* This is the referrer */
05474          referer = ast_var_value(current);
05475       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
05476          /* We're replacing a call. */
05477          p->options->replaces = ast_var_value(current);
05478       }
05479    }
05480 
05481    res = 0;
05482    ast_set_flag(&p->flags[0], SIP_OUTGOING);
05483 
05484    /* T.38 re-INVITE FAX detection should never be done for outgoing calls,
05485     * so ensure it is disabled.
05486     */
05487    ast_clear_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38);
05488 
05489    if (p->options->transfer) {
05490       char buf[SIPBUFSIZE/2];
05491 
05492       if (referer) {
05493          if (sipdebug)
05494             ast_debug(3, "Call for %s transfered by %s\n", p->username, referer);
05495          snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
05496       } else 
05497          snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
05498       ast_string_field_set(p, cid_name, buf);
05499    } 
05500    ast_debug(1, "Outgoing Call for %s\n", p->username);
05501 
05502    res = update_call_counter(p, INC_CALL_RINGING);
05503 
05504    if (res == -1) {
05505       ast->hangupcause = AST_CAUSE_USER_BUSY;
05506       return res;
05507    }
05508    p->callingpres = ast->cid.cid_pres;
05509    p->jointcapability = ast_translate_available_formats(p->capability, p->prefcodec);
05510    p->jointnoncodeccapability = p->noncodeccapability;
05511 
05512    /* If there are no audio formats left to offer, punt */
05513    if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
05514       ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
05515       res = -1;
05516    } else {
05517       int xmitres;
05518 
05519       xmitres = transmit_invite(p, SIP_INVITE, 1, 2);
05520       if (xmitres == XMIT_ERROR)
05521          return -1;
05522       p->invitestate = INV_CALLING;
05523    
05524       /* Initialize auto-congest time */
05525       AST_SCHED_REPLACE_UNREF(p->initid, sched, p->timer_b, auto_congest, p, 
05526                         dialog_unref(_data, "dialog ptr dec when SCHED_REPLACE del op succeeded"), 
05527                         dialog_unref(p, "dialog ptr dec when SCHED_REPLACE add failed"),
05528                         dialog_ref(p, "dialog ptr inc when SCHED_REPLACE add succeeded") );
05529    }
05530    return res;
05531 }
05532 
05533 /*! \brief Destroy registry object
05534    Objects created with the register= statement in static configuration */
05535 static void sip_registry_destroy(struct sip_registry *reg)
05536 {
05537    /* Really delete */
05538    ast_debug(3, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
05539 
05540    if (reg->call) {
05541       /* Clear registry before destroying to ensure
05542          we don't get reentered trying to grab the registry lock */
05543       reg->call->registry = registry_unref(reg->call->registry, "destroy reg->call->registry");
05544       ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
05545       dialog_unlink_all(reg->call, TRUE, TRUE);
05546       reg->call = dialog_unref(reg->call, "unref reg->call");
05547       /* reg->call = sip_destroy(reg->call); */
05548    }
05549    AST_SCHED_DEL(sched, reg->expire);  
05550    AST_SCHED_DEL(sched, reg->timeout);
05551    
05552    ast_string_field_free_memory(reg);
05553    ast_atomic_fetchadd_int(&regobjs, -1);
05554    ast_dnsmgr_release(reg->dnsmgr);
05555    ast_free(reg);
05556 }
05557 
05558 /*! \brief Destroy MWI subscription object */
05559 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi)
05560 {
05561    if (mwi->call) {
05562       mwi->call->mwi = NULL;
05563       sip_destroy(mwi->call);
05564    }
05565    
05566    AST_SCHED_DEL(sched, mwi->resub);
05567    ast_string_field_free_memory(mwi);
05568    ast_dnsmgr_release(mwi->dnsmgr);
05569    ast_free(mwi);
05570 }
05571 
05572 /*! \brief Execute destruction of SIP dialog structure, release memory */
05573 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
05574 {
05575    struct sip_request *req;
05576 
05577    if (p->stimer) {
05578       ast_free(p->stimer);
05579       p->stimer = NULL;
05580    }
05581 
05582    if (sip_debug_test_pvt(p))
05583       ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
05584 
05585    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05586       update_call_counter(p, DEC_CALL_LIMIT);
05587       ast_debug(2, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
05588    }
05589 
05590    /* Unlink us from the owner if we have one */
05591    if (p->owner) {
05592       if (lockowner)
05593          ast_channel_lock(p->owner);
05594       if (option_debug)
05595          ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
05596       p->owner->tech_pvt = NULL;
05597       /* Make sure that the channel knows its backend is going away */
05598       p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
05599       if (lockowner)
05600          ast_channel_unlock(p->owner);
05601       /* Give the channel a chance to react before deallocation */
05602       usleep(1);
05603    }
05604 
05605    /* Remove link from peer to subscription of MWI */
05606    if (p->relatedpeer && p->relatedpeer->mwipvt)
05607       p->relatedpeer->mwipvt = dialog_unref(p->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
05608    if (p->relatedpeer && p->relatedpeer->call == p)
05609       p->relatedpeer->call = dialog_unref(p->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
05610    
05611    if (p->relatedpeer)
05612       p->relatedpeer = unref_peer(p->relatedpeer,"unsetting a dialog relatedpeer field in sip_destroy");
05613    
05614    if (p->registry) {
05615       if (p->registry->call == p)
05616          p->registry->call = dialog_unref(p->registry->call, "nulling out the registry's call dialog field in unlink_all");
05617       p->registry = registry_unref(p->registry, "delete p->registry");
05618    }
05619    
05620    if (p->mwi) {
05621       p->mwi->call = NULL;
05622    }
05623 
05624    if (dumphistory)
05625       sip_dump_history(p);
05626 
05627    if (p->options)
05628       ast_free(p->options);
05629 
05630    if (p->notify_headers) {
05631       ast_variables_destroy(p->notify_headers);
05632       p->notify_headers = NULL;
05633    }
05634    if (p->rtp) {
05635       ast_rtp_destroy(p->rtp);
05636    }
05637    if (p->vrtp) {
05638       ast_rtp_destroy(p->vrtp);
05639    }
05640    if (p->trtp) {
05641       while (ast_rtp_get_bridged(p->trtp))
05642          usleep(1);
05643       ast_rtp_destroy(p->trtp);
05644    }
05645    if (p->udptl)
05646       ast_udptl_destroy(p->udptl);
05647    if (p->refer)
05648       ast_free(p->refer);
05649    if (p->route) {
05650       free_old_route(p->route);
05651       p->route = NULL;
05652    }
05653    deinit_req(&p->initreq);
05654 
05655    /* Destroy Session-Timers if allocated */
05656    if (p->stimer) {
05657       p->stimer->quit_flag = 1;
05658       if (p->stimer->st_active == TRUE && p->stimer->st_schedid > -1) {
05659          AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
05660                dialog_unref(p, "removing session timer ref"));
05661       }
05662       ast_free(p->stimer);
05663       p->stimer = NULL;
05664    }
05665 
05666    /* Clear history */
05667    if (p->history) {
05668       struct sip_history *hist;
05669       while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
05670          ast_free(hist);
05671          p->history_entries--;
05672       }
05673       ast_free(p->history);
05674       p->history = NULL;
05675    }
05676 
05677    while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
05678       ast_free(req);
05679    }
05680 
05681    if (p->chanvars) {
05682       ast_variables_destroy(p->chanvars);
05683       p->chanvars = NULL;
05684    }
05685 
05686    ast_string_field_free_memory(p);
05687 
05688    if (p->socket.tcptls_session) {
05689       ao2_ref(p->socket.tcptls_session, -1);
05690       p->socket.tcptls_session = NULL;
05691    }
05692 }
05693 
05694 /*! \brief  update_call_counter: Handle call_limit for SIP devices
05695  * Setting a call-limit will cause calls above the limit not to be accepted.
05696  *
05697  * Remember that for a type=friend, there's one limit for the user and
05698  * another for the peer, not a combined call limit.
05699  * This will cause unexpected behaviour in subscriptions, since a "friend"
05700  * is *two* devices in Asterisk, not one.
05701  *
05702  * Thought: For realtime, we should probably update storage with inuse counter... 
05703  *
05704  * \return 0 if call is ok (no call limit, below threshold)
05705  * -1 on rejection of call
05706  *    
05707  */
05708 static int update_call_counter(struct sip_pvt *fup, int event)
05709 {
05710    char name[256];
05711    int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
05712    int outgoing = fup->outgoing_call;
05713    struct sip_peer *p = NULL;
05714 
05715    ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
05716 
05717 
05718    /* Test if we need to check call limits, in order to avoid 
05719       realtime lookups if we do not need it */
05720    if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
05721       return 0;
05722 
05723    ast_copy_string(name, fup->username, sizeof(name));
05724 
05725    /* Check the list of devices */
05726    if ((p = find_peer(ast_strlen_zero(fup->peername) ? name : fup->peername, NULL, TRUE, FINDALLDEVICES, FALSE, 0))) { 
05727       inuse = &p->inUse;
05728       call_limit = &p->call_limit;
05729       inringing = &p->inRinging;
05730       ast_copy_string(name, fup->peername, sizeof(name));
05731    }
05732    if (!p) {
05733       ast_debug(2, "%s is not a local device, no call limit\n", name);
05734       return 0;
05735    }
05736 
05737    switch(event) {
05738    /* incoming and outgoing affects the inUse counter */
05739    case DEC_CALL_LIMIT:
05740       /* Decrement inuse count if applicable */
05741       if (inuse) {
05742          sip_pvt_lock(fup);
05743          ao2_lock(p);
05744          if (*inuse > 0) {
05745             if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
05746                (*inuse)--;
05747                ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
05748             }
05749          } else {
05750             *inuse = 0;
05751          }
05752          ao2_unlock(p);
05753          sip_pvt_unlock(fup);
05754       }
05755 
05756       /* Decrement ringing count if applicable */
05757       if (inringing) {
05758          sip_pvt_lock(fup);
05759          ao2_lock(p);
05760          if (*inringing > 0) {
05761             if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05762                (*inringing)--;
05763                ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
05764             }
05765          } else {
05766             *inringing = 0;
05767          }
05768          ao2_unlock(p);
05769          sip_pvt_unlock(fup);
05770       }
05771 
05772       /* Decrement onhold count if applicable */
05773       sip_pvt_lock(fup);
05774       ao2_lock(p);
05775       if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && sip_cfg.notifyhold) {
05776          ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
05777          ao2_unlock(p);
05778          sip_pvt_unlock(fup);
05779          sip_peer_hold(fup, FALSE);
05780       } else {
05781          ao2_unlock(p);
05782          sip_pvt_unlock(fup);
05783       }
05784       if (sipdebug)
05785          ast_debug(2, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
05786       break;
05787 
05788    case INC_CALL_RINGING:
05789    case INC_CALL_LIMIT:
05790       /* If call limit is active and we have reached the limit, reject the call */
05791       if (*call_limit > 0 ) {
05792          if (*inuse >= *call_limit) {
05793             ast_log(LOG_NOTICE, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
05794             unref_peer(p, "update_call_counter: unref peer p, call limit exceeded");
05795             return -1; 
05796          }
05797       }
05798       if (inringing && (event == INC_CALL_RINGING)) {
05799          sip_pvt_lock(fup);
05800          ao2_lock(p);
05801          if (!ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05802             (*inringing)++;
05803             ast_set_flag(&fup->flags[0], SIP_INC_RINGING);
05804          }
05805          ao2_unlock(p);
05806          sip_pvt_unlock(fup);
05807       }
05808       if (inuse) {
05809          sip_pvt_lock(fup);
05810          ao2_lock(p);
05811          if (!ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
05812             (*inuse)++;
05813             ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
05814          }
05815          ao2_unlock(p);
05816          sip_pvt_unlock(fup);
05817       }
05818       if (sipdebug) {
05819          ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", "peer", name, *inuse, *call_limit);
05820       }
05821       break;
05822 
05823    case DEC_CALL_RINGING:
05824       if (inringing) {
05825          sip_pvt_lock(fup);
05826          ao2_lock(p);
05827          if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05828             if (*inringing > 0) {
05829                (*inringing)--;
05830             }
05831             ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
05832          }
05833          ao2_unlock(p);
05834          sip_pvt_unlock(fup);
05835       }
05836       break;
05837 
05838    default:
05839       ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
05840    }
05841 
05842    if (p) {
05843       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", p->name);
05844       unref_peer(p, "update_call_counter: unref_peer from call counter");
05845    } 
05846    return 0;
05847 }
05848 
05849 
05850 static void sip_destroy_fn(void *p)
05851 {
05852    sip_destroy(p);
05853 }
05854 
05855 /*! \brief Destroy SIP call structure.
05856  * Make it return NULL so the caller can do things like
05857  * foo = sip_destroy(foo);
05858  * and reduce the chance of bugs due to dangling pointers.
05859  */
05860 static struct sip_pvt * sip_destroy(struct sip_pvt *p)
05861 {
05862    ast_debug(3, "Destroying SIP dialog %s\n", p->callid);
05863    __sip_destroy(p, TRUE, TRUE);
05864    return NULL;
05865 }
05866 
05867 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
05868 static int hangup_sip2cause(int cause)
05869 {
05870    /* Possible values taken from causes.h */
05871 
05872    switch(cause) {
05873       case 401:   /* Unauthorized */
05874          return AST_CAUSE_CALL_REJECTED;
05875       case 403:   /* Not found */
05876          return AST_CAUSE_CALL_REJECTED;
05877       case 404:   /* Not found */
05878          return AST_CAUSE_UNALLOCATED;
05879       case 405:   /* Method not allowed */
05880          return AST_CAUSE_INTERWORKING;
05881       case 407:   /* Proxy authentication required */
05882          return AST_CAUSE_CALL_REJECTED;
05883       case 408:   /* No reaction */
05884          return AST_CAUSE_NO_USER_RESPONSE;
05885       case 409:   /* Conflict */
05886          return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
05887       case 410:   /* Gone */
05888          return AST_CAUSE_NUMBER_CHANGED;
05889       case 411:   /* Length required */
05890          return AST_CAUSE_INTERWORKING;
05891       case 413:   /* Request entity too large */
05892          return AST_CAUSE_INTERWORKING;
05893       case 414:   /* Request URI too large */
05894          return AST_CAUSE_INTERWORKING;
05895       case 415:   /* Unsupported media type */
05896          return AST_CAUSE_INTERWORKING;
05897       case 420:   /* Bad extension */
05898          return AST_CAUSE_NO_ROUTE_DESTINATION;
05899       case 480:   /* No answer */
05900          return AST_CAUSE_NO_ANSWER;
05901       case 481:   /* No answer */
05902          return AST_CAUSE_INTERWORKING;
05903       case 482:   /* Loop detected */
05904          return AST_CAUSE_INTERWORKING;
05905       case 483:   /* Too many hops */
05906          return AST_CAUSE_NO_ANSWER;
05907       case 484:   /* Address incomplete */
05908          return AST_CAUSE_INVALID_NUMBER_FORMAT;
05909       case 485:   /* Ambiguous */
05910          return AST_CAUSE_UNALLOCATED;
05911       case 486:   /* Busy everywhere */
05912          return AST_CAUSE_BUSY;
05913       case 487:   /* Request terminated */
05914          return AST_CAUSE_INTERWORKING;
05915       case 488:   /* No codecs approved */
05916          return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05917       case 491:   /* Request pending */
05918          return AST_CAUSE_INTERWORKING;
05919       case 493:   /* Undecipherable */
05920          return AST_CAUSE_INTERWORKING;
05921       case 500:   /* Server internal failure */
05922          return AST_CAUSE_FAILURE;
05923       case 501:   /* Call rejected */
05924          return AST_CAUSE_FACILITY_REJECTED;
05925       case 502:   
05926          return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
05927       case 503:   /* Service unavailable */
05928          return AST_CAUSE_CONGESTION;
05929       case 504:   /* Gateway timeout */
05930          return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
05931       case 505:   /* SIP version not supported */
05932          return AST_CAUSE_INTERWORKING;
05933       case 600:   /* Busy everywhere */
05934          return AST_CAUSE_USER_BUSY;
05935       case 603:   /* Decline */
05936          return AST_CAUSE_CALL_REJECTED;
05937       case 604:   /* Does not exist anywhere */
05938          return AST_CAUSE_UNALLOCATED;
05939       case 606:   /* Not acceptable */
05940          return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05941       default:
05942          return AST_CAUSE_NORMAL;
05943    }
05944    /* Never reached */
05945    return 0;
05946 }
05947 
05948 /*! \brief Convert Asterisk hangup causes to SIP codes 
05949 \verbatim
05950  Possible values from causes.h
05951         AST_CAUSE_NOTDEFINED    AST_CAUSE_NORMAL        AST_CAUSE_BUSY
05952         AST_CAUSE_FAILURE       AST_CAUSE_CONGESTION    AST_CAUSE_UNALLOCATED
05953 
05954    In addition to these, a lot of PRI codes is defined in causes.h 
05955    ...should we take care of them too ?
05956    
05957    Quote RFC 3398
05958 
05959    ISUP Cause value                        SIP response
05960    ----------------                        ------------
05961    1  unallocated number                   404 Not Found
05962    2  no route to network                  404 Not found
05963    3  no route to destination              404 Not found
05964    16 normal call clearing                 --- (*)
05965    17 user busy                            486 Busy here
05966    18 no user responding                   408 Request Timeout
05967    19 no answer from the user              480 Temporarily unavailable
05968    20 subscriber absent                    480 Temporarily unavailable
05969    21 call rejected                        403 Forbidden (+)
05970    22 number changed (w/o diagnostic)      410 Gone
05971    22 number changed (w/ diagnostic)       301 Moved Permanently
05972    23 redirection to new destination       410 Gone
05973    26 non-selected user clearing           404 Not Found (=)
05974    27 destination out of order             502 Bad Gateway
05975    28 address incomplete                   484 Address incomplete
05976    29 facility rejected                    501 Not implemented
05977    31 normal unspecified                   480 Temporarily unavailable
05978 \endverbatim
05979 */
05980 static const char *hangup_cause2sip(int cause)
05981 {
05982    switch (cause) {
05983       case AST_CAUSE_UNALLOCATED:      /* 1 */
05984       case AST_CAUSE_NO_ROUTE_DESTINATION:   /* 3 IAX2: Can't find extension in context */
05985       case AST_CAUSE_NO_ROUTE_TRANSIT_NET:   /* 2 */
05986          return "404 Not Found";
05987       case AST_CAUSE_CONGESTION:    /* 34 */
05988       case AST_CAUSE_SWITCH_CONGESTION:   /* 42 */
05989          return "503 Service Unavailable";
05990       case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
05991          return "408 Request Timeout";
05992       case AST_CAUSE_NO_ANSWER:     /* 19 */
05993       case AST_CAUSE_UNREGISTERED:        /* 20 */
05994          return "480 Temporarily unavailable";
05995       case AST_CAUSE_CALL_REJECTED:    /* 21 */
05996          return "403 Forbidden";
05997       case AST_CAUSE_NUMBER_CHANGED:      /* 22 */
05998          return "410 Gone";
05999       case AST_CAUSE_NORMAL_UNSPECIFIED:  /* 31 */
06000          return "480 Temporarily unavailable";
06001       case AST_CAUSE_INVALID_NUMBER_FORMAT:
06002          return "484 Address incomplete";
06003       case AST_CAUSE_USER_BUSY:
06004          return "486 Busy here";
06005       case AST_CAUSE_FAILURE:
06006          return "500 Server internal failure";
06007       case AST_CAUSE_FACILITY_REJECTED:   /* 29 */
06008          return "501 Not Implemented";
06009       case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
06010          return "503 Service Unavailable";
06011       /* Used in chan_iax2 */
06012       case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
06013          return "502 Bad Gateway";
06014       case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
06015          return "488 Not Acceptable Here";
06016          
06017       case AST_CAUSE_NOTDEFINED:
06018       default:
06019          ast_debug(1, "AST hangup cause %d (no match found in SIP)\n", cause);
06020          return NULL;
06021    }
06022 
06023    /* Never reached */
06024    return 0;
06025 }
06026 
06027 
06028 /*! \brief  sip_hangup: Hangup SIP call
06029  * Part of PBX interface, called from ast_hangup */
06030 static int sip_hangup(struct ast_channel *ast)
06031 {
06032    struct sip_pvt *p = ast->tech_pvt;
06033    int needcancel = FALSE;
06034    int needdestroy = 0;
06035    struct ast_channel *oldowner = ast;
06036 
06037    if (!p) {
06038       ast_debug(1, "Asked to hangup channel that was not connected\n");
06039       return 0;
06040    }
06041    if (ast_test_flag(ast, AST_FLAG_ANSWERED_ELSEWHERE) || ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
06042       ast_debug(1, "This call was answered elsewhere");
06043       if (ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
06044          ast_debug(1, "####### It's the cause code, buddy. The cause code!!!\n");
06045       }
06046       append_history(p, "Cancel", "Call answered elsewhere");
06047       p->answered_elsewhere = TRUE;
06048    }
06049 
06050    /* Store hangupcause locally in PVT so we still have it before disconnect */
06051    if (p->owner)
06052       p->hangupcause = p->owner->hangupcause;
06053 
06054    if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
06055       if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06056          if (sipdebug)
06057             ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
06058          update_call_counter(p, DEC_CALL_LIMIT);
06059       }
06060       ast_debug(4, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
06061       if (p->autokillid > -1 && sip_cancel_destroy(p))
06062          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
06063       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06064       ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Really hang up next time */
06065       p->needdestroy = 0;
06066       p->owner->tech_pvt = dialog_unref(p->owner->tech_pvt, "unref p->owner->tech_pvt");
06067       sip_pvt_lock(p);
06068       p->owner = NULL;  /* Owner will be gone after we return, so take it away */
06069       sip_pvt_unlock(p);
06070       ast_module_unref(ast_module_info->self);
06071       return 0;
06072    }
06073 
06074    if (ast_test_flag(ast, AST_FLAG_ZOMBIE)) {
06075       if (p->refer)
06076          ast_debug(1, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast->name, p->callid);
06077       else
06078          ast_debug(1, "Hanging up zombie call. Be scared.\n");
06079    } else
06080       ast_debug(1, "Hangup call %s, SIP callid %s\n", ast->name, p->callid);
06081 
06082    sip_pvt_lock(p);
06083    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06084       if (sipdebug)
06085          ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
06086       update_call_counter(p, DEC_CALL_LIMIT);
06087    }
06088 
06089    /* Determine how to disconnect */
06090    if (p->owner != ast) {
06091       ast_log(LOG_WARNING, "Huh?  We aren't the owner? Can't hangup call.\n");
06092       sip_pvt_unlock(p);
06093       return 0;
06094    }
06095    /* If the call is not UP, we need to send CANCEL instead of BYE */
06096    /* In case of re-invites, the call might be UP even though we have an incomplete invite transaction */
06097    if (p->invitestate < INV_COMPLETED && p->owner->_state != AST_STATE_UP) {
06098       needcancel = TRUE;
06099       ast_debug(4, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
06100    }
06101 
06102    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
06103 
06104    append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", p->owner ? ast_cause2str(p->hangupcause) : "Unknown");
06105 
06106    /* Disconnect */
06107    if (p->dsp)
06108       ast_dsp_free(p->dsp);
06109 
06110    p->owner = NULL;
06111    ast->tech_pvt = dialog_unref(ast->tech_pvt, "unref ast->tech_pvt");
06112 
06113    ast_module_unref(ast_module_info->self);
06114    /* Do not destroy this pvt until we have timeout or
06115       get an answer to the BYE or INVITE/CANCEL 
06116       If we get no answer during retransmit period, drop the call anyway.
06117       (Sorry, mother-in-law, you can't deny a hangup by sending
06118       603 declined to BYE...)
06119    */
06120    if (p->alreadygone)
06121       needdestroy = 1;  /* Set destroy flag at end of this function */
06122    else if (p->invitestate != INV_CALLING)
06123       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06124 
06125    /* Start the process if it's not already started */
06126    if (!p->alreadygone && p->initreq.data && !ast_strlen_zero(p->initreq.data->str)) {
06127       if (needcancel) { /* Outgoing call, not up */
06128          if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06129             /* stop retransmitting an INVITE that has not received a response */
06130             /* if we can't send right now, mark it pending */
06131             if (p->invitestate == INV_CALLING) {
06132                /* We can't send anything in CALLING state */
06133                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
06134                /* 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. */
06135                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06136                append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
06137             } else {
06138                struct sip_pkt *cur;
06139 
06140                for (cur = p->packets; cur; cur = cur->next) {
06141                   __sip_semi_ack(p, cur->seqno, cur->is_resp, cur->method ? cur->method : find_sip_method(cur->data->str));
06142                }
06143                p->invitestate = INV_CANCELLED;
06144                /* Send a new request: CANCEL */
06145                transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
06146                /* Actually don't destroy us yet, wait for the 487 on our original 
06147                   INVITE, but do set an autodestruct just in case we never get it. */
06148                needdestroy = 0;
06149                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06150             }
06151          } else { /* Incoming call, not up */
06152             const char *res;
06153             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"));
06154             if (p->hangupcause && (res = hangup_cause2sip(p->hangupcause)))
06155                transmit_response_reliable(p, res, &p->initreq);
06156             else 
06157                transmit_response_reliable(p, "603 Declined", &p->initreq);
06158             p->invitestate = INV_TERMINATED;
06159          }
06160       } else { /* Call is in UP state, send BYE */
06161          if (p->stimer->st_active == TRUE) {
06162             stop_session_timer(p);
06163          }
06164 
06165          if (!p->pendinginvite) {
06166             struct ast_channel *bridge = ast_bridged_channel(oldowner);
06167             char *audioqos = "";
06168             char *videoqos = "";
06169             char *textqos = "";
06170 
06171             /* We need to get the lock on bridge because ast_rtp_set_vars will attempt
06172              * to lock the bridge. This may get hairy...
06173              */
06174             while (bridge && ast_channel_trylock(bridge)) {
06175                sip_pvt_unlock(p);
06176                do {
06177                   /* Use oldowner since p->owner is already NULL */
06178                   CHANNEL_DEADLOCK_AVOIDANCE(oldowner);
06179                } while (sip_pvt_trylock(p));
06180                bridge = ast_bridged_channel(oldowner);
06181             }
06182 
06183             if (p->rtp)
06184                ast_rtp_set_vars(oldowner, p->rtp);
06185 
06186             if (bridge) {
06187                struct sip_pvt *q = bridge->tech_pvt;
06188 
06189                if (IS_SIP_TECH(bridge->tech) && q && q->rtp)
06190                   ast_rtp_set_vars(bridge, q->rtp);
06191                ast_channel_unlock(bridge);
06192             }
06193 
06194             if (p->vrtp)
06195                videoqos = ast_rtp_get_quality(p->vrtp, NULL, RTPQOS_SUMMARY);
06196             if (p->trtp)
06197                textqos = ast_rtp_get_quality(p->trtp, NULL, RTPQOS_SUMMARY);
06198             /* Send a hangup */
06199             if (oldowner->_state == AST_STATE_UP) {
06200                transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
06201             }
06202 
06203             /* Get RTCP quality before end of call */
06204             if (p->do_history) {
06205                if (p->rtp)
06206                   append_history(p, "RTCPaudio", "Quality:%s", audioqos);
06207                if (p->vrtp)
06208                   append_history(p, "RTCPvideo", "Quality:%s", videoqos);
06209                if (p->trtp)
06210                   append_history(p, "RTCPtext", "Quality:%s", textqos);
06211             }
06212             if (p->rtp && oldowner)
06213                pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", audioqos);
06214             if (p->vrtp && oldowner)
06215                pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", videoqos);
06216             if (p->trtp && oldowner)
06217                pbx_builtin_setvar_helper(oldowner, "RTPTEXTQOS", textqos);
06218          } else {
06219             /* Note we will need a BYE when this all settles out
06220                but we can't send one while we have "INVITE" outstanding. */
06221             ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
06222             ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE); 
06223             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"));
06224             if (sip_cancel_destroy(p))
06225                ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
06226          }
06227       }
06228    }
06229    if (needdestroy) {
06230       pvt_set_needdestroy(p, "hangup");
06231    }
06232    sip_pvt_unlock(p);
06233    return 0;
06234 }
06235 
06236 /*! \brief Try setting codec suggested by the SIP_CODEC channel variable */
06237 static void try_suggested_sip_codec(struct sip_pvt *p)
06238 {
06239    int fmt;
06240    const char *codec;
06241 
06242    codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
06243    if (!codec) 
06244       return;
06245 
06246    fmt = ast_getformatbyname(codec);
06247    if (fmt) {
06248       ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
06249       if (p->jointcapability & fmt) {
06250          p->jointcapability &= fmt;
06251          p->capability &= fmt;
06252       } else
06253          ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
06254    } else
06255       ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
06256    return;  
06257 }
06258 
06259 /*! \brief  sip_answer: Answer SIP call , send 200 OK on Invite 
06260  * Part of PBX interface */
06261 static int sip_answer(struct ast_channel *ast)
06262 {
06263    int res = 0;
06264    struct sip_pvt *p = ast->tech_pvt;
06265 
06266    sip_pvt_lock(p);
06267    if (ast->_state != AST_STATE_UP) {
06268       try_suggested_sip_codec(p);   
06269 
06270       ast_setstate(ast, AST_STATE_UP);
06271       ast_debug(1, "SIP answering channel: %s\n", ast->name);
06272       ast_rtp_new_source(p->rtp);
06273       res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL, FALSE);
06274       ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
06275    }
06276    sip_pvt_unlock(p);
06277    return res;
06278 }
06279 
06280 /*! \brief Send frame to media channel (rtp) */
06281 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
06282 {
06283    struct sip_pvt *p = ast->tech_pvt;
06284    int res = 0;
06285 
06286    switch (frame->frametype) {
06287    case AST_FRAME_VOICE:
06288       if (!(frame->subclass & ast->nativeformats)) {
06289          char s1[512], s2[512], s3[512];
06290          ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %s(%d) read/write = %s(%d)/%s(%d)\n",
06291             frame->subclass, 
06292             ast_getformatname_multiple(s1, sizeof(s1) - 1, ast->nativeformats & AST_FORMAT_AUDIO_MASK),
06293             ast->nativeformats & AST_FORMAT_AUDIO_MASK,
06294             ast_getformatname_multiple(s2, sizeof(s2) - 1, ast->readformat),
06295             ast->readformat,
06296             ast_getformatname_multiple(s3, sizeof(s3) - 1, ast->writeformat),
06297             ast->writeformat);
06298          return 0;
06299       }
06300       if (p) {
06301          sip_pvt_lock(p);
06302          if (p->rtp) {
06303             /* If channel is not up, activate early media session */
06304             if ((ast->_state != AST_STATE_UP) &&
06305                 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06306                 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06307                ast_rtp_new_source(p->rtp);
06308                if (!global_prematuremediafilter) {
06309                   p->invitestate = INV_EARLY_MEDIA;
06310                   transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06311                   ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06312                }
06313             } else if (p->t38.state == T38_ENABLED) {
06314                /* drop frame, can't sent VOICE frames while in T.38 mode */
06315             } else {
06316                p->lastrtptx = time(NULL);
06317                res = ast_rtp_write(p->rtp, frame);
06318             }
06319          }
06320          sip_pvt_unlock(p);
06321       }
06322       break;
06323    case AST_FRAME_VIDEO:
06324       if (p) {
06325          sip_pvt_lock(p);
06326          if (p->vrtp) {
06327             /* Activate video early media */
06328             if ((ast->_state != AST_STATE_UP) &&
06329                 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06330                 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06331                p->invitestate = INV_EARLY_MEDIA;
06332                transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06333                ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06334             }
06335             p->lastrtptx = time(NULL);
06336             res = ast_rtp_write(p->vrtp, frame);
06337          }
06338          sip_pvt_unlock(p);
06339       }
06340       break;
06341    case AST_FRAME_TEXT:
06342       if (p) {
06343          sip_pvt_lock(p);
06344          if (p->red) {
06345             red_buffer_t140(p->trtp, frame);
06346          } else {
06347             if (p->trtp) {
06348                /* Activate text early media */
06349                if ((ast->_state != AST_STATE_UP) &&
06350                    !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06351                    !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06352                   p->invitestate = INV_EARLY_MEDIA;
06353                   transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06354                   ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06355                }
06356                p->lastrtptx = time(NULL);
06357                res = ast_rtp_write(p->trtp, frame);
06358             }
06359          }
06360          sip_pvt_unlock(p);
06361       }
06362       break;
06363    case AST_FRAME_IMAGE:
06364       return 0;
06365       break;
06366    case AST_FRAME_MODEM:
06367       if (p) {
06368          sip_pvt_lock(p);
06369          /* UDPTL requires two-way communication, so early media is not needed here.
06370             we simply forget the frames if we get modem frames before the bridge is up.
06371             Fax will re-transmit.
06372          */
06373          if ((ast->_state == AST_STATE_UP) &&
06374              p->udptl &&
06375              (p->t38.state == T38_ENABLED)) {
06376             res = ast_udptl_write(p->udptl, frame);
06377          }
06378          sip_pvt_unlock(p);
06379       }
06380       break;
06381    default: 
06382       ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
06383       return 0;
06384    }
06385 
06386    return res;
06387 }
06388 
06389 /*! \brief  sip_fixup: Fix up a channel:  If a channel is consumed, this is called.
06390         Basically update any ->owner links */
06391 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
06392 {
06393    int ret = -1;
06394    struct sip_pvt *p;
06395 
06396    if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE))
06397       ast_debug(1, "New channel is zombie\n");
06398    if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE))
06399       ast_debug(1, "Old channel is zombie\n");
06400 
06401    if (!newchan || !newchan->tech_pvt) {
06402       if (!newchan)
06403          ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
06404       else
06405          ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
06406       return -1;
06407    }
06408    p = newchan->tech_pvt;
06409 
06410    sip_pvt_lock(p);
06411    append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
06412    append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
06413    if (p->owner != oldchan)
06414       ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
06415    else {
06416       p->owner = newchan;
06417       /* Re-invite RTP back to Asterisk. Needed if channel is masqueraded out of a native
06418          RTP bridge (i.e., RTP not going through Asterisk): RTP bridge code might not be
06419          able to do this if the masquerade happens before the bridge breaks (e.g., AMI
06420          redirect of both channels). Note that a channel can not be masqueraded *into*
06421          a native bridge. So there is no danger that this breaks a native bridge that
06422          should stay up. */
06423       sip_set_rtp_peer(newchan, NULL, NULL, 0, 0, 0);
06424       ret = 0;
06425    }
06426    ast_debug(3, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);
06427 
06428    sip_pvt_unlock(p);
06429    return ret;
06430 }
06431 
06432 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
06433 {
06434    struct sip_pvt *p = ast->tech_pvt;
06435    int res = 0;
06436 
06437    sip_pvt_lock(p);
06438    switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06439    case SIP_DTMF_INBAND:
06440       res = -1; /* Tell Asterisk to generate inband indications */
06441       break;
06442    case SIP_DTMF_RFC2833:
06443       if (p->rtp)
06444          ast_rtp_senddigit_begin(p->rtp, digit);
06445       break;
06446    default:
06447       break;
06448    }
06449    sip_pvt_unlock(p);
06450 
06451    return res;
06452 }
06453 
06454 /*! \brief Send DTMF character on SIP channel
06455    within one call, we're able to transmit in many methods simultaneously */
06456 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
06457 {
06458    struct sip_pvt *p = ast->tech_pvt;
06459    int res = 0;
06460 
06461    sip_pvt_lock(p);
06462    switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06463    case SIP_DTMF_INFO:
06464    case SIP_DTMF_SHORTINFO:
06465       transmit_info_with_digit(p, digit, duration);
06466       break;
06467    case SIP_DTMF_RFC2833:
06468       if (p->rtp)
06469          ast_rtp_senddigit_end_with_duration(p->rtp, digit, duration);
06470       break;
06471    case SIP_DTMF_INBAND:
06472       res = -1; /* Tell Asterisk to stop inband indications */
06473       break;
06474    }
06475    sip_pvt_unlock(p);
06476 
06477    return res;
06478 }
06479 
06480 /*! \brief Transfer SIP call */
06481 static int sip_transfer(struct ast_channel *ast, const char *dest)
06482 {
06483    struct sip_pvt *p = ast->tech_pvt;
06484    int res;
06485 
06486    if (dest == NULL) /* functions below do not take a NULL */
06487       dest = "";
06488    sip_pvt_lock(p);
06489    if (ast->_state == AST_STATE_RING)
06490       res = sip_sipredirect(p, dest);
06491    else
06492       res = transmit_refer(p, dest);
06493    sip_pvt_unlock(p);
06494    return res;
06495 }
06496 
06497 /*! \brief Helper function which updates T.38 capability information and triggers a reinvite */
06498 static int interpret_t38_parameters(struct sip_pvt *p, const struct ast_control_t38_parameters *parameters)
06499 {
06500    int res = 0;
06501 
06502    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) || !p->udptl) {
06503       return -1;
06504    }
06505    switch (parameters->request_response) {
06506    case AST_T38_NEGOTIATED:
06507    case AST_T38_REQUEST_NEGOTIATE:         /* Request T38 */
06508       /* Negotiation can not take place without a valid max_ifp value. */
06509       if (!parameters->max_ifp) {
06510          change_t38_state(p, T38_DISABLED);
06511          if (p->t38.state == T38_PEER_REINVITE) {
06512             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"));
06513             transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06514          }
06515          break;
06516       } else if (p->t38.state == T38_PEER_REINVITE) {
06517          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"));
06518          p->t38.our_parms = *parameters;
06519          /* modify our parameters to conform to the peer's parameters,
06520           * based on the rules in the ITU T.38 recommendation
06521           */
06522          if (!p->t38.their_parms.fill_bit_removal) {
06523             p->t38.our_parms.fill_bit_removal = FALSE;
06524          }
06525          if (!p->t38.their_parms.transcoding_mmr) {
06526             p->t38.our_parms.transcoding_mmr = FALSE;
06527          }
06528          if (!p->t38.their_parms.transcoding_jbig) {
06529             p->t38.our_parms.transcoding_jbig = FALSE;
06530          }
06531          p->t38.our_parms.version = MIN(p->t38.our_parms.version, p->t38.their_parms.version);
06532          p->t38.our_parms.rate_management = p->t38.their_parms.rate_management;
06533          ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06534          change_t38_state(p, T38_ENABLED);
06535          transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
06536       } else if (p->t38.state != T38_ENABLED) {
06537          p->t38.our_parms = *parameters;
06538          ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06539          change_t38_state(p, T38_LOCAL_REINVITE);
06540          if (!p->pendinginvite) {
06541             transmit_reinvite_with_sdp(p, TRUE, FALSE);
06542          } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
06543             ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
06544          }
06545       }
06546       break;
06547    case AST_T38_TERMINATED:
06548    case AST_T38_REFUSED:
06549    case AST_T38_REQUEST_TERMINATE:         /* Shutdown T38 */
06550       if (p->t38.state == T38_PEER_REINVITE) {
06551          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"));
06552          change_t38_state(p, T38_DISABLED);
06553          transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06554       } else if (p->t38.state == T38_ENABLED)
06555          transmit_reinvite_with_sdp(p, FALSE, FALSE);
06556       break;
06557    case AST_T38_REQUEST_PARMS: {    /* Application wants remote's parameters re-sent */
06558       struct ast_control_t38_parameters parameters = p->t38.their_parms;
06559 
06560       if (p->t38.state == T38_PEER_REINVITE) {
06561          AST_SCHED_DEL(sched, p->t38id);
06562          parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
06563          parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
06564          ast_queue_control_data(p->owner, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
06565          /* we need to return a positive value here, so that applications that
06566           * send this request can determine conclusively whether it was accepted or not...
06567           * older versions of chan_sip would just silently accept it and return zero.
06568           */
06569          res = AST_T38_REQUEST_PARMS;
06570       }
06571       break;
06572    }
06573    default:
06574       res = -1;
06575       break;
06576    }
06577 
06578    return res;
06579 }
06580 
06581 /*! \brief Play indication to user 
06582  * With SIP a lot of indications is sent as messages, letting the device play
06583    the indication - busy signal, congestion etc 
06584    \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
06585 */
06586 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
06587 {
06588    struct sip_pvt *p = ast->tech_pvt;
06589    int res = 0;
06590 
06591    sip_pvt_lock(p);
06592    switch(condition) {
06593    case AST_CONTROL_RINGING:
06594       if (ast->_state == AST_STATE_RING) {
06595          p->invitestate = INV_EARLY_MEDIA;
06596          if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
06597              (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {            
06598             /* Send 180 ringing if out-of-band seems reasonable */
06599             transmit_provisional_response(p, "180 Ringing", &p->initreq, 0);
06600             ast_set_flag(&p->flags[0], SIP_RINGING);
06601             if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
06602                break;
06603          } else {
06604             /* Well, if it's not reasonable, just send in-band */
06605          }
06606       }
06607       res = -1;
06608       break;
06609    case AST_CONTROL_BUSY:
06610       if (ast->_state != AST_STATE_UP) {
06611          transmit_response_reliable(p, "486 Busy Here", &p->initreq);
06612          p->invitestate = INV_COMPLETED;
06613          sip_alreadygone(p);
06614          ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06615          break;
06616       }
06617       res = -1;
06618       break;
06619    case AST_CONTROL_CONGESTION:
06620       if (ast->_state != AST_STATE_UP) {
06621          transmit_response_reliable(p, "503 Service Unavailable", &p->initreq);
06622          p->invitestate = INV_COMPLETED;
06623          sip_alreadygone(p);
06624          ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06625          break;
06626       }
06627       res = -1;
06628       break;
06629    case AST_CONTROL_PROCEEDING:
06630       if ((ast->_state != AST_STATE_UP) &&
06631           !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06632           !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06633          transmit_response(p, "100 Trying", &p->initreq);
06634          p->invitestate = INV_PROCEEDING;  
06635          break;
06636       }
06637       res = -1;
06638       break;
06639    case AST_CONTROL_PROGRESS:
06640       if ((ast->_state != AST_STATE_UP) &&
06641           !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06642           !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06643          p->invitestate = INV_EARLY_MEDIA;
06644          transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06645          ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06646          break;
06647       }
06648       res = -1;
06649       break;
06650    case AST_CONTROL_HOLD:
06651       ast_rtp_new_source(p->rtp);
06652       ast_moh_start(ast, data, p->mohinterpret);
06653       break;
06654    case AST_CONTROL_UNHOLD:
06655       ast_rtp_new_source(p->rtp);
06656       ast_moh_stop(ast);
06657       break;
06658    case AST_CONTROL_VIDUPDATE:   /* Request a video frame update */
06659       if (p->vrtp && !p->novideo) {
06660          transmit_info_with_vidupdate(p);
06661          /* ast_rtcp_send_h261fur(p->vrtp); */
06662       } else
06663          res = -1;
06664       break;
06665    case AST_CONTROL_T38_PARAMETERS:
06666       if (datalen != sizeof(struct ast_control_t38_parameters)) {
06667          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);
06668          res = -1;
06669       } else {
06670          const struct ast_control_t38_parameters *parameters = data;
06671          res = interpret_t38_parameters(p, parameters);
06672       }
06673       break;
06674    case AST_CONTROL_SRCUPDATE:
06675       ast_rtp_new_source(p->rtp);
06676       break;
06677    case AST_CONTROL_SRCCHANGE:
06678       ast_rtp_change_source(p->rtp);
06679       break;
06680    case -1:
06681       res = -1;
06682       break;
06683    default:
06684       ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
06685       res = -1;
06686       break;
06687    }
06688    sip_pvt_unlock(p);
06689    return res;
06690 }
06691 
06692 
06693 /*! \brief Initiate a call in the SIP channel
06694    called from sip_request_call (calls from the pbx ) for outbound channels
06695    and from handle_request_invite for inbound channels
06696    
06697 */
06698 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title)
06699 {
06700    struct ast_channel *tmp;
06701    struct ast_variable *v = NULL;
06702    int fmt;
06703    int what;
06704    int video;
06705    int text;
06706    int needvideo = 0;
06707    int needtext = 0;
06708    char buf[SIPBUFSIZE];
06709    char *decoded_exten;
06710 
06711    {
06712       const char *my_name; /* pick a good name */
06713    
06714       if (title) {
06715          my_name = title;
06716       } else {
06717          char *port = NULL;
06718          my_name = ast_strdupa(i->fromdomain);
06719          if ((port = strchr(i->fromdomain, ':'))) {
06720             *port = '\0';
06721          }
06722       }
06723 
06724       sip_pvt_unlock(i);
06725       /* Don't hold a sip pvt lock while we allocate a channel */
06726       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));
06727 
06728    }
06729    if (!tmp) {
06730       ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
06731       sip_pvt_lock(i);
06732       return NULL;
06733    }
06734    sip_pvt_lock(i);
06735 
06736    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;
06737 
06738    /* Select our native format based on codec preference until we receive
06739       something from another device to the contrary. */
06740    if (i->jointcapability) {  /* The joint capabilities of us and peer */
06741       what = i->jointcapability;
06742       video = i->jointcapability & AST_FORMAT_VIDEO_MASK;
06743       text = i->jointcapability & AST_FORMAT_TEXT_MASK;
06744    } else if (i->capability) {      /* Our configured capability for this peer */
06745       what = i->capability;
06746       video = i->capability & AST_FORMAT_VIDEO_MASK;
06747       text = i->capability & AST_FORMAT_TEXT_MASK;
06748    } else {
06749       what = global_capability;  /* Global codec support */
06750       video = global_capability & AST_FORMAT_VIDEO_MASK;
06751       text = global_capability & AST_FORMAT_TEXT_MASK;
06752    }
06753 
06754    /* Set the native formats for audio  and merge in video */
06755    tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | video | text;
06756    ast_debug(3, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmp->nativeformats));
06757    ast_debug(3, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcapability));
06758    ast_debug(3, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->capability));
06759    ast_debug(3, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, ast_codec_choose(&i->prefs, what, 1)));
06760    if (i->prefcodec)
06761       ast_debug(3, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcodec));
06762 
06763    /* XXX Why are we choosing a codec from the native formats?? */
06764    fmt = ast_best_codec(tmp->nativeformats);
06765 
06766    /* If we have a prefcodec setting, we have an inbound channel that set a 
06767       preferred format for this call. Otherwise, we check the jointcapability
06768       We also check for vrtp. If it's not there, we are not allowed do any video anyway.
06769     */
06770    if (i->vrtp) {
06771       if (ast_test_flag(&i->flags[1], SIP_PAGE2_VIDEOSUPPORT))
06772          needvideo = AST_FORMAT_VIDEO_MASK;
06773       else if (i->prefcodec)
06774          needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK;  /* Outbound call */
06775       else
06776          needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK;  /* Inbound call */
06777    }
06778 
06779    if (i->trtp) {
06780       if (i->prefcodec)
06781          needtext = i->prefcodec & AST_FORMAT_TEXT_MASK; /* Outbound call */
06782       else
06783          needtext = i->jointcapability & AST_FORMAT_TEXT_MASK; /* Inbound call */
06784    }
06785 
06786    if (needvideo) 
06787       ast_debug(3, "This channel can handle video! HOLLYWOOD next!\n");
06788    else
06789       ast_debug(3, "This channel will not be able to handle video.\n");
06790 
06791    if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) || (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) ||
06792        (ast_test_flag(&i->flags[1], SIP_PAGE2_FAX_DETECT))) {
06793       int features = 0;
06794 
06795       if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) || (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
06796          features |= DSP_FEATURE_DIGIT_DETECT;
06797       }
06798 
06799       if (ast_test_flag(&i->flags[1], SIP_PAGE2_FAX_DETECT)) {
06800          features |= DSP_FEATURE_FAX_DETECT;
06801       }
06802 
06803       i->dsp = ast_dsp_new();
06804       ast_dsp_set_features(i->dsp, features);
06805       if (global_relaxdtmf)
06806          ast_dsp_set_digitmode(i->dsp, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
06807          }
06808 
06809    /* Set file descriptors for audio, video, realtime text and UDPTL as needed */
06810    if (i->rtp) {
06811       ast_channel_set_fd(tmp, 0, ast_rtp_fd(i->rtp));
06812       ast_channel_set_fd(tmp, 1, ast_rtcp_fd(i->rtp));
06813    }
06814    if (needvideo && i->vrtp) {
06815       ast_channel_set_fd(tmp, 2, ast_rtp_fd(i->vrtp));
06816       ast_channel_set_fd(tmp, 3, ast_rtcp_fd(i->vrtp));
06817    }
06818    if (needtext && i->trtp) 
06819       ast_channel_set_fd(tmp, 4, ast_rtp_fd(i->trtp));
06820    if (i->udptl)
06821       ast_channel_set_fd(tmp, 5, ast_udptl_fd(i->udptl));
06822 
06823    if (state == AST_STATE_RING)
06824       tmp->rings = 1;
06825    tmp->adsicpe = AST_ADSI_UNAVAILABLE;
06826    tmp->writeformat = fmt;
06827    tmp->rawwriteformat = fmt;
06828    tmp->readformat = fmt;
06829    tmp->rawreadformat = fmt;
06830    tmp->tech_pvt = dialog_ref(i, "sip_new: set chan->tech_pvt to i");
06831 
06832    tmp->callgroup = i->callgroup;
06833    tmp->pickupgroup = i->pickupgroup;
06834    tmp->cid.cid_pres = i->callingpres;
06835    if (!ast_strlen_zero(i->parkinglot))
06836       ast_string_field_set(tmp, parkinglot, i->parkinglot);
06837    if (!ast_strlen_zero(i->accountcode))
06838       ast_string_field_set(tmp, accountcode, i->accountcode);
06839    if (i->amaflags)
06840       tmp->amaflags = i->amaflags;
06841    if (!ast_strlen_zero(i->language))
06842       ast_string_field_set(tmp, language, i->language);
06843    i->owner = tmp;
06844    ast_module_ref(ast_module_info->self);
06845    ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
06846    /*Since it is valid to have extensions in the dialplan that have unescaped characters in them
06847     * we should decode the uri before storing it in the channel, but leave it encoded in the sip_pvt
06848     * structure so that there aren't issues when forming URI's
06849     */
06850    if (ast_exists_extension(NULL, i->context, i->exten, 1, i->cid_num)) {
06851       /* encoded in dialplan, so keep extension encoded */
06852       ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
06853    } else {
06854       decoded_exten = ast_strdupa(i->exten);
06855       ast_uri_decode(decoded_exten);
06856       ast_copy_string(tmp->exten, decoded_exten, sizeof(tmp->exten));
06857    }
06858 
06859    /* Don't use ast_set_callerid() here because it will
06860     * generate an unnecessary NewCallerID event  */
06861    tmp->cid.cid_ani = ast_strdup(i->cid_num);
06862    if (!ast_strlen_zero(i->rdnis))
06863       tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
06864    
06865    if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
06866       tmp->cid.cid_dnid = ast_strdup(i->exten);
06867 
06868    tmp->priority = 1;
06869    if (!ast_strlen_zero(i->uri))
06870       pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
06871    if (!ast_strlen_zero(i->domain))
06872       pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
06873    if (!ast_strlen_zero(i->callid))
06874       pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
06875    if (i->rtp)
06876       ast_jb_configure(tmp, &global_jbconf);
06877 
06878    /* Set channel variables for this call from configuration */
06879    for (v = i->chanvars ; v ; v = v->next) {
06880       char valuebuf[1024];
06881       pbx_builtin_setvar_helper(tmp, v->name, ast_get_encoded_str(v->value, valuebuf, sizeof(valuebuf)));
06882    }
06883 
06884    if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
06885       ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
06886       tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
06887       ast_hangup(tmp);
06888       tmp = NULL;
06889    }
06890 
06891    if (i->do_history)
06892       append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);
06893 
06894    /* Inform manager user about new channel and their SIP call ID */
06895    if (sip_cfg.callevents)
06896       manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
06897          "Channel: %s\r\nUniqueid: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\n",
06898          tmp->name, tmp->uniqueid, "SIP", i->callid, i->fullcontact);
06899 
06900    return tmp;
06901 }
06902 
06903 /*! \brief Reads one line of SIP message body */
06904 static char *get_body_by_line(const char *line, const char *name, int nameLen, char delimiter)
06905 {
06906    if (!strncasecmp(line, name, nameLen) && line[nameLen] == delimiter)
06907       return ast_skip_blanks(line + nameLen + 1);
06908 
06909    return "";
06910 }
06911 
06912 /*! \brief Lookup 'name' in the SDP starting
06913  * at the 'start' line. Returns the matching line, and 'start'
06914  * is updated with the next line number.
06915  */
06916 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
06917 {
06918    int len = strlen(name);
06919 
06920    while (*start < (req->sdp_start + req->sdp_count)) {
06921       const char *r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[(*start)++]), name, len, '=');
06922       if (r[0] != '\0')
06923          return r;
06924    }
06925 
06926    /* if the line was not found, ensure that *start points past the SDP */
06927    (*start)++;
06928 
06929    return "";
06930 }
06931 
06932 /*! \brief Fetches the next valid SDP line between the 'start' line
06933  * (inclusive) and the 'stop' line (exclusive). Returns the type
06934  * ('a', 'c', ...) and matching line in reference 'start' is updated
06935  * with the next line number.
06936  */
06937 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value)
06938 {
06939    char type = '\0';
06940    const char *line = NULL;
06941 
06942    if (stop > (req->sdp_start + req->sdp_count)) {
06943       stop = req->sdp_start + req->sdp_count;
06944    }
06945 
06946    while (*start < stop) {
06947       line = REQ_OFFSET_TO_STR(req, line[(*start)++]);
06948       if (line[1] == '=') {
06949          type = line[0];
06950          *value = ast_skip_blanks(line + 2);
06951          break;
06952       }
06953    }
06954 
06955    return type;
06956 }
06957 
06958 /*! \brief Get a specific line from the message body */
06959 static char *get_body(struct sip_request *req, char *name, char delimiter) 
06960 {
06961    int x;
06962    int len = strlen(name);
06963    char *r;
06964 
06965    for (x = 0; x < req->lines; x++) {
06966       r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[x]), name, len, delimiter);
06967       if (r[0] != '\0')
06968          return r;
06969    }
06970 
06971    return "";
06972 }
06973 
06974 /*! \brief Find compressed SIP alias */
06975 static const char *find_alias(const char *name, const char *_default)
06976 {
06977    /*! \brief Structure for conversion between compressed SIP and "normal" SIP */
06978    static const struct cfalias {
06979       char * const fullname;
06980       char * const shortname;
06981    } aliases[] = {
06982       { "Content-Type",  "c" },
06983       { "Content-Encoding",    "e" },
06984       { "From",       "f" },
06985       { "Call-ID",       "i" },
06986       { "Contact",       "m" },
06987       { "Content-Length",   "l" },
06988       { "Subject",       "s" },
06989       { "To",         "t" },
06990       { "Supported",     "k" },
06991       { "Refer-To",      "r" },
06992       { "Referred-By",   "b" },
06993       { "Allow-Events",  "u" },
06994       { "Event",      "o" },
06995       { "Via",     "v" },
06996       { "Accept-Contact",      "a" },
06997       { "Reject-Contact",      "j" },
06998       { "Request-Disposition", "d" },
06999       { "Session-Expires",     "x" },
07000       { "Identity",            "y" },
07001       { "Identity-Info",       "n" },
07002    };
07003    int x;
07004 
07005    for (x = 0; x < ARRAY_LEN(aliases); x++) {
07006       if (!strcasecmp(aliases[x].fullname, name))
07007          return aliases[x].shortname;
07008    }
07009 
07010    return _default;
07011 }
07012 
07013 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
07014 {
07015    int pass;
07016 
07017    /*
07018     * Technically you can place arbitrary whitespace both before and after the ':' in
07019     * a header, although RFC3261 clearly says you shouldn't before, and place just
07020     * one afterwards.  If you shouldn't do it, what absolute idiot decided it was 
07021     * a good idea to say you can do it, and if you can do it, why in the hell would.
07022     * you say you shouldn't.
07023     * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
07024     * and we always allow spaces after that for compatibility.
07025     */
07026    for (pass = 0; name && pass < 2;pass++) {
07027       int x, len = strlen(name);
07028       for (x = *start; x < req->headers; x++) {
07029          char *header = REQ_OFFSET_TO_STR(req, header[x]);
07030          if (!strncasecmp(header, name, len)) {
07031             char *r = header + len; /* skip name */
07032             if (sip_cfg.pedanticsipchecking)
07033                r = ast_skip_blanks(r);
07034 
07035             if (*r == ':') {
07036                *start = x+1;
07037                return ast_skip_blanks(r+1);
07038             }
07039          }
07040       }
07041       if (pass == 0) /* Try aliases */
07042          name = find_alias(name, NULL);
07043    }
07044 
07045    /* Don't return NULL, so get_header is always a valid pointer */
07046    return "";
07047 }
07048 
07049 /*! \brief Get header from SIP request 
07050    \return Always return something, so don't check for NULL because it won't happen :-)
07051 */
07052 static const char *get_header(const struct sip_request *req, const char *name)
07053 {
07054    int start = 0;
07055    return __get_header(req, name, &start);
07056 }
07057 
07058 /*! \brief Read RTP from network */
07059 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
07060 {
07061    /* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
07062    struct ast_frame *f;
07063    
07064    if (!p->rtp) {
07065       /* We have no RTP allocated for this channel */
07066       return &ast_null_frame;
07067    }
07068 
07069    switch(ast->fdno) {
07070    case 0:
07071       f = ast_rtp_read(p->rtp);  /* RTP Audio */
07072       break;
07073    case 1:
07074       f = ast_rtcp_read(p->rtp); /* RTCP Control Channel */
07075       break;
07076    case 2:
07077       f = ast_rtp_read(p->vrtp); /* RTP Video */
07078       break;
07079    case 3:
07080       f = ast_rtcp_read(p->vrtp);   /* RTCP Control Channel for video */
07081       break;
07082    case 4:
07083       f = ast_rtp_read(p->trtp); /* RTP Text */
07084       if (sipdebug_text) {
07085          int i;
07086          unsigned char* arr = f->data.ptr;
07087          for (i=0; i < f->datalen; i++)
07088             ast_verbose("%c", (arr[i] > ' ' && arr[i] < '}') ? arr[i] : '.');
07089          ast_verbose(" -> ");
07090          for (i=0; i < f->datalen; i++)
07091             ast_verbose("%02X ", arr[i]);
07092          ast_verbose("\n");
07093       }
07094       break;
07095    case 5:
07096       f = ast_udptl_read(p->udptl); /* UDPTL for T.38 */
07097       break;
07098    default:
07099       f = &ast_null_frame;
07100    }
07101    /* Don't forward RFC2833 if we're not supposed to */
07102    if (f && (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) &&
07103        (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833)) {
07104       ast_debug(1, "Ignoring DTMF (%c) RTP frame because dtmfmode is not RFC2833\n", f->subclass);
07105       return &ast_null_frame;
07106    }
07107 
07108    /* We already hold the channel lock */
07109    if (!p->owner || (f && f->frametype != AST_FRAME_VOICE))
07110       return f;
07111 
07112    if (f && f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
07113       if (!(f->subclass & p->jointcapability)) {
07114          ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
07115             ast_getformatname(f->subclass), p->owner->name);
07116          return &ast_null_frame;
07117       }
07118       ast_debug(1, "Oooh, format changed to %d %s\n",
07119          f->subclass, ast_getformatname(f->subclass));
07120       p->owner->nativeformats = (p->owner->nativeformats & (AST_FORMAT_VIDEO_MASK | AST_FORMAT_TEXT_MASK)) | f->subclass;
07121       ast_set_read_format(p->owner, p->owner->readformat);
07122       ast_set_write_format(p->owner, p->owner->writeformat);
07123    }
07124 
07125    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) {
07126       f = ast_dsp_process(p->owner, p->dsp, f);
07127                 if (f && f->frametype == AST_FRAME_DTMF) {
07128          if (f->subclass == 'f') {
07129                                 if (option_debug)
07130                                         ast_log(LOG_DEBUG, "Fax CNG detected on %s\n", ast->name);
07131                                 *faxdetect = 1;
07132             /* If we only needed this DSP for fax detection purposes we can just drop it now */
07133             if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
07134                ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
07135             } else {
07136                ast_dsp_free(p->dsp);
07137                p->dsp = NULL;
07138             }
07139          } else {
07140             ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass);
07141          }
07142       }
07143    }
07144    
07145    return f;
07146 }
07147 
07148 /*! \brief Read SIP RTP from channel */
07149 static struct ast_frame *sip_read(struct ast_channel *ast)
07150 {
07151    struct ast_frame *fr;
07152    struct sip_pvt *p = ast->tech_pvt;
07153    int faxdetected = FALSE;
07154 
07155    sip_pvt_lock(p);
07156    fr = sip_rtp_read(ast, p, &faxdetected);
07157    p->lastrtprx = time(NULL);
07158 
07159    /* If we detect a CNG tone and fax detection is enabled then send us off to the fax extension */
07160    if (faxdetected && ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
07161       ast_channel_lock(ast);
07162       if (strcmp(ast->exten, "fax")) {
07163          const char *target_context = S_OR(ast->macrocontext, ast->context);
07164          ast_channel_unlock(ast);
07165          if (ast_exists_extension(ast, target_context, "fax", 1, ast->cid.cid_num)) {
07166             ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to CNG detection\n", ast->name);
07167             pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
07168             if (ast_async_goto(ast, target_context, "fax", 1)) {
07169                ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast->name, target_context);
07170             }
07171             fr = &ast_null_frame;
07172          } else {
07173             ast_log(LOG_NOTICE, "FAX CNG detected but no fax extension\n");
07174                         }
07175       } else {
07176          ast_channel_unlock(ast);
07177                 }
07178         }
07179 
07180    /* Only allow audio through if they sent progress with SDP, or if the channel is actually answered */
07181    if (fr && fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast->_state != AST_STATE_UP) {
07182       fr = &ast_null_frame;
07183    }
07184 
07185    sip_pvt_unlock(p);
07186 
07187    return fr;
07188 }
07189 
07190 
07191 /*! \brief Generate 32 byte random string for callid's etc */
07192 static char *generate_random_string(char *buf, size_t size)
07193 {
07194    long val[4];
07195    int x;
07196 
07197    for (x=0; x<4; x++)
07198       val[x] = ast_random();
07199    snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
07200 
07201    return buf;
07202 }
07203 
07204 /*! \brief Build SIP Call-ID value for a non-REGISTER transaction */
07205 static void build_callid_pvt(struct sip_pvt *pvt)
07206 {
07207    char buf[33];
07208 
07209    const char *host = S_OR(pvt->fromdomain, ast_inet_ntoa(pvt->ourip.sin_addr));
07210    
07211    ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07212 
07213 }
07214 
07215 /*! \brief Build SIP Call-ID value for a REGISTER transaction */
07216 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain)
07217 {
07218    char buf[33];
07219 
07220    const char *host = S_OR(fromdomain, ast_inet_ntoa(ourip));
07221 
07222    ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07223 }
07224 
07225 /*! \brief Make our SIP dialog tag */
07226 static void make_our_tag(char *tagbuf, size_t len)
07227 {
07228    snprintf(tagbuf, len, "as%08lx", ast_random());
07229 }
07230 
07231 /*! \brief Allocate Session-Timers struct w/in dialog */
07232 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
07233 {
07234    struct sip_st_dlg *stp;
07235 
07236    if (p->stimer) {
07237       ast_log(LOG_ERROR, "Session-Timer struct already allocated\n");
07238       return p->stimer;
07239    }
07240 
07241    if (!(stp = ast_calloc(1, sizeof(struct sip_st_dlg))))
07242       return NULL;
07243 
07244    p->stimer = stp;
07245 
07246    stp->st_schedid = -1;           /* Session-Timers ast_sched scheduler id */
07247 
07248    return p->stimer;
07249 }
07250 
07251 /*! \brief Allocate sip_pvt structure, set defaults and link in the container.
07252  * Returns a reference to the object so whoever uses it later must
07253  * remember to release the reference.
07254  */
07255 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
07256              int useglobal_nat, const int intended_method, struct sip_request *req)
07257 {
07258    struct sip_pvt *p;
07259 
07260    if (!(p = ao2_t_alloc(sizeof(*p), sip_destroy_fn, "allocate a dialog(pvt) struct")))
07261       return NULL;
07262 
07263    if (ast_string_field_init(p, 512)) {
07264       ao2_t_ref(p, -1, "failed to string_field_init, drop p");
07265       return NULL;
07266    }
07267 
07268    if (req) {
07269       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 */
07270    } else {
07271       set_socket_transport(&p->socket, SIP_TRANSPORT_UDP);
07272    }
07273 
07274    p->socket.fd = -1;
07275    p->method = intended_method;
07276    p->initid = -1;
07277    p->waitid = -1;
07278    p->autokillid = -1;
07279    p->request_queue_sched_id = -1;
07280    p->provisional_keepalive_sched_id = -1;
07281    p->t38id = -1;
07282    p->subscribed = NONE;
07283    p->stateid = -1;
07284    p->sessionversion_remote = -1;
07285    p->session_modify = TRUE;
07286    p->stimer = NULL;
07287    p->prefs = default_prefs;     /* Set default codecs for this call */
07288 
07289    if (intended_method != SIP_OPTIONS) {  /* Peerpoke has it's own system */
07290       p->timer_t1 = global_t1;   /* Default SIP retransmission timer T1 (RFC 3261) */
07291       p->timer_b = global_timer_b;  /* Default SIP transaction timer B (RFC 3261) */
07292    }
07293 
07294    if (!sin)
07295       p->ourip = internip;
07296    else {
07297       p->sa = *sin;
07298       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
07299    }
07300 
07301    /* Copy global flags to this PVT at setup. */
07302    ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
07303    ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
07304 
07305    p->do_history = recordhistory;
07306 
07307    p->branch = ast_random();  
07308    make_our_tag(p->tag, sizeof(p->tag));
07309    p->ocseq = INITIAL_CSEQ;
07310 
07311    if (sip_methods[intended_method].need_rtp) {
07312       p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
07313       /* If the global videosupport flag is on, we always create a RTP interface for video */
07314       if (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
07315             ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS))
07316          p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
07317       if (ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT))
07318          p->trtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
07319       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
07320          if (!(p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr))) {
07321             /* udptl creation failed, T38 can not be supported on this dialog */
07322             ast_log(LOG_ERROR, "UDPTL creation failed\n");
07323             ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
07324          }
07325       }
07326       if (!p->rtp|| (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) && !p->vrtp) 
07327             || (ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) && !p->trtp)) {
07328          ast_log(LOG_WARNING, "Unable to create RTP audio %s%ssession: %s\n",
07329             ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "and video " : "",
07330             ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "and text " : "", strerror(errno));
07331          if (p->chanvars) {
07332             ast_variables_destroy(p->chanvars);
07333             p->chanvars = NULL;
07334          }
07335          ao2_t_ref(p, -1, "failed to create RTP audio session, drop p");
07336          return NULL;
07337          p->t38_maxdatagram = global_t38_maxdatagram;
07338       }
07339       ast_rtp_setqos(p->rtp, global_tos_audio, global_cos_audio, "SIP RTP");
07340       ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
07341       ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
07342       ast_rtp_set_rtptimeout(p->rtp, global_rtptimeout);
07343       ast_rtp_set_rtpholdtimeout(p->rtp, global_rtpholdtimeout);
07344       ast_rtp_set_rtpkeepalive(p->rtp, global_rtpkeepalive);
07345       if (p->vrtp) {
07346          ast_rtp_setqos(p->vrtp, global_tos_video, global_cos_video, "SIP VRTP");
07347          ast_rtp_setdtmf(p->vrtp, 0);
07348          ast_rtp_setdtmfcompensate(p->vrtp, 0);
07349          ast_rtp_set_rtptimeout(p->vrtp, global_rtptimeout);
07350          ast_rtp_set_rtpholdtimeout(p->vrtp, global_rtpholdtimeout);
07351          ast_rtp_set_rtpkeepalive(p->vrtp, global_rtpkeepalive);
07352       }
07353       if (p->trtp) {
07354          ast_rtp_setqos(p->trtp, global_tos_text, global_cos_text, "SIP TRTP");
07355          ast_rtp_setdtmf(p->trtp, 0);
07356          ast_rtp_setdtmfcompensate(p->trtp, 0);
07357       }
07358       if (p->udptl)
07359          ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
07360       p->maxcallbitrate = default_maxcallbitrate;
07361       p->autoframing = global_autoframing;
07362       ast_rtp_codec_setpref(p->rtp, &p->prefs);
07363    }
07364 
07365    if (useglobal_nat && sin) {
07366       /* Setup NAT structure according to global settings if we have an address */
07367       ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
07368       p->recv = *sin;
07369       do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
07370    }
07371 
07372    if (p->method != SIP_REGISTER)
07373       ast_string_field_set(p, fromdomain, default_fromdomain);
07374    build_via(p);
07375    if (!callid)
07376       build_callid_pvt(p);
07377    else
07378       ast_string_field_set(p, callid, callid);
07379    /* Assign default music on hold class */
07380    ast_string_field_set(p, mohinterpret, default_mohinterpret);
07381    ast_string_field_set(p, mohsuggest, default_mohsuggest);
07382    p->capability = global_capability;
07383    p->allowtransfer = sip_cfg.allowtransfer;
07384    if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
07385        (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
07386       p->noncodeccapability |= AST_RTP_DTMF;
07387    if (p->udptl) {
07388       p->t38_maxdatagram = global_t38_maxdatagram;
07389       set_t38_capabilities(p);
07390    }
07391    ast_string_field_set(p, context, sip_cfg.default_context);
07392    ast_string_field_set(p, parkinglot, default_parkinglot);
07393 
07394    AST_LIST_HEAD_INIT_NOLOCK(&p->request_queue);
07395 
07396    /* Add to active dialog list */
07397 
07398    ao2_t_link(dialogs, p, "link pvt into dialogs table");
07399    
07400    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");
07401    return p;
07402 }
07403 
07404 /*! \brief argument to the helper function to identify a call */
07405 struct find_call_cb_arg {
07406    enum sipmethod method;
07407    const char *callid;
07408    const char *fromtag;
07409    const char *totag;
07410    const char *tag;
07411 };
07412 
07413 /*!
07414  * code to determine whether this is the pvt that we are looking for.
07415  * Return FALSE if not found, true otherwise. p is unlocked.
07416  */
07417 static int find_call_cb(void *__pvt, void *__arg, int flags)
07418 {
07419    struct sip_pvt *p = __pvt;
07420    struct find_call_cb_arg *arg = __arg;
07421    /* In pedantic, we do not want packets with bad syntax to be connected to a PVT */
07422    int found = FALSE;
07423    
07424    if (!ast_strlen_zero(p->callid)) { /* XXX double check, do we allow match on empty p->callid ? */
07425       if (arg->method == SIP_REGISTER)
07426          found = (!strcmp(p->callid, arg->callid));
07427       else {
07428          found = !strcmp(p->callid, arg->callid);
07429          if (sip_cfg.pedanticsipchecking && found) {
07430             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);
07431          } 
07432       }
07433       
07434       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);
07435       
07436       /* If we get a new request within an existing to-tag - check the to tag as well */
07437       if (sip_cfg.pedanticsipchecking && found && arg->method != SIP_RESPONSE) { /* SIP Request */
07438          if (p->tag[0] == '\0' && arg->totag[0]) {
07439             /* We have no to tag, but they have. Wrong dialog */
07440             found = FALSE;
07441          } else if (arg->totag[0]) { /* Both have tags, compare them */
07442             if (strcmp(arg->totag, p->tag)) {
07443                found = FALSE; /* This is not our packet */
07444             }
07445          }
07446          if (!found)
07447             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);
07448       }
07449    }
07450    return found;
07451 }
07452 
07453 /*! \brief find or create a dialog structure for an incoming SIP message.
07454  * Connect incoming SIP message to current dialog or create new dialog structure
07455  * Returns a reference to the sip_pvt object, remember to give it back once done.
07456  *     Called by handle_incoming(), sipsock_read
07457  */
07458 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
07459 {
07460    struct sip_pvt *p = NULL;
07461    char *tag = "";   /* note, tag is never NULL */
07462    char totag[128];
07463    char fromtag[128];
07464    struct find_call_cb_arg arg;
07465    const char *callid = get_header(req, "Call-ID");
07466    const char *from = get_header(req, "From");
07467    const char *to = get_header(req, "To");
07468    const char *cseq = get_header(req, "Cseq");
07469    struct sip_pvt *sip_pvt_ptr;
07470 
07471    /* Call-ID, to, from and Cseq are required by RFC 3261. (Max-forwards and via too - ignored now) */
07472    /* get_header always returns non-NULL so we must use ast_strlen_zero() */
07473    if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
07474          ast_strlen_zero(from) || ast_strlen_zero(cseq))
07475       return NULL;   /* Invalid packet */
07476 
07477    arg.method = req->method;
07478    arg.callid = callid;
07479    arg.fromtag = fromtag;
07480    arg.totag = totag;
07481    arg.tag = ""; /* make sure tag is never NULL */
07482 
07483    if (sip_cfg.pedanticsipchecking) {
07484       /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
07485          we need more to identify a branch - so we have to check branch, from
07486          and to tags to identify a call leg.
07487          For Asterisk to behave correctly, you need to turn on pedanticsipchecking
07488          in sip.conf
07489          */
07490       if (gettag(req, "To", totag, sizeof(totag)))
07491          req->has_to_tag = 1; /* Used in handle_request/response */
07492       gettag(req, "From", fromtag, sizeof(fromtag));
07493 
07494       tag = (req->method == SIP_RESPONSE) ? totag : fromtag;
07495 
07496       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);
07497 
07498       /* All messages must always have From: tag */
07499       if (ast_strlen_zero(fromtag)) {
07500          ast_debug(5, "%s request has no from tag, dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
07501          return NULL;
07502       }
07503       /* reject requests that must always have a To: tag */
07504       if (ast_strlen_zero(totag) && (req->method == SIP_ACK || req->method == SIP_BYE || req->method == SIP_INFO )) {
07505          ast_debug(5, "%s must have a to tag. dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
07506          return NULL;
07507       }
07508    }
07509 
07510 restartsearch:
07511    if (!sip_cfg.pedanticsipchecking) {
07512       struct sip_pvt tmp_dialog = {
07513          .callid = callid,
07514       };       
07515       sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find in dialogs");
07516       if (sip_pvt_ptr) {  /* well, if we don't find it-- what IS in there? */
07517          /* Found the call */
07518          sip_pvt_lock(sip_pvt_ptr);
07519          return sip_pvt_ptr;
07520       }
07521    } else { /* in pedantic mode! -- do the fancy linear search */
07522       ao2_lock(dialogs);
07523       p = ao2_t_callback(dialogs, 0 /* single, data */, find_call_cb, &arg, "pedantic linear search for dialog");
07524       if (p) {
07525          if (sip_pvt_trylock(p)) {
07526             ao2_unlock(dialogs);
07527             usleep(1);
07528             goto restartsearch;
07529          }
07530          ao2_unlock(dialogs);
07531          return p;
07532       }
07533       ao2_unlock(dialogs);
07534    }
07535  
07536    /* See if the method is capable of creating a dialog */
07537    if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
07538       if (intended_method == SIP_REFER) {
07539          /* We do support REFER, but not outside of a dialog yet */
07540          transmit_response_using_temp(callid, sin, 1, intended_method, req, "603 Declined (no dialog)");
07541       } else if (intended_method == SIP_NOTIFY) {
07542          /* We do not support out-of-dialog NOTIFY either,
07543             like voicemail notification, so cancel that early */
07544          transmit_response_using_temp(callid, sin, 1, intended_method, req, "481 No subscription");
07545       } else {
07546          /* Ok, time to create a new SIP dialog object, a pvt */
07547          if ((p = sip_alloc(callid, sin, 1, intended_method, req)))  {
07548             /* Ok, we've created a dialog, let's go and process it */
07549             sip_pvt_lock(p);
07550          } else {
07551             /* We have a memory or file/socket error (can't allocate RTP sockets or something) so we're not
07552                getting a dialog from sip_alloc. 
07553    
07554                Without a dialog we can't retransmit and handle ACKs and all that, but at least
07555                send an error message.
07556    
07557                Sorry, we apologize for the inconvienience
07558             */
07559             transmit_response_using_temp(callid, sin, 1, intended_method, req, "500 Server internal error");
07560             ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
07561          }
07562       }
07563       return p; /* can be NULL */
07564    } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
07565       /* A method we do not support, let's take it on the volley */
07566       transmit_response_using_temp(callid, sin, 1, intended_method, req, "501 Method Not Implemented");
07567       ast_debug(2, "Got a request with unsupported SIP method.\n");
07568    } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
07569       /* This is a request outside of a dialog that we don't know about */
07570       transmit_response_using_temp(callid, sin, 1, intended_method, req, "481 Call leg/transaction does not exist");
07571       ast_debug(2, "That's odd...  Got a request in unknown dialog. Callid %s\n", callid ? callid : "<unknown>");
07572    }
07573    /* We do not respond to responses for dialogs that we don't know about, we just drop
07574       the session quickly */
07575    if (intended_method == SIP_RESPONSE)
07576       ast_debug(2, "That's odd...  Got a response on a call we don't know about. Callid %s\n", callid ? callid : "<unknown>");
07577 
07578    return NULL;
07579 }
07580 
07581 /*! \brief Parse register=> line in sip.conf and add to registry */
07582 static int sip_register(const char *value, int lineno)
07583 {
07584    struct sip_registry *reg;
07585    int portnum = 0;
07586    enum sip_transport transport = SIP_TRANSPORT_UDP;
07587    char buf[256] = "";
07588    char *userpart = NULL, *hostpart = NULL;
07589    /* register => [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] */
07590    AST_DECLARE_APP_ARGS(pre1,
07591       AST_APP_ARG(peer);
07592       AST_APP_ARG(userpart);
07593    );
07594    AST_DECLARE_APP_ARGS(pre2,
07595       AST_APP_ARG(transport);
07596       AST_APP_ARG(blank);
07597       AST_APP_ARG(userpart);
07598    );
07599    AST_DECLARE_APP_ARGS(user1,
07600       AST_APP_ARG(userpart);
07601       AST_APP_ARG(secret);
07602       AST_APP_ARG(authuser);
07603    );
07604    AST_DECLARE_APP_ARGS(host1,
07605       AST_APP_ARG(hostpart);
07606       AST_APP_ARG(expiry);
07607    );
07608    AST_DECLARE_APP_ARGS(host2,
07609       AST_APP_ARG(hostpart);
07610       AST_APP_ARG(extension);
07611    );
07612    AST_DECLARE_APP_ARGS(host3,
07613       AST_APP_ARG(host);
07614       AST_APP_ARG(port);
07615    );
07616 
07617    if (!value)
07618       return -1;
07619    ast_copy_string(buf, value, sizeof(buf));
07620 
07621    /*! register => [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry]
07622     * becomes
07623     *   userpart => [peer?][transport://]user[@domain][:secret[:authuser]]
07624     *   hostpart => host[:port][/extension][~expiry]
07625     */
07626    if ((hostpart = strrchr(buf, '@'))) {
07627       *hostpart++ = '\0';
07628       userpart = buf;
07629    }
07630 
07631    if (ast_strlen_zero(userpart) || ast_strlen_zero(hostpart)) {
07632       ast_log(LOG_WARNING, "Format for registration is [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] at line %d\n", lineno);
07633       return -1;
07634    }
07635 
07636    /*!
07637     * pre1.peer => peer
07638     * pre1.userpart => [transport://]user[@domain][:secret[:authuser]]
07639     * hostpart => host[:port][/extension][~expiry]
07640     */
07641    AST_NONSTANDARD_RAW_ARGS(pre1, userpart, '?');
07642    if (ast_strlen_zero(pre1.userpart)) {
07643       pre1.userpart = pre1.peer;
07644       pre1.peer = NULL;
07645    }
07646 
07647    /*!
07648     * pre1.peer => peer
07649     * pre2.transport = transport
07650     * pre2.userpart => user[@domain][:secret[:authuser]]
07651     * hostpart => host[:port][/extension][~expiry]
07652     */
07653    AST_NONSTANDARD_RAW_ARGS(pre2, pre1.userpart, '/');
07654    if (ast_strlen_zero(pre2.userpart)) {
07655       pre2.userpart = pre2.transport;
07656       pre2.transport = NULL;
07657    } else {
07658       pre2.transport[strlen(pre2.transport) - 1] = '\0'; /* Remove trailing : */
07659    }
07660 
07661    if (!ast_strlen_zero(pre2.blank)) {
07662       ast_log(LOG_WARNING, "Format for registration is [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] at line %d\n", lineno);
07663       return -1;
07664    }
07665 
07666    /*!
07667     * pre1.peer => peer
07668     * pre2.transport = transport
07669     * user1.userpart => user[@domain]
07670     * user1.secret => secret
07671     * user1.authuser => authuser
07672     * hostpart => host[:port][/extension][~expiry]
07673     */
07674    AST_NONSTANDARD_RAW_ARGS(user1, pre2.userpart, ':');
07675 
07676    /*!
07677     * pre1.peer => peer
07678     * pre2.transport = transport
07679     * user1.userpart => user[@domain]
07680     * user1.secret => secret
07681     * user1.authuser => authuser
07682     * host1.hostpart => host[:port][/extension]
07683     * host1.expiry => [expiry]
07684     */
07685    AST_NONSTANDARD_RAW_ARGS(host1, hostpart, '~');
07686 
07687    /*!
07688     * pre1.peer => peer
07689     * pre2.transport = transport
07690     * user1.userpart => user[@domain]
07691     * user1.secret => secret
07692     * user1.authuser => authuser
07693     * host2.hostpart => host[:port]
07694     * host2.extension => [extension]
07695     * host1.expiry => [expiry]
07696     */
07697    AST_NONSTANDARD_RAW_ARGS(host2, host1.hostpart, '/');
07698 
07699    /*!
07700     * pre1.peer => peer
07701     * pre2.transport = transport
07702     * user1.userpart => user[@domain]
07703     * user1.secret => secret
07704     * user1.authuser => authuser
07705     * host3.host => host
07706     * host3.port => port
07707     * host2.extension => extension
07708     * host1.expiry => expiry
07709     */
07710    AST_NONSTANDARD_RAW_ARGS(host3, host2.hostpart, ':');
07711 
07712    if (host3.port) {
07713       if (!(portnum = port_str2int(host3.port, 0))) {
07714          ast_log(LOG_NOTICE, "'%s' is not a valid port number on line %d of sip.conf. using default.\n", host3.port, lineno);
07715       }
07716    }
07717 
07718    /* set transport type */
07719    if (!pre2.transport) {
07720       transport = SIP_TRANSPORT_UDP;
07721    } else if (!strncasecmp(pre2.transport, "tcp", 3)) {
07722       transport = SIP_TRANSPORT_TCP;
07723    } else if (!strncasecmp(pre2.transport, "tls", 3)) {
07724       transport = SIP_TRANSPORT_TLS;
07725    } else if (!strncasecmp(pre2.transport, "udp", 3)) {
07726       transport = SIP_TRANSPORT_UDP;
07727    } else {
07728       transport = SIP_TRANSPORT_UDP;
07729       ast_log(LOG_NOTICE, "'%.3s' is not a valid transport type on line %d of sip.conf. defaulting to udp.\n", pre2.transport, lineno);
07730    }
07731 
07732    /* if no portnum specified, set default for transport */
07733    if (!portnum) {
07734       if (transport == SIP_TRANSPORT_TLS) {
07735          portnum = STANDARD_TLS_PORT;
07736       } else {
07737          portnum = STANDARD_SIP_PORT;
07738       }
07739    }
07740 
07741    if (!(reg = ast_calloc(1, sizeof(*reg)))) {
07742       ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
07743       return -1;
07744    }
07745 
07746    if (ast_string_field_init(reg, 256)) {
07747       ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry strings\n");
07748       ast_free(reg);
07749       return -1;
07750    }
07751 
07752    ast_atomic_fetchadd_int(&regobjs, 1);
07753    ASTOBJ_INIT(reg);
07754    ast_string_field_set(reg, callback, ast_strip_quoted(S_OR(host2.extension, "s"), "\"", "\""));
07755    ast_string_field_set(reg, username, ast_strip_quoted(S_OR(user1.userpart, ""), "\"", "\""));
07756    ast_string_field_set(reg, hostname, ast_strip_quoted(S_OR(host3.host, ""), "\"", "\""));
07757    ast_string_field_set(reg, authuser, ast_strip_quoted(S_OR(user1.authuser, ""), "\"", "\""));
07758    ast_string_field_set(reg, secret, ast_strip_quoted(S_OR(user1.secret, ""), "\"", "\""));
07759    ast_string_field_set(reg, peername, ast_strip_quoted(S_OR(pre1.peer, ""), "\"", "\""));
07760 
07761    reg->transport = transport;
07762    reg->timeout = reg->expire = -1;
07763    reg->refresh = reg->expiry = reg->configured_expiry = (host1.expiry ? atoi(ast_strip_quoted(host1.expiry, "\"", "\"")) : default_expiry);
07764    reg->portno = portnum;
07765    reg->callid_valid = FALSE;
07766    reg->ocseq = INITIAL_CSEQ;
07767    ASTOBJ_CONTAINER_LINK(&regl, reg); /* Add the new registry entry to the list */
07768    registry_unref(reg, "unref the reg pointer");   /* release the reference given by ASTOBJ_INIT. The container has another reference */
07769    return 0;
07770 }
07771 
07772 /*! \brief Parse mwi=> line in sip.conf and add to list */
07773 static int sip_subscribe_mwi(const char *value, int lineno)
07774 {
07775    struct sip_subscription_mwi *mwi;
07776    int portnum = 0;
07777    enum sip_transport transport = SIP_TRANSPORT_UDP;
07778    char buf[256] = "";
07779    char *username = NULL, *hostname = NULL, *secret = NULL, *authuser = NULL, *porta = NULL, *mailbox = NULL;
07780    
07781    if (!value) {
07782       return -1;
07783    }
07784    
07785    ast_copy_string(buf, value, sizeof(buf));
07786 
07787    sip_parse_host(buf, lineno, &username, &portnum, &transport);
07788    
07789    if ((hostname = strrchr(username, '@'))) {
07790       *hostname++ = '\0';
07791    }
07792    
07793    if ((secret = strchr(username, ':'))) {
07794       *secret++ = '\0';
07795       if ((authuser = strchr(secret, ':'))) {
07796          *authuser++ = '\0';
07797       }
07798    }
07799    
07800    if ((mailbox = strchr(hostname, '/'))) {
07801       *mailbox++ = '\0';
07802    }
07803 
07804    if (ast_strlen_zero(username) || ast_strlen_zero(hostname) || ast_strlen_zero(mailbox)) {
07805       ast_log(LOG_WARNING, "Format for MWI subscription is user[:secret[:authuser]]@host[:port][/mailbox] at line %d\n", lineno);
07806       return -1;
07807    }
07808    
07809    if ((porta = strchr(hostname, ':'))) {
07810       *porta++ = '\0';
07811       if (!(portnum = atoi(porta))) {
07812          ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
07813          return -1;
07814       }
07815    }
07816    
07817    if (!(mwi = ast_calloc(1, sizeof(*mwi)))) {
07818       return -1;
07819    }
07820    
07821    if (ast_string_field_init(mwi, 256)) {
07822       ast_free(mwi);
07823       return -1;
07824    }
07825    
07826    ASTOBJ_INIT(mwi);
07827    ast_string_field_set(mwi, username, username);
07828    if (secret) {
07829       ast_string_field_set(mwi, secret, secret);
07830    }
07831    if (authuser) {
07832       ast_string_field_set(mwi, authuser, authuser);
07833    }
07834    ast_string_field_set(mwi, hostname, hostname);
07835    ast_string_field_set(mwi, mailbox, mailbox);
07836    mwi->resub = -1;
07837    mwi->portno = portnum;
07838    mwi->transport = transport;
07839    
07840    ASTOBJ_CONTAINER_LINK(&submwil, mwi);
07841    ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
07842    
07843    return 0;
07844 }
07845 
07846 /*! \brief  Parse multiline SIP headers into one header
07847    This is enabled if pedanticsipchecking is enabled */
07848 static int lws2sws(char *msgbuf, int len) 
07849 {
07850    int h = 0, t = 0; 
07851    int lws = 0; 
07852 
07853    for (; h < len;) { 
07854       /* Eliminate all CRs */ 
07855       if (msgbuf[h] == '\r') { 
07856          h++; 
07857          continue; 
07858       } 
07859       /* Check for end-of-line */ 
07860       if (msgbuf[h] == '\n') { 
07861          /* Check for end-of-message */ 
07862          if (h + 1 == len) 
07863             break; 
07864          /* Check for a continuation line */ 
07865          if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') { 
07866             /* Merge continuation line */ 
07867             h++; 
07868             continue; 
07869          } 
07870          /* Propagate LF and start new line */ 
07871          msgbuf[t++] = msgbuf[h++]; 
07872          lws = 0;
07873          continue; 
07874       } 
07875       if (msgbuf[h] == ' ' || msgbuf[h] == '\t') { 
07876          if (lws) { 
07877             h++; 
07878             continue; 
07879          } 
07880          msgbuf[t++] = msgbuf[h++]; 
07881          lws = 1; 
07882          continue; 
07883       } 
07884       msgbuf[t++] = msgbuf[h++]; 
07885       if (lws) 
07886          lws = 0; 
07887    } 
07888    msgbuf[t] = '\0'; 
07889    return t; 
07890 }
07891 
07892 /*! \brief Parse a SIP message 
07893    \note this function is used both on incoming and outgoing packets
07894 */
07895 static int parse_request(struct sip_request *req)
07896 {
07897    char *c = req->data->str;
07898    ptrdiff_t *dst = req->header;
07899    int i = 0, lim = SIP_MAX_HEADERS - 1;
07900    unsigned int skipping_headers = 0;
07901    ptrdiff_t current_header_offset = 0;
07902    char *previous_header = "";
07903 
07904    req->header[0] = 0;
07905    req->headers = -1;   /* mark that we are working on the header */
07906    for (; *c; c++) {
07907       if (*c == '\r') {    /* remove \r */
07908          *c = '\0';
07909       } else if (*c == '\n') {   /* end of this line */
07910          *c = '\0';
07911          current_header_offset = (c + 1) - req->data->str;
07912          previous_header = req->data->str + dst[i];
07913          if (skipping_headers) {
07914             /* check to see if this line is blank; if so, turn off
07915                the skipping flag, so the next line will be processed
07916                as a body line */
07917             if (ast_strlen_zero(previous_header)) {
07918                skipping_headers = 0;
07919             }
07920             dst[i] = current_header_offset; /* record start of next line */
07921             continue;
07922          }
07923          if (sipdebug) {
07924             ast_debug(4, "%7s %2d [%3d]: %s\n",
07925                  req->headers < 0 ? "Header" : "Body",
07926                  i, (int) strlen(previous_header), previous_header);
07927          }
07928          if (ast_strlen_zero(previous_header) && req->headers < 0) {
07929             req->headers = i; /* record number of header lines */
07930             dst = req->line;  /* start working on the body */
07931             i = 0;
07932             lim = SIP_MAX_LINES - 1;
07933          } else { /* move to next line, check for overflows */
07934             if (i++ == lim) {
07935                /* if we're processing headers, then skip any remaining
07936                   headers and move on to processing the body, otherwise
07937                   we're done */
07938                if (req->headers != -1) {
07939                   break;
07940                } else {
07941                   req->headers = i;
07942                   dst = req->line;
07943                   i = 0;
07944                   lim = SIP_MAX_LINES - 1;
07945                   skipping_headers = 1;
07946                }
07947             }
07948          }
07949          dst[i] = current_header_offset; /* record start of next line */
07950       }
07951    }
07952 
07953    /* Check for last header or body line without CRLF. The RFC for SDP requires CRLF,
07954       but since some devices send without, we'll be generous in what we accept. However,
07955       if we've already reached the maximum number of lines for portion of the message
07956       we were parsing, we can't accept any more, so just ignore it.
07957    */
07958    previous_header = req->data->str + dst[i];
07959    if ((i < lim) && !ast_strlen_zero(previous_header)) {
07960       if (sipdebug) {
07961          ast_debug(4, "%7s %2d [%3d]: %s\n",
07962               req->headers < 0 ? "Header" : "Body",
07963               i, (int) strlen(previous_header), previous_header );
07964       }
07965       i++;
07966    }
07967 
07968    /* update count of header or body lines */
07969    if (req->headers >= 0) {   /* we are in the body */
07970       req->lines = i;
07971    } else {       /* no body */
07972       req->headers = i;
07973       req->lines = 0;
07974       /* req->data->used will be a NULL byte */
07975       req->line[0] = ast_str_strlen(req->data);
07976    }
07977 
07978    if (*c) {
07979       ast_log(LOG_WARNING, "Too many lines, skipping <%s>\n", c);
07980    }
07981 
07982    /* Split up the first line parts */
07983    return determine_firstline_parts(req);
07984 }
07985 
07986 /*!
07987   \brief Determine whether a SIP message contains an SDP in its body
07988   \param req the SIP request to process
07989   \return 1 if SDP found, 0 if not found
07990 
07991   Also updates req->sdp_start and req->sdp_count to indicate where the SDP
07992   lives in the message body.
07993 */
07994 static int find_sdp(struct sip_request *req)
07995 {
07996    const char *content_type;
07997    const char *content_length;
07998    const char *search;
07999    char *boundary;
08000    unsigned int x;
08001    int boundaryisquoted = FALSE;
08002    int found_application_sdp = FALSE;
08003    int found_end_of_headers = FALSE;
08004 
08005    content_length = get_header(req, "Content-Length");
08006 
08007    if (!ast_strlen_zero(content_length)) {
08008       if (sscanf(content_length, "%30u", &x) != 1) {
08009          ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
08010          return 0;
08011       }
08012 
08013       /* Content-Length of zero means there can't possibly be an
08014          SDP here, even if the Content-Type says there is */
08015       if (x == 0)
08016          return 0;
08017    }
08018 
08019    content_type = get_header(req, "Content-Type");
08020 
08021    /* if the body contains only SDP, this is easy */
08022    if (!strncasecmp(content_type, "application/sdp", 15)) {
08023       req->sdp_start = 0;
08024       req->sdp_count = req->lines;
08025       return req->lines ? 1 : 0;
08026    }
08027 
08028    /* if it's not multipart/mixed, there cannot be an SDP */
08029    if (strncasecmp(content_type, "multipart/mixed", 15))
08030       return 0;
08031 
08032    /* if there is no boundary marker, it's invalid */
08033    if ((search = strcasestr(content_type, ";boundary=")))
08034       search += 10;
08035    else if ((search = strcasestr(content_type, "; boundary=")))
08036       search += 11;
08037    else
08038       return 0;
08039 
08040    if (ast_strlen_zero(search))
08041       return 0;
08042 
08043    /* If the boundary is quoted with ", remove quote */
08044    if (*search == '\"')  {
08045       search++;
08046       boundaryisquoted = TRUE;
08047    }
08048 
08049    /* make a duplicate of the string, with two extra characters
08050       at the beginning */
08051    boundary = ast_strdupa(search - 2);
08052    boundary[0] = boundary[1] = '-';
08053    /* Remove final quote */
08054    if (boundaryisquoted)
08055       boundary[strlen(boundary) - 1] = '\0';
08056 
08057    /* search for the boundary marker, the empty line delimiting headers from
08058       sdp part and the end boundry if it exists */
08059 
08060    for (x = 0; x < (req->lines); x++) {
08061       char *line = REQ_OFFSET_TO_STR(req, line[x]);
08062       if (!strncasecmp(line, boundary, strlen(boundary))){
08063          if (found_application_sdp && found_end_of_headers) {
08064             req->sdp_count = (x - 1) - req->sdp_start;
08065             return 1;
08066          }
08067          found_application_sdp = FALSE;
08068       }
08069       if (!strcasecmp(line, "Content-Type: application/sdp"))
08070          found_application_sdp = TRUE;
08071       
08072       if (ast_strlen_zero(line)) {
08073          if (found_application_sdp && !found_end_of_headers){
08074             req->sdp_start = x;
08075             found_end_of_headers = TRUE;
08076          }
08077       }
08078    }
08079    if (found_application_sdp && found_end_of_headers) {
08080       req->sdp_count = x - req->sdp_start;
08081       return TRUE;
08082    }
08083    return FALSE;
08084 }
08085 
08086 /*! \brief Change hold state for a call */
08087 static void change_hold_state(struct sip_pvt *dialog, struct sip_request *req, int holdstate, int sendonly)
08088 {
08089    if (sip_cfg.notifyhold && (!holdstate || !ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD)))
08090       sip_peer_hold(dialog, holdstate);
08091    if (sip_cfg.callevents)
08092       manager_event(EVENT_FLAG_CALL, "Hold",
08093                "Status: %s\r\n"
08094                "Channel: %s\r\n"
08095                "Uniqueid: %s\r\n",
08096                holdstate ? "On" : "Off",
08097                dialog->owner->name,
08098                dialog->owner->uniqueid);
08099    append_history(dialog, holdstate ? "Hold" : "Unhold", "%s", req->data->str);
08100    if (!holdstate) { /* Put off remote hold */
08101       ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD);   /* Clear both flags */
08102       return;
08103    }
08104    /* No address for RTP, we're on hold */
08105 
08106    if (sendonly == 1)   /* One directional hold (sendonly/recvonly) */
08107       ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
08108    else if (sendonly == 2) /* Inactive stream */
08109       ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
08110    else
08111       ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
08112    return;
08113 }
08114 
08115 enum media_type {
08116    SDP_AUDIO,
08117    SDP_VIDEO,
08118    SDP_IMAGE,
08119    SDP_TEXT,
08120 };
08121 
08122 static int get_ip_and_port_from_sdp(struct sip_request *req, const enum media_type media, struct sockaddr_in *sin)
08123 {
08124    const char *m;
08125    const char *c;
08126    int miterator = req->sdp_start;
08127    int citerator = req->sdp_start;
08128    int x = 0;
08129    int numberofports;
08130    int len;
08131    char host[258] = ""; /*Initialize to empty so we will know if we have any input */
08132    struct ast_hostent audiohp;
08133    struct hostent *hp;
08134 
08135    c = get_sdp_iterate(&citerator, req, "c");
08136    if (sscanf(c, "IN IP4 %256s", host) != 1) {
08137       ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
08138       /* Continue since there may be a valid host in a c= line specific to the audio stream */
08139    }
08140    /* We only want the m and c lines for audio */
08141    for (m = get_sdp_iterate(&miterator, req, "m"); !ast_strlen_zero(m); m = get_sdp_iterate(&miterator, req, "m")) {
08142       if ((media == SDP_AUDIO && ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08143           (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0))) ||
08144          (media == SDP_VIDEO && ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08145           (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len > 0)))) {
08146          /* See if there's a c= line for this media stream.
08147           * XXX There is no guarantee that we'll be grabbing the c= line for this
08148           * particular media stream here. However, this is the same logic used in process_sdp.
08149           */
08150          c = get_sdp_iterate(&citerator, req, "c");
08151          if (!ast_strlen_zero(c)) {
08152             sscanf(c, "IN IP4 %256s", host);
08153          }
08154          break;
08155       }
08156    }
08157 
08158    if (ast_strlen_zero(host) || x == 0) {
08159       ast_log(LOG_WARNING, "Failed to read an alternate host or port in SDP. Expect %s problems\n", media == SDP_AUDIO ? "audio" : "video");
08160       return -1;
08161    }
08162 
08163    hp = ast_gethostbyname(host, &audiohp);
08164    if (!hp) {
08165       ast_log(LOG_WARNING, "Could not look up IP address of alternate hostname. Expect %s problems\n", media == SDP_AUDIO? "audio" : "video");
08166       return -1;
08167    }
08168 
08169    memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
08170    sin->sin_port = htons(x);
08171    return 0;
08172 }
08173 
08174 /*! \brief Process SIP SDP offer, select formats and activate RTP channels
08175    If offer is rejected, we will not change any properties of the call
08176    Return 0 on success, a negative value on errors.
08177    Must be called after find_sdp().
08178 */
08179 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
08180 {
08181    /* Iterators for SDP parsing */
08182    int start = req->sdp_start;
08183    int next = start;
08184    int iterator = start;
08185 
08186    /* Temporary vars for SDP parsing */
08187    char type = '\0';
08188    const char *value = NULL;
08189    const char *m = NULL;           /* SDP media offer */
08190    const char *nextm = NULL;
08191    int len = -1;
08192 
08193    /* Host information */
08194    struct ast_hostent sessionhp;
08195    struct ast_hostent audiohp;
08196    struct ast_hostent videohp;
08197    struct ast_hostent texthp;
08198    struct ast_hostent imagehp;
08199    struct hostent *hp = NULL; /*!< RTP Audio host IP */
08200    struct hostent *vhp = NULL;   /*!< RTP video host IP */
08201    struct hostent *thp = NULL;   /*!< RTP text host IP */
08202    struct hostent *ihp = NULL;     /*!< UDPTL host ip */
08203    int portno = -1;     /*!< RTP Audio port number */
08204    int vportno = -1;    /*!< RTP Video port number */
08205    int tportno = -1;    /*!< RTP Text port number */
08206    int udptlportno = -1;      /*!< UDPTL Image port number */
08207    struct sockaddr_in sin = { 0, }; /*!< media socket address */
08208    struct sockaddr_in vsin = { 0, };   /*!< video socket address */
08209    struct sockaddr_in isin = { 0, };   /*!< image socket address */
08210    struct sockaddr_in tsin = { 0, };   /*!< text socket address */
08211 
08212    /* Peer capability is the capability in the SDP, non codec is RFC2833 DTMF (101) */ 
08213    int peercapability = 0, peernoncodeccapability = 0;
08214    int vpeercapability = 0, vpeernoncodeccapability = 0;
08215    int tpeercapability = 0, tpeernoncodeccapability = 0;
08216 
08217    struct ast_rtp *newaudiortp, *newvideortp, *newtextrtp;
08218    int newjointcapability;          /* Negotiated capability */
08219    int newpeercapability;
08220    int newnoncodeccapability;
08221 
08222    const char *codecs;
08223    int codec;
08224 
08225    /* Others */
08226    int sendonly = -1;
08227    int vsendonly = -1;
08228    int numberofports;
08229    int numberofmediastreams = 0;
08230    int last_rtpmap_codec = 0;
08231    int red_data_pt[10];    /* For T.140 red */
08232    int red_num_gen = 0;    /* For T.140 red */
08233    char red_fmtp[100] = "empty"; /* For T.140 red */
08234    int debug = sip_debug_test_pvt(p);
08235 
08236    /* START UNKNOWN */
08237    char buf[SIPBUFSIZE];
08238    /* END UNKNOWN */
08239 
08240    /* Initial check */
08241    if (!p->rtp) {
08242       ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
08243       return -1;
08244    }
08245 
08246    /* Initialize the temporary RTP structures we use to evaluate the offer from the peer */
08247 #ifdef LOW_MEMORY
08248    newaudiortp = ast_threadstorage_get(&ts_audio_rtp, ast_rtp_alloc_size());
08249 #else
08250    newaudiortp = alloca(ast_rtp_alloc_size());
08251 #endif
08252    memset(newaudiortp, 0, ast_rtp_alloc_size());
08253    ast_rtp_new_init(newaudiortp);
08254    ast_rtp_pt_clear(newaudiortp);
08255 
08256 #ifdef LOW_MEMORY
08257    newvideortp = ast_threadstorage_get(&ts_video_rtp, ast_rtp_alloc_size());
08258 #else
08259    newvideortp = alloca(ast_rtp_alloc_size());
08260 #endif
08261    memset(newvideortp, 0, ast_rtp_alloc_size());
08262    ast_rtp_new_init(newvideortp);
08263    ast_rtp_pt_clear(newvideortp);
08264 
08265 #ifdef LOW_MEMORY
08266    newtextrtp = ast_threadstorage_get(&ts_text_rtp, ast_rtp_alloc_size());
08267 #else
08268    newtextrtp = alloca(ast_rtp_alloc_size());
08269 #endif
08270    memset(newtextrtp, 0, ast_rtp_alloc_size());
08271    ast_rtp_new_init(newtextrtp);
08272    ast_rtp_pt_clear(newtextrtp);
08273 
08274    /* Update our last rtprx when we receive an SDP, too */
08275    p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
08276 
08277    memset(p->offered_media, 0, sizeof(p->offered_media));
08278 
08279 
08280    /* default: novideo and notext set */
08281    p->novideo = TRUE;
08282    p->notext = TRUE;
08283 
08284    if (p->vrtp)
08285       ast_rtp_pt_clear(newvideortp);  /* Must be cleared in case no m=video line exists */
08286  
08287    if (p->trtp)
08288       ast_rtp_pt_clear(newtextrtp);  /* Must be cleared in case no m=text line exists */
08289    
08290    /* Scan for the first media stream (m=) line to limit scanning of globals */
08291    nextm = get_sdp_iterate(&next, req, "m");
08292    if (ast_strlen_zero(nextm)) {
08293       ast_log(LOG_WARNING, "Insufficient information for SDP (m= not found)\n");
08294       return -1;
08295    }
08296 
08297    /* Scan session level SDP parameters (lines before first media stream) */
08298    while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
08299       int processed = FALSE;
08300       switch (type) {
08301       case 'o':
08302          /* If we end up receiving SDP that doesn't actually modify the session we don't want to treat this as a fatal
08303           * error. We just want to ignore the SDP and let the rest of the packet be handled as normal.
08304           */
08305          if (!process_sdp_o(value, p))
08306             return (p->session_modify == FALSE) ? 0 : -1;
08307          break;
08308       case 'c':
08309          if (process_sdp_c(value, &sessionhp)) {
08310             processed = TRUE;
08311             hp = &sessionhp.hp;
08312             vhp = hp;
08313             thp = hp;
08314             ihp = hp;
08315          }
08316          break;
08317       case 'a':
08318          if (process_sdp_a_sendonly(value, &sendonly)) {
08319             processed = TRUE;
08320             vsendonly = sendonly;
08321          }
08322          else if (process_sdp_a_audio(value, p, newaudiortp, &last_rtpmap_codec))
08323             processed = TRUE;
08324          else if (process_sdp_a_video(value, p, newvideortp, &last_rtpmap_codec))
08325             processed = TRUE;
08326          else if (process_sdp_a_text(value, p, newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
08327             processed = TRUE;
08328          else if (process_sdp_a_image(value, p))
08329             processed = TRUE;
08330          break;
08331       }
08332 
08333       if (option_debug > 2)
08334          ast_log(LOG_DEBUG, "Processing session-level SDP %c=%s... %s\n", type, value, (processed == TRUE)? "OK." : "UNSUPPORTED.");
08335    }
08336 
08337 
08338 
08339    /* Scan media stream (m=) specific parameters loop */
08340    while (!ast_strlen_zero(nextm)) {
08341       int audio = FALSE;
08342       int video = FALSE;
08343       int image = FALSE;
08344       int text = FALSE;
08345       int x;
08346 
08347       numberofports = 1;
08348       len = -1;
08349       start = next;
08350       m = nextm;
08351       iterator = next;
08352       nextm = get_sdp_iterate(&next, req, "m");
08353 
08354       /* Search for audio media definition */
08355       if ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08356           (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
08357          audio = TRUE;
08358          p->offered_media[SDP_AUDIO].offered = TRUE;
08359          numberofmediastreams++;
08360          portno = x;
08361 
08362          /* Scan through the RTP payload types specified in a "m=" line: */
08363          codecs = m + len;
08364          ast_copy_string(p->offered_media[SDP_AUDIO].text, codecs, sizeof(p->offered_media[SDP_AUDIO].text));
08365          for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08366             if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08367                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08368                return -1;
08369             }
08370             if (debug)
08371                ast_verbose("Found RTP audio format %d\n", codec);
08372 
08373             ast_rtp_set_m_type(newaudiortp, codec);
08374          }
08375       /* Search for video media definition */
08376       } else if ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08377             (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len >= 0)) {
08378          video = TRUE;
08379          p->novideo = FALSE;
08380          p->offered_media[SDP_VIDEO].offered = TRUE;
08381          numberofmediastreams++;
08382          vportno = x;
08383 
08384          /* Scan through the RTP payload types specified in a "m=" line: */
08385          codecs = m + len;
08386          ast_copy_string(p->offered_media[SDP_VIDEO].text, codecs, sizeof(p->offered_media[SDP_VIDEO].text));
08387          for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08388             if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08389                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08390                return -1;
08391             }
08392             if (debug)
08393                ast_verbose("Found RTP video format %d\n", codec);
08394             ast_rtp_set_m_type(newvideortp, codec);
08395          }
08396       /* Search for text media definition */
08397       } else if ((sscanf(m, "text %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08398             (sscanf(m, "text %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
08399          text = TRUE;
08400          p->notext = FALSE;
08401          p->offered_media[SDP_TEXT].offered = TRUE;
08402          numberofmediastreams++;
08403          tportno = x;
08404 
08405          /* Scan through the RTP payload types specified in a "m=" line: */
08406          codecs = m + len;
08407          ast_copy_string(p->offered_media[SDP_TEXT].text, codecs, sizeof(p->offered_media[SDP_TEXT].text));
08408          for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08409             if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08410                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08411                return -1;
08412             }
08413             if (debug)
08414                ast_verbose("Found RTP text format %d\n", codec);
08415             ast_rtp_set_m_type(newtextrtp, codec);
08416          }
08417       /* Search for image media definition */
08418       } else if (p->udptl && ((sscanf(m, "image %30u udptl t38%n", &x, &len) == 1 && len > 0) ||
08419                (sscanf(m, "image %30u UDPTL t38%n", &x, &len) == 1 && len > 0) )) {
08420          image = TRUE;
08421          if (debug)
08422             ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
08423          p->offered_media[SDP_IMAGE].offered = TRUE;
08424          udptlportno = x;
08425          numberofmediastreams++;
08426 
08427          if (p->t38.state != T38_ENABLED) {
08428             memset(&p->t38.their_parms, 0, sizeof(p->t38.their_parms));
08429 
08430             /* default EC to none, the remote end should
08431              * respond with the EC they want to use */
08432             ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
08433          }
08434       } else {
08435          ast_log(LOG_WARNING, "Unsupported SDP media type in offer: %s\n", m);
08436          continue;
08437       }
08438 
08439       /* Check for number of ports */
08440       if (numberofports > 1)
08441          ast_log(LOG_WARNING, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports);
08442       
08443 
08444 
08445       /* Media stream specific parameters */
08446       while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
08447          int processed = FALSE;
08448 
08449          switch (type) {
08450          case 'c':
08451             if (audio) {
08452                if (process_sdp_c(value, &audiohp)) {
08453                   processed = TRUE;
08454                   hp = &audiohp.hp;
08455                }
08456             } else if (video) {
08457                if (process_sdp_c(value, &videohp)) {
08458                   processed = TRUE;
08459                   vhp = &videohp.hp;
08460                }
08461             } else if (text) {
08462                if (process_sdp_c(value, &texthp)) {
08463                   processed = TRUE;
08464                   thp = &texthp.hp;
08465                }
08466             } else if (image) {
08467                if (process_sdp_c(value, &imagehp)) {
08468                   processed = TRUE;
08469                   ihp = &imagehp.hp;
08470                }
08471             }
08472             break;
08473          case 'a':
08474             /* Audio specific scanning */
08475             if (audio) {
08476                if (process_sdp_a_sendonly(value, &sendonly))
08477                   processed = TRUE;
08478                else if (process_sdp_a_audio(value, p, newaudiortp, &last_rtpmap_codec))
08479                   processed = TRUE;
08480             }
08481             /* Video specific scanning */
08482             else if (video) {
08483                if (process_sdp_a_sendonly(value, &vsendonly))
08484                   processed = TRUE;
08485                else if (process_sdp_a_video(value, p, newvideortp, &last_rtpmap_codec))
08486                   processed = TRUE;
08487             }
08488             /* Text (T.140) specific scanning */
08489             else if (text) {
08490                if (process_sdp_a_text(value, p, newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
08491                   processed = TRUE;
08492             }
08493             /* Image (T.38 FAX) specific scanning */
08494             else if (image) {
08495                if (process_sdp_a_image(value, p))
08496                   processed = TRUE;
08497             }
08498             break;
08499          }
08500 
08501          if (option_debug > 2)
08502             ast_log(LOG_DEBUG, "Processing media-level (%s) SDP %c=%s... %s\n",
08503                   (audio == TRUE)? "audio" : (video == TRUE)? "video" : "image",
08504                   type, value,
08505                   (processed == TRUE)? "OK." : "UNSUPPORTED.");
08506       }
08507    }
08508 
08509 
08510    /* Sanity checks */
08511    if (!hp && !vhp && !thp && !ihp) {
08512       ast_log(LOG_WARNING, "Insufficient information in SDP (c=)...\n");
08513       return -1;
08514    }
08515 
08516    if (portno == -1 && vportno == -1 && udptlportno == -1  && tportno == -1)
08517       /* No acceptable offer found in SDP  - we have no ports */
08518       /* Do not change RTP or VRTP if this is a re-invite */
08519       return -2;
08520 
08521    if (numberofmediastreams > 3)
08522       /* We have too many fax, audio and/or video and/or text media streams, fail this offer */
08523       return -3;
08524 
08525    if (udptlportno == -1) {
08526       change_t38_state(p, T38_DISABLED);
08527    }
08528 
08529 
08530    /* Now gather all of the codecs that we are asked for: */
08531    ast_rtp_get_current_formats(newaudiortp, &peercapability, &peernoncodeccapability);
08532    ast_rtp_get_current_formats(newvideortp, &vpeercapability, &vpeernoncodeccapability);
08533    ast_rtp_get_current_formats(newtextrtp, &tpeercapability, &tpeernoncodeccapability);
08534 
08535    newjointcapability = p->capability & (peercapability | vpeercapability | tpeercapability);
08536    newpeercapability = (peercapability | vpeercapability | tpeercapability);
08537    newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
08538 
08539    if (debug) {
08540       /* shame on whoever coded this.... */
08541       char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE], s5[SIPBUFSIZE];
08542 
08543       ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s/text=%s, combined - %s\n",
08544              ast_getformatname_multiple(s1, SIPBUFSIZE, p->capability),
08545              ast_getformatname_multiple(s2, SIPBUFSIZE, peercapability),
08546              ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
08547              ast_getformatname_multiple(s4, SIPBUFSIZE, tpeercapability),
08548              ast_getformatname_multiple(s5, SIPBUFSIZE, newjointcapability));
08549 
08550       ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
08551              ast_rtp_lookup_mime_multiple(s1, SIPBUFSIZE, p->noncodeccapability, 0, 0),
08552              ast_rtp_lookup_mime_multiple(s2, SIPBUFSIZE, peernoncodeccapability, 0, 0),
08553              ast_rtp_lookup_mime_multiple(s3, SIPBUFSIZE, newnoncodeccapability, 0, 0));
08554    }
08555    if (!newjointcapability && (portno != -1)) {
08556       ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
08557       /* Do NOT Change current setting */
08558       return -1;
08559    }
08560 
08561    /* Setup audio address and port */
08562    if (p->rtp) {
08563       if (portno > 0) {
08564          sin.sin_family = AF_INET;
08565          sin.sin_port = htons(portno);
08566          memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
08567          ast_rtp_set_peer(p->rtp, &sin);
08568          if (debug)
08569             ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
08570          /* We are now ready to change the sip session and p->rtp and p->vrtp with the offered codecs, since                                                                                                    
08571             they are acceptable */
08572          p->jointcapability = newjointcapability;                /* Our joint codec profile for this call */
08573          p->peercapability = newpeercapability;                  /* The other sides capability in latest offer */
08574          p->jointnoncodeccapability = newnoncodeccapability;     /* DTMF capabilities */
08575 
08576          ast_rtp_pt_copy(p->rtp, newaudiortp);
08577 
08578          if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
08579             ast_clear_flag(&p->flags[0], SIP_DTMF);
08580             if (newnoncodeccapability & AST_RTP_DTMF) {
08581                /* XXX Would it be reasonable to drop the DSP at this point? XXX */
08582                ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
08583                /* Since RFC2833 is now negotiated we need to change some properties of the RTP stream */
08584                ast_rtp_setdtmf(p->rtp, 1);
08585                ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
08586             } else {
08587                ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
08588             }
08589          }
08590       } else if (udptlportno > 0) {
08591          if (debug)
08592             ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session.\n");
08593       } else {
08594          ast_rtp_stop(p->rtp);
08595          if (debug)
08596             ast_verbose("Peer doesn't provide audio\n");
08597       }
08598    }
08599 
08600    /* Setup video address and port */
08601    if (p->vrtp) {
08602       if (vportno > 0) {
08603          vsin.sin_family = AF_INET;
08604          vsin.sin_port = htons(vportno);
08605          memcpy(&vsin.sin_addr, vhp->h_addr, sizeof(vsin.sin_addr));
08606          ast_rtp_set_peer(p->vrtp, &vsin);
08607          if (debug) 
08608             ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(vsin.sin_addr), ntohs(vsin.sin_port));
08609          ast_rtp_pt_copy(p->vrtp, newvideortp);
08610       } else {
08611          ast_rtp_stop(p->vrtp);
08612          if (debug)
08613             ast_verbose("Peer doesn't provide video\n");
08614       }
08615    }
08616 
08617    /* Setup text address and port */
08618    if (p->trtp) {
08619       if (tportno > 0) {
08620          tsin.sin_family = AF_INET;
08621          tsin.sin_port = htons(tportno);
08622          memcpy(&tsin.sin_addr, thp->h_addr, sizeof(tsin.sin_addr));
08623          ast_rtp_set_peer(p->trtp, &tsin);
08624          if (debug) 
08625             ast_verbose("Peer T.140 RTP is at port %s:%d\n", ast_inet_ntoa(tsin.sin_addr), ntohs(tsin.sin_port));
08626          if ((p->jointcapability & AST_FORMAT_T140RED)) {
08627             p->red = 1;
08628             rtp_red_init(p->trtp, 300, red_data_pt, 2);
08629          } else {
08630             p->red = 0;
08631          }
08632          ast_rtp_pt_copy(p->trtp, newtextrtp);
08633       } else {
08634          ast_rtp_stop(p->trtp);
08635          if (debug)
08636             ast_verbose("Peer doesn't provide T.140\n");
08637       }
08638    }
08639    /* Setup image address and port */
08640    if (p->udptl) {
08641       if (udptlportno > 0) {
08642          isin.sin_family = AF_INET;
08643          isin.sin_port = htons(udptlportno);
08644          if (ast_test_flag(&p->flags[0], SIP_NAT) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
08645             struct sockaddr_in remote_address = { 0, };
08646             ast_rtp_get_peer(p->rtp, &remote_address);
08647             if (remote_address.sin_addr.s_addr) {
08648                memcpy(&isin, &remote_address, sizeof(isin));
08649                if (debug) {
08650                   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));
08651                }
08652             }
08653          } else {
08654             memcpy(&isin.sin_addr, ihp->h_addr, sizeof(isin.sin_addr));
08655          }
08656          ast_udptl_set_peer(p->udptl, &isin);
08657          if (debug)
08658             ast_debug(1,"Peer T.38 UDPTL is at port %s:%d\n", ast_inet_ntoa(isin.sin_addr), ntohs(isin.sin_port));
08659 
08660          /* verify the far max ifp can be calculated. this requires far max datagram to be set. */
08661          if (!ast_udptl_get_far_max_datagram(p->udptl)) {
08662             /* setting to zero will force a default if none was provided by the SDP */
08663             ast_udptl_set_far_max_datagram(p->udptl, 0);
08664          }
08665 
08666          /* Remote party offers T38, we need to update state */
08667          if ((t38action == SDP_T38_ACCEPT) &&
08668              (p->t38.state == T38_LOCAL_REINVITE)) {
08669             change_t38_state(p, T38_ENABLED);
08670          } else if ((t38action == SDP_T38_INITIATE) &&
08671                p->owner && p->lastinvite) {
08672             change_t38_state(p, T38_PEER_REINVITE); /* T38 Offered in re-invite from remote party */
08673             /* If fax detection is enabled then send us off to the fax extension */
08674             if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38)) {
08675                ast_channel_lock(p->owner);
08676                if (strcmp(p->owner->exten, "fax")) {
08677                   const char *target_context = S_OR(p->owner->macrocontext, p->owner->context);
08678                   ast_channel_unlock(p->owner);
08679                   if (ast_exists_extension(p->owner, target_context, "fax", 1, p->owner->cid.cid_num)) {
08680                      ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to peer T.38 re-INVITE\n", p->owner->name);
08681                      pbx_builtin_setvar_helper(p->owner, "FAXEXTEN", p->owner->exten);
08682                      if (ast_async_goto(p->owner, target_context, "fax", 1)) {
08683                         ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", p->owner->name, target_context);
08684                      }
08685                   } else {
08686                      ast_log(LOG_NOTICE, "T.38 re-INVITE detected but no fax extension\n");
08687                   }
08688                } else {
08689                   ast_channel_unlock(p->owner);
08690                }
08691             }
08692          }
08693       } else {
08694          ast_udptl_stop(p->udptl);
08695          if (debug)
08696             ast_debug(1, "Peer doesn't provide T.38 UDPTL\n");
08697       }
08698    }
08699 
08700    if ((portno == -1) && (p->t38.state != T38_DISABLED)) {
08701       ast_debug(3, "Have T.38 but no audio, accepting offer anyway\n");
08702                 return 0;
08703         }
08704 
08705    /* Ok, we're going with this offer */
08706    ast_debug(2, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcapability));
08707 
08708    if (!p->owner)    /* There's no open channel owning us so we can return here. For a re-invite or so, we proceed */
08709       return 0;
08710 
08711    ast_debug(4, "We have an owner, now see if we need to change this call\n");
08712 
08713    if (!(p->owner->nativeformats & p->jointcapability) && (p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
08714       if (debug) {
08715          char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
08716          ast_debug(1, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n", 
08717             ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcapability),
08718             ast_getformatname_multiple(s2, SIPBUFSIZE, p->owner->nativeformats));
08719       }
08720       p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability) | (p->capability & tpeercapability);
08721       ast_set_read_format(p->owner, p->owner->readformat);
08722       ast_set_write_format(p->owner, p->owner->writeformat);
08723    }
08724    
08725    if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)
08726          && (sin.sin_addr.s_addr || vsin.sin_addr.s_addr ||
08727          isin.sin_addr.s_addr || tsin.sin_addr.s_addr)
08728          && (!sendonly || sendonly == -1)) {
08729       ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
08730       /* Activate a re-invite */
08731       ast_queue_frame(p->owner, &ast_null_frame);
08732       change_hold_state(p, req, FALSE, sendonly);
08733    } else if (!(sin.sin_addr.s_addr || vsin.sin_addr.s_addr ||
08734          isin.sin_addr.s_addr || tsin.sin_addr.s_addr)
08735          || (sendonly && sendonly != -1)) {
08736       ast_queue_control_data(p->owner, AST_CONTROL_HOLD, 
08737                    S_OR(p->mohsuggest, NULL),
08738                    !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
08739       if (sendonly)
08740          ast_rtp_stop(p->rtp);
08741       /* RTCP needs to go ahead, even if we're on hold!!! */
08742       /* Activate a re-invite */
08743       ast_queue_frame(p->owner, &ast_null_frame);
08744       change_hold_state(p, req, TRUE, sendonly);
08745    }
08746    
08747    return 0;
08748 }
08749 
08750 static int process_sdp_o(const char *o, struct sip_pvt *p)
08751 {
08752    char *o_copy;
08753    char *token;
08754    int64_t rua_version;
08755 
08756    /* Store the SDP version number of remote UA. This will allow us to
08757    distinguish between session modifications and session refreshes. If
08758    the remote UA does not send an incremented SDP version number in a
08759    subsequent RE-INVITE then that means its not changing media session.
08760    The RE-INVITE may have been sent to update connected party, remote
08761    target or to refresh the session (Session-Timers).  Asterisk must not
08762    change media session and increment its own version number in answer
08763    SDP in this case. */
08764 
08765    p->session_modify = TRUE;
08766 
08767    if (ast_strlen_zero(o)) {
08768       ast_log(LOG_WARNING, "SDP syntax error. SDP without an o= line\n");
08769       return FALSE;
08770    }
08771 
08772    o_copy = ast_strdupa(o);
08773    token = strsep(&o_copy, " ");  /* Skip username   */
08774    if (!o_copy) {
08775       ast_log(LOG_WARNING, "SDP syntax error in o= line username\n");
08776       return FALSE;
08777    }
08778    token = strsep(&o_copy, " ");  /* Skip session-id */
08779    if (!o_copy) {
08780       ast_log(LOG_WARNING, "SDP syntax error in o= line session-id\n");
08781       return FALSE;
08782    }
08783    token = strsep(&o_copy, " ");  /* Version         */
08784    if (!o_copy) {
08785       ast_log(LOG_WARNING, "SDP syntax error in o= line\n");
08786       return FALSE;
08787    }
08788    if (!sscanf(token, "%30" SCNd64, &rua_version)) {
08789       ast_log(LOG_WARNING, "SDP syntax error in o= line version\n");
08790       return FALSE;
08791    }
08792 
08793    /* we need to check the SDP version number the other end sent us;
08794     * our rules for deciding what to accept are a bit complex.
08795     *
08796     * 1) if 'ignoresdpversion' has been set for this dialog, then
08797     *    we will just accept whatever they sent and assume it is
08798     *    a modification of the session, even if it is not
08799     * 2) otherwise, if this is the first SDP we've seen from them
08800     *    we accept it
08801     * 3) otherwise, if the new SDP version number is higher than the
08802     *    old one, we accept it
08803     * 4) otherwise, if this SDP is in response to us requesting a switch
08804     *    to T.38, we accept the SDP, but also generate a warning message
08805     *    that this peer should have the 'ignoresdpversion' option set,
08806     *    because it is not following the SDP offer/answer RFC; if we did
08807     *    not request a switch to T.38, then we stop parsing the SDP, as it
08808     *    has not changed from the previous version
08809     */
08810 
08811    if (ast_test_flag(&p->flags[1], SIP_PAGE2_IGNORESDPVERSION) ||
08812        (p->sessionversion_remote < 0) ||
08813        (p->sessionversion_remote < rua_version)) {
08814       p->sessionversion_remote = rua_version;
08815    } else {
08816       if (p->t38.state == T38_LOCAL_REINVITE) {
08817          p->sessionversion_remote = rua_version;
08818          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);
08819       } else {
08820          p->session_modify = FALSE;
08821          ast_debug(2, "Call %s responded to our reinvite without changing SDP version; ignoring SDP.\n", p->callid);
08822          return FALSE;
08823       }
08824    }
08825 
08826    return TRUE;
08827 }
08828 
08829 static int process_sdp_c(const char *c, struct ast_hostent *ast_hp)
08830 {
08831    char host[258];
08832    struct hostent *hp;
08833 
08834    /* Check for Media-description-level-address */
08835    if (sscanf(c, "IN IP4 %255s", host) != 1) {
08836       ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
08837       return FALSE;
08838    } else {
08839       if (!(hp = ast_gethostbyname(host, ast_hp))) {
08840          ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in c= line, '%s'\n", c);
08841          return FALSE;
08842       }
08843       return TRUE;
08844    }
08845    return FALSE;
08846 }
08847 
08848 static int process_sdp_a_sendonly(const char *a, int *sendonly)
08849 {
08850    int found = FALSE;
08851 
08852    if (!strcasecmp(a, "sendonly")) {
08853       if (*sendonly == -1)
08854          *sendonly = 1;
08855       found = TRUE;
08856    } else if (!strcasecmp(a, "inactive")) {
08857       if (*sendonly == -1)
08858          *sendonly = 2;
08859       found = TRUE;
08860    }  else if (!strcasecmp(a, "sendrecv")) {
08861       if (*sendonly == -1)
08862          *sendonly = 0;
08863       found = TRUE;
08864    }
08865    return found;
08866 }
08867 
08868 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp *newaudiortp, int *last_rtpmap_codec)
08869 {
08870    int found = FALSE;
08871    int codec;
08872    char mimeSubtype[128];
08873    char fmtp_string[64];
08874    unsigned int sample_rate;
08875    int debug = sip_debug_test_pvt(p);
08876 
08877    if (!strncasecmp(a, "ptime", 5)) {
08878       char *tmp = strrchr(a, ':');
08879       long int framing = 0;
08880       if (tmp) {
08881          tmp++;
08882          framing = strtol(tmp, NULL, 10);
08883          if (framing == LONG_MIN || framing == LONG_MAX) {
08884             framing = 0;
08885             ast_debug(1, "Can't read framing from SDP: %s\n", a);
08886          }
08887       }
08888       if (framing && p->autoframing) {
08889          struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
08890          int codec_n;
08891          int format = 0;
08892          for (codec_n = 0; codec_n < MAX_RTP_PT; codec_n++) {
08893             format = ast_rtp_codec_getformat(codec_n);
08894             if (!format)   /* non-codec or not found */
08895                continue;
08896             if (option_debug)
08897                ast_log(LOG_DEBUG, "Setting framing for %d to %ld\n", format, framing);
08898             ast_codec_pref_setsize(pref, format, framing);
08899          }
08900          ast_rtp_codec_setpref(p->rtp, pref);
08901       }
08902       found = TRUE;
08903    } else if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
08904       /* We have a rtpmap to handle */
08905       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
08906          if (ast_rtp_set_rtpmap_type_rate(newaudiortp, codec, "audio", mimeSubtype,
08907              ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0, sample_rate) != -1) {
08908             if (debug)
08909                ast_verbose("Found audio description format %s for ID %d\n", mimeSubtype, codec);
08910             //found_rtpmap_codecs[last_rtpmap_codec] = codec;
08911             (*last_rtpmap_codec)++;
08912             found = TRUE;
08913          } else {
08914             ast_rtp_unset_m_type(newaudiortp, codec);
08915             if (debug)
08916                ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
08917          }
08918       } else {
08919          if (debug)
08920             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
08921       }
08922    } else if (sscanf(a, "fmtp: %30u %63s", &codec, fmtp_string) == 2) {
08923       struct rtpPayloadType payload;
08924 
08925       payload = ast_rtp_lookup_pt(newaudiortp, codec);
08926       if (payload.code && payload.isAstFormat) {
08927          unsigned int bit_rate;
08928 
08929          switch (payload.code) {
08930          case AST_FORMAT_SIREN7:
08931             if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
08932                if (bit_rate != 32000) {
08933                   ast_log(LOG_WARNING, "Got Siren7 offer at %d bps, but only 32000 bps supported; ignoring.\n", bit_rate);
08934                   ast_rtp_unset_m_type(newaudiortp, codec);
08935                } else {
08936                   found = TRUE;
08937                }
08938             }
08939             break;
08940          case AST_FORMAT_SIREN14:
08941             if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
08942                if (bit_rate != 48000) {
08943                   ast_log(LOG_WARNING, "Got Siren14 offer at %d bps, but only 48000 bps supported; ignoring.\n", bit_rate);
08944                   ast_rtp_unset_m_type(newaudiortp, codec);
08945                } else {
08946                   found = TRUE;
08947                }
08948             }
08949             break;
08950          }
08951       }
08952    }
08953 
08954    return found;
08955 }
08956 
08957 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp *newvideortp, int *last_rtpmap_codec)
08958 {
08959    int found = FALSE;
08960    int codec;
08961    char mimeSubtype[128];
08962    unsigned int sample_rate;
08963    int debug = sip_debug_test_pvt(p);
08964 
08965    if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
08966       /* We have a rtpmap to handle */
08967       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
08968          /* Note: should really look at the '#chans' params too */
08969          if (!strncasecmp(mimeSubtype, "H26", 3) || !strncasecmp(mimeSubtype, "MP4", 3)) {
08970             if (ast_rtp_set_rtpmap_type_rate(newvideortp, codec, "video", mimeSubtype, 0, sample_rate) != -1) {
08971                if (debug)
08972                   ast_verbose("Found video description format %s for ID %d\n", mimeSubtype, codec);
08973                //found_rtpmap_codecs[last_rtpmap_codec] = codec;
08974                (*last_rtpmap_codec)++;
08975                found = TRUE;
08976             } else {
08977                ast_rtp_unset_m_type(newvideortp, codec);
08978                if (debug) 
08979                   ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
08980             }
08981          }
08982       } else {
08983          if (debug)
08984             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
08985       }
08986    }
08987 
08988    return found;
08989 }
08990 
08991 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)
08992 {
08993    int found = FALSE;
08994    int codec;
08995    char mimeSubtype[128];
08996    unsigned int sample_rate;
08997    char *red_cp;
08998    int debug = sip_debug_test_pvt(p);
08999 
09000    if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
09001       /* We have a rtpmap to handle */
09002       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
09003          if (!strncasecmp(mimeSubtype, "T140", 4)) { /* Text */
09004             if (p->trtp) {
09005                /* ast_verbose("Adding t140 mimeSubtype to textrtp struct\n"); */
09006                ast_rtp_set_rtpmap_type(newtextrtp, codec, "text", mimeSubtype, 0);
09007                found = TRUE;
09008             }
09009          } else if (!strncasecmp(mimeSubtype, "RED", 3)) { /* Text with Redudancy */
09010             if (p->trtp) {
09011                ast_rtp_set_rtpmap_type(newtextrtp, codec, "text", mimeSubtype, 0);
09012                sprintf(red_fmtp, "fmtp:%d ", codec); 
09013                if (debug)
09014                   ast_verbose("RED submimetype has payload type: %d\n", codec);
09015                found = TRUE;
09016             }
09017          }
09018       } else {
09019          if (debug)
09020             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
09021       }
09022    } else if (!strncmp(a, red_fmtp, strlen(red_fmtp))) {
09023       /* count numbers of generations in fmtp */
09024       red_cp = &red_fmtp[strlen(red_fmtp)];
09025       strncpy(red_fmtp, a, 100);
09026 
09027       sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
09028       red_cp = strtok(red_cp, "/");
09029       while (red_cp && (*red_num_gen)++ < RED_MAX_GENERATION) {
09030          sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
09031          red_cp = strtok(NULL, "/");
09032       }
09033       red_cp = red_fmtp;
09034       found = TRUE;
09035    }
09036 
09037    return found;
09038 }
09039 
09040 static int process_sdp_a_image(const char *a, struct sip_pvt *p)
09041 {
09042    int found = FALSE;
09043    char s[256];
09044    unsigned int x;
09045 
09046    if ((sscanf(a, "T38FaxMaxBuffer:%30u", &x) == 1)) {
09047       ast_debug(3, "MaxBufferSize:%d\n", x);
09048       found = TRUE;
09049    } else if ((sscanf(a, "T38MaxBitRate:%30u", &x) == 1) || (sscanf(a, "T38FaxMaxRate:%30u", &x) == 1)) {
09050       ast_debug(3, "T38MaxBitRate: %d\n", x);
09051       switch (x) {
09052       case 14400:
09053          p->t38.their_parms.rate = AST_T38_RATE_14400;
09054          break;
09055       case 12000:
09056          p->t38.their_parms.rate = AST_T38_RATE_12000;
09057          break;
09058       case 9600:
09059          p->t38.their_parms.rate = AST_T38_RATE_9600;
09060          break;
09061       case 7200:
09062          p->t38.their_parms.rate = AST_T38_RATE_7200;
09063          break;
09064       case 4800:
09065          p->t38.their_parms.rate = AST_T38_RATE_4800;
09066          break;
09067       case 2400:
09068          p->t38.their_parms.rate = AST_T38_RATE_2400;
09069          break;
09070       }
09071       found = TRUE;
09072    } else if ((sscanf(a, "T38FaxVersion:%30u", &x) == 1)) {
09073       ast_debug(3, "FaxVersion: %u\n", x);
09074       p->t38.their_parms.version = x;
09075       found = TRUE;
09076    } else if ((sscanf(a, "T38FaxMaxDatagram:%30u", &x) == 1) || (sscanf(a, "T38MaxDatagram:%30u", &x) == 1)) {
09077       /* override the supplied value if the configuration requests it */
09078       if (((signed int) p->t38_maxdatagram >= 0) && ((unsigned int) p->t38_maxdatagram > x)) {
09079          ast_debug(1, "Overriding T38FaxMaxDatagram '%d' with '%d'\n", x, p->t38_maxdatagram);
09080          x = p->t38_maxdatagram;
09081       }
09082       ast_debug(3, "FaxMaxDatagram: %u\n", x);
09083       ast_udptl_set_far_max_datagram(p->udptl, x);
09084       found = TRUE;
09085    } else if ((strncmp(a, "T38FaxFillBitRemoval", 20) == 0)) {
09086       if (sscanf(a, "T38FaxFillBitRemoval:%30u", &x) == 1) {
09087          ast_debug(3, "FillBitRemoval: %d\n", x);
09088          if (x == 1) {
09089             p->t38.their_parms.fill_bit_removal = TRUE;
09090          }
09091       } else {
09092          ast_debug(3, "FillBitRemoval\n");
09093          p->t38.their_parms.fill_bit_removal = TRUE;
09094       }
09095       found = TRUE;
09096    } else if ((strncmp(a, "T38FaxTranscodingMMR", 20) == 0)) {
09097       if (sscanf(a, "T38FaxTranscodingMMR:%30u", &x) == 1) {
09098          ast_debug(3, "Transcoding MMR: %d\n", x);
09099          if (x == 1) {
09100             p->t38.their_parms.transcoding_mmr = TRUE;
09101          }
09102       } else {
09103          ast_debug(3, "Transcoding MMR\n");
09104          p->t38.their_parms.transcoding_mmr = TRUE;
09105       }
09106       found = TRUE;
09107    } else if ((strncmp(a, "T38FaxTranscodingJBIG", 21) == 0)) {
09108       if (sscanf(a, "T38FaxTranscodingJBIG:%30u", &x) == 1) {
09109          ast_debug(3, "Transcoding JBIG: %d\n", x);
09110          if (x == 1) {
09111             p->t38.their_parms.transcoding_jbig = TRUE;
09112          }
09113       } else {
09114          ast_debug(3, "Transcoding JBIG\n");
09115          p->t38.their_parms.transcoding_jbig = TRUE;
09116       }
09117       found = TRUE;
09118    } else if ((sscanf(a, "T38FaxRateManagement:%255s", s) == 1)) {
09119       ast_debug(3, "RateManagement: %s\n", s);
09120       if (!strcasecmp(s, "localTCF"))
09121          p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_LOCAL_TCF;
09122       else if (!strcasecmp(s, "transferredTCF"))
09123          p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF;
09124       found = TRUE;
09125    } else if ((sscanf(a, "T38FaxUdpEC:%255s", s) == 1)) {
09126       ast_debug(3, "UDP EC: %s\n", s);
09127       if (!strcasecmp(s, "t38UDPRedundancy")) {
09128          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
09129       } else if (!strcasecmp(s, "t38UDPFEC")) {
09130          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
09131       } else {
09132          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
09133       }
09134       found = TRUE;
09135    }
09136 
09137    return found;
09138 }
09139 
09140 
09141 #ifdef LOW_MEMORY
09142 static void ts_ast_rtp_destroy(void *data)
09143 {
09144     struct ast_rtp *tmp = data;
09145     ast_rtp_destroy(tmp);
09146 }
09147 #endif
09148 
09149 /*! \brief Add "Supported" header to sip message.  Since some options may
09150  *  be disabled in the config, the sip_pvt must be inspected to determine what
09151  *  is supported for this dialog. */
09152 static int add_supported_header(struct sip_pvt *pvt, struct sip_request *req)
09153 {
09154    int res;
09155    if (st_get_mode(pvt) != SESSION_TIMER_MODE_REFUSE) {
09156       res = add_header(req, "Supported", "replaces, timer");
09157    } else {
09158       res = add_header(req, "Supported", "replaces");
09159    }
09160    return res;
09161 }
09162 
09163 /*! \brief Add header to SIP message */
09164 static int add_header(struct sip_request *req, const char *var, const char *value)
09165 {
09166    if (req->headers == SIP_MAX_HEADERS) {
09167       ast_log(LOG_WARNING, "Out of SIP header space\n");
09168       return -1;
09169    }
09170 
09171    if (req->lines) {
09172       ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
09173       return -1;
09174    }
09175 
09176    if (sip_cfg.compactheaders) {
09177       var = find_alias(var, var);
09178    }
09179 
09180    ast_str_append(&req->data, 0, "%s: %s\r\n", var, value);
09181    req->header[req->headers] = req->len;
09182 
09183    req->len = ast_str_strlen(req->data);
09184    req->headers++;
09185 
09186    return 0;   
09187 }
09188 
09189 /*! \brief Add 'Content-Length' header and content to SIP message */
09190 static int finalize_content(struct sip_request *req)
09191 {
09192    char clen[10];
09193 
09194    if (req->lines) {
09195       ast_log(LOG_WARNING, "finalize_content() called on a message that has already been finalized\n");
09196       return -1;
09197    }
09198 
09199    snprintf(clen, sizeof(clen), "%zd", ast_str_strlen(req->content));
09200    add_header(req, "Content-Length", clen);
09201 
09202    if (ast_str_strlen(req->content)) {
09203       ast_str_append(&req->data, 0, "\r\n%s", ast_str_buffer(req->content));
09204       req->len = ast_str_strlen(req->data);
09205    }
09206    req->lines = ast_str_strlen(req->content) ? 1 : 0;
09207    return 0;
09208 }
09209 
09210 /*! \brief Add content (not header) to SIP message */
09211 static int add_content(struct sip_request *req, const char *line)
09212 {
09213    if (req->lines) {
09214       ast_log(LOG_WARNING, "Can't add more content when the content has been finalized\n");
09215       return -1;
09216    }
09217 
09218    ast_str_append(&req->content, 0, "%s", line);
09219    return 0;
09220 }
09221 
09222 /*! \brief Copy one header field from one request to another */
09223 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
09224 {
09225    const char *tmp = get_header(orig, field);
09226 
09227    if (!ast_strlen_zero(tmp)) /* Add what we're responding to */
09228       return add_header(req, field, tmp);
09229    ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
09230    return -1;
09231 }
09232 
09233 /*! \brief Copy all headers from one request to another */
09234 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
09235 {
09236    int start = 0;
09237    int copied = 0;
09238    for (;;) {
09239       const char *tmp = __get_header(orig, field, &start);
09240 
09241       if (ast_strlen_zero(tmp))
09242          break;
09243       /* Add what we're responding to */
09244       add_header(req, field, tmp);
09245       copied++;
09246    }
09247    return copied ? 0 : -1;
09248 }
09249 
09250 /*! \brief Copy SIP VIA Headers from the request to the response
09251 \note If the client indicates that it wishes to know the port we received from,
09252    it adds ;rport without an argument to the topmost via header. We need to
09253    add the port number (from our point of view) to that parameter.
09254 \verbatim
09255    We always add ;received=<ip address> to the topmost via header.
09256 \endverbatim
09257    Received: RFC 3261, rport RFC 3581 */
09258 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
09259 {
09260    int copied = 0;
09261    int start = 0;
09262 
09263    for (;;) {
09264       char new[512];
09265       const char *oh = __get_header(orig, field, &start);
09266 
09267       if (ast_strlen_zero(oh))
09268          break;
09269 
09270       if (!copied) { /* Only check for empty rport in topmost via header */
09271          char leftmost[512], *others, *rport;
09272 
09273          /* Only work on leftmost value */
09274          ast_copy_string(leftmost, oh, sizeof(leftmost));
09275          others = strchr(leftmost, ',');
09276          if (others)
09277              *others++ = '\0';
09278 
09279          /* Find ;rport;  (empty request) */
09280          rport = strstr(leftmost, ";rport");
09281          if (rport && *(rport+6) == '=') 
09282             rport = NULL;     /* We already have a parameter to rport */
09283 
09284          /* Check rport if NAT=yes or NAT=rfc3581 (which is the default setting)  */
09285          if (rport && ((ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_ALWAYS) || (ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_RFC3581))) {
09286             /* We need to add received port - rport */
09287             char *end;
09288 
09289             rport = strstr(leftmost, ";rport");
09290 
09291             if (rport) {
09292                end = strchr(rport + 1, ';');
09293                if (end)
09294                   memmove(rport, end, strlen(end) + 1);
09295                else
09296                   *rport = '\0';
09297             }
09298 
09299             /* Add rport to first VIA header if requested */
09300             snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
09301                leftmost, ast_inet_ntoa(p->recv.sin_addr),
09302                ntohs(p->recv.sin_port),
09303                others ? "," : "", others ? others : "");
09304          } else {
09305             /* We should *always* add a received to the topmost via */
09306             snprintf(new, sizeof(new), "%s;received=%s%s%s",
09307                leftmost, ast_inet_ntoa(p->recv.sin_addr),
09308                others ? "," : "", others ? others : "");
09309          }
09310          oh = new;   /* the header to copy */
09311       }  /* else add the following via headers untouched */
09312       add_header(req, field, oh);
09313       copied++;
09314    }
09315    if (!copied) {
09316       ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
09317       return -1;
09318    }
09319    return 0;
09320 }
09321 
09322 /*! \brief Add route header into request per learned route */
09323 static void add_route(struct sip_request *req, struct sip_route *route)
09324 {
09325    char r[SIPBUFSIZE*2], *p;
09326    int n, rem = sizeof(r);
09327 
09328    if (!route)
09329       return;
09330 
09331    p = r;
09332    for (;route ; route = route->next) {
09333       n = strlen(route->hop);
09334       if (rem < n+3) /* we need room for ",<route>" */
09335          break;
09336       if (p != r) {  /* add a separator after fist route */
09337          *p++ = ',';
09338          --rem;
09339       }
09340       *p++ = '<';
09341       ast_copy_string(p, route->hop, rem); /* cannot fail */
09342       p += n;
09343       *p++ = '>';
09344       rem -= (n+2);
09345    }
09346    *p = '\0';
09347    add_header(req, "Route", r);
09348 }
09349 
09350 /*! \brief Set destination from SIP URI 
09351  *
09352  * Parse uri to h (host) and port - uri is already just the part inside the <> 
09353  * general form we are expecting is sip[s]:username[:password][;parameter]@host[:port][;...] 
09354  * If there's a port given, turn NAPTR/SRV off. NAPTR might indicate SIPS preference even
09355  * for SIP: uri's
09356  *
09357  * If there's a sips: uri scheme, TLS will be required. 
09358  */
09359 static void set_destination(struct sip_pvt *p, char *uri)
09360 {
09361    char *h, *maddr, hostname[256];
09362    int port, hn;
09363    struct hostent *hp;
09364    struct ast_hostent ahp;
09365    int debug=sip_debug_test_pvt(p);
09366    int tls_on = FALSE;
09367    int use_dns = sip_cfg.srvlookup;
09368 
09369    if (debug)
09370       ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
09371 
09372    /* Find and parse hostname */
09373    h = strchr(uri, '@');
09374    if (h)
09375       ++h;
09376    else {
09377       h = uri;
09378       if (!strncasecmp(h, "sip:", 4)) {
09379          h += 4;
09380       } else if (!strncasecmp(h, "sips:", 5)) {
09381          h += 5;
09382          tls_on = TRUE;
09383       }
09384    }
09385    hn = strcspn(h, ":;>") + 1;
09386    if (hn > sizeof(hostname)) 
09387       hn = sizeof(hostname);
09388    ast_copy_string(hostname, h, hn);
09389    /* XXX bug here if string has been trimmed to sizeof(hostname) */
09390    h += hn - 1;
09391 
09392    /* Is "port" present? if not default to STANDARD_SIP_PORT */
09393    if (*h == ':') {
09394       /* Parse port */
09395       ++h;
09396       port = strtol(h, &h, 10);
09397       use_dns = FALSE;
09398    } else
09399       port = tls_on ? STANDARD_TLS_PORT : STANDARD_SIP_PORT;
09400 
09401    /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
09402    maddr = strstr(h, "maddr=");
09403    if (maddr) {
09404       maddr += 6;
09405       hn = strspn(maddr, "0123456789.") + 1;
09406       if (hn > sizeof(hostname))
09407          hn = sizeof(hostname);
09408       ast_copy_string(hostname, maddr, hn);
09409    }
09410 
09411    /*! \todo XXX If we have use_dns on, then look for NAPTR/SRV, otherwise, just look for A records */
09412    
09413    hp = ast_gethostbyname(hostname, &ahp);
09414    if (hp == NULL)  {
09415       ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
09416       return;
09417    }
09418    p->sa.sin_family = AF_INET;
09419    memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
09420    p->sa.sin_port = htons(port);
09421    if (debug)
09422       ast_verbose("set_destination: set destination to %s, port %d\n", ast_inet_ntoa(p->sa.sin_addr), port);
09423 }
09424 
09425 /*! \brief Initialize SIP response, based on SIP request */
09426 static int init_resp(struct sip_request *resp, const char *msg)
09427 {
09428    /* Initialize a response */
09429    memset(resp, 0, sizeof(*resp));
09430    resp->method = SIP_RESPONSE;
09431    if (!(resp->data = ast_str_create(SIP_MIN_PACKET)))
09432       goto e_return;
09433    if (!(resp->content = ast_str_create(SIP_MIN_PACKET)))
09434       goto e_free_data;
09435    resp->header[0] = 0;
09436    ast_str_set(&resp->data, 0, "SIP/2.0 %s\r\n", msg);
09437    resp->len = resp->data->used;
09438    resp->headers++;
09439    return 0;
09440 
09441 e_free_data:
09442    ast_free(resp->data);
09443    resp->data = NULL;
09444 e_return:
09445    return -1;
09446 }
09447 
09448 /*! \brief Initialize SIP request */
09449 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
09450 {
09451    /* Initialize a request */
09452    memset(req, 0, sizeof(*req));
09453    if (!(req->data = ast_str_create(SIP_MIN_PACKET)))
09454       goto e_return;
09455    if (!(req->content = ast_str_create(SIP_MIN_PACKET)))
09456       goto e_free_data;
09457    req->method = sipmethod;
09458    req->header[0] = 0;
09459    ast_str_set(&req->data, 0, "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
09460    req->len = ast_str_strlen(req->data);
09461    req->headers++;
09462    return 0;
09463 
09464 e_free_data:
09465    ast_free(req->data);
09466    req->data = NULL;
09467 e_return:
09468    return -1;
09469 }
09470 
09471 /*! \brief Deinitialize SIP response/request */
09472 static void deinit_req(struct sip_request *req)
09473 {
09474    if (req->data) {
09475       ast_free(req->data);
09476       req->data = NULL;
09477    }
09478    if (req->content) {
09479       ast_free(req->content);
09480       req->content = NULL;
09481    }
09482 }
09483 
09484 
09485 /*! \brief Test if this response needs a contact header */
09486 static inline int resp_needs_contact(const char *msg, enum sipmethod method) {
09487    /* Requirements for Contact header inclusion in responses generated
09488     * from the header tables found in the following RFCs.  Where the
09489     * Contact header was marked mandatory (m) or optional (o) this
09490     * function returns 1.
09491     *
09492     * - RFC 3261 (ACK, BYE, CANCEL, INVITE, OPTIONS, REGISTER)
09493     * - RFC 2976 (INFO)
09494     * - RFC 3262 (PRACK)
09495     * - RFC 3265 (SUBSCRIBE, NOTIFY)
09496     * - RFC 3311 (UPDATE)
09497     * - RFC 3428 (MESSAGE)
09498     * - RFC 3515 (REFER)
09499     * - RFC 3903 (PUBLISH)
09500     */
09501 
09502    switch (method) {
09503       /* 1xx, 2xx, 3xx, 485 */
09504       case SIP_INVITE:
09505       case SIP_UPDATE:
09506       case SIP_SUBSCRIBE:
09507       case SIP_NOTIFY:
09508          if ((msg[0] >= '1' && msg[0] <= '3') || !strncmp(msg, "485", 3))
09509             return 1;
09510          break;
09511 
09512       /* 2xx, 3xx, 485 */
09513       case SIP_REGISTER:
09514       case SIP_OPTIONS:
09515          if (msg[0] == '2' || msg[0] == '3' || !strncmp(msg, "485", 3))
09516             return 1;
09517          break;
09518 
09519       /* 3xx, 485 */
09520       case SIP_BYE:
09521       case SIP_PRACK:
09522       case SIP_MESSAGE:
09523       case SIP_PUBLISH:
09524          if (msg[0] == '3' || !strncmp(msg, "485", 3))
09525             return 1;
09526          break;
09527 
09528       /* 2xx, 3xx, 4xx, 5xx, 6xx */
09529       case SIP_REFER:
09530          if (msg[0] >= '2' && msg[0] <= '6')
09531             return 1;
09532          break;
09533 
09534       /* contact will not be included for everything else */
09535       case SIP_ACK:
09536       case SIP_CANCEL:
09537       case SIP_INFO:
09538       case SIP_PING:
09539       default:
09540          return 0;
09541    }
09542    return 0;
09543 }
09544 
09545 /*! \brief Prepare SIP response packet */
09546 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
09547 {
09548    char newto[256];
09549    const char *ot;
09550 
09551    init_resp(resp, msg);
09552    copy_via_headers(p, resp, req, "Via");
09553    if (msg[0] == '1' || msg[0] == '2')
09554       copy_all_header(resp, req, "Record-Route");
09555    copy_header(resp, req, "From");
09556    ot = get_header(req, "To");
09557    if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
09558       /* Add the proper tag if we don't have it already.  If they have specified
09559          their tag, use it.  Otherwise, use our own tag */
09560       if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
09561          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
09562       else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
09563          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
09564       else
09565          ast_copy_string(newto, ot, sizeof(newto));
09566       ot = newto;
09567    }
09568    add_header(resp, "To", ot);
09569    copy_header(resp, req, "Call-ID");
09570    copy_header(resp, req, "CSeq");
09571    if (!ast_strlen_zero(global_useragent))
09572       add_header(resp, "Server", global_useragent);
09573    add_header(resp, "Allow", ALLOWED_METHODS);
09574    add_supported_header(p, resp);
09575 
09576    /* If this is an invite, add Session-Timers related headers if the feature is active for this session */
09577    if (p->method == SIP_INVITE && p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE) {
09578       char se_hdr[256];
09579       snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval, 
09580          strefresher2str(p->stimer->st_ref));
09581       add_header(resp, "Session-Expires", se_hdr);
09582    }
09583 
09584    if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
09585       /* For registration responses, we also need expiry and
09586          contact info */
09587       char tmp[256];
09588 
09589       snprintf(tmp, sizeof(tmp), "%d", p->expiry);
09590       add_header(resp, "Expires", tmp);
09591       if (p->expiry) {  /* Only add contact if we have an expiry time */
09592          char contact[SIPBUFSIZE];
09593          const char *contact_uri = p->method == SIP_SUBSCRIBE ? p->our_contact : p->fullcontact;
09594          char *brackets = strchr(contact_uri, '<');
09595          snprintf(contact, sizeof(contact), "%s%s%s;expires=%d", brackets ? "" : "<", contact_uri, brackets ? "" : ">", p->expiry);
09596          add_header(resp, "Contact", contact);  /* Not when we unregister */
09597       }
09598    } else if (!ast_strlen_zero(p->our_contact) && resp_needs_contact(msg, p->method)) {
09599       add_header(resp, "Contact", p->our_contact);
09600    }
09601 
09602    if (!ast_strlen_zero(p->url)) {
09603       add_header(resp, "Access-URL", p->url);
09604       ast_string_field_set(p, url, NULL);
09605    }
09606 
09607    return 0;
09608 }
09609 
09610 /*! \brief Initialize a SIP request message (not the initial one in a dialog) */
09611 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch)
09612 {
09613    struct sip_request *orig = &p->initreq;
09614    char stripped[80];
09615    char tmp[80];
09616    char newto[256];
09617    const char *c;
09618    const char *ot, *of;
09619    int is_strict = FALSE;     /*!< Strict routing flag */
09620    int is_outbound = ast_test_flag(&p->flags[0], SIP_OUTGOING);   /* Session direction */
09621 
09622    memset(req, 0, sizeof(struct sip_request));
09623    
09624    snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
09625    
09626    if (!seqno) {
09627       p->ocseq++;
09628       seqno = p->ocseq;
09629    }
09630    
09631    /* A CANCEL must have the same branch as the INVITE that it is canceling. */
09632    if (sipmethod == SIP_CANCEL) {
09633       p->branch = p->invite_branch;
09634       build_via(p);
09635    } else if (newbranch && (sipmethod == SIP_INVITE)) {
09636       p->branch ^= ast_random();
09637       p->invite_branch = p->branch;
09638       build_via(p);
09639    } else if (newbranch) {
09640       p->branch ^= ast_random();
09641       build_via(p);
09642    }
09643 
09644    /* Check for strict or loose router */
09645    if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop, ";lr") == NULL) {
09646       is_strict = TRUE;
09647       if (sipdebug)
09648          ast_debug(1, "Strict routing enforced for session %s\n", p->callid);
09649    }
09650    
09651    if (sipmethod == SIP_CANCEL)
09652       c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2); /* Use original URI */
09653    else if (sipmethod == SIP_ACK) {
09654       /* Use URI from Contact: in 200 OK (if INVITE) 
09655       (we only have the contacturi on INVITEs) */
09656       if (!ast_strlen_zero(p->okcontacturi))
09657          c = is_strict ? p->route->hop : p->okcontacturi;
09658       else
09659          c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
09660    } else if (!ast_strlen_zero(p->okcontacturi)) 
09661       c = is_strict ? p->route->hop : p->okcontacturi; /* Use for BYE or REINVITE */
09662    else if (!ast_strlen_zero(p->uri)) 
09663       c = p->uri;
09664    else {
09665       char *n;
09666       /* We have no URI, use To: or From:  header as URI (depending on direction) */
09667       ast_copy_string(stripped, get_header(orig, is_outbound ? "To" : "From"),
09668             sizeof(stripped));
09669       n = get_in_brackets(stripped);
09670       c = remove_uri_parameters(n);
09671    }  
09672    init_req(req, sipmethod, c);
09673 
09674    snprintf(tmp, sizeof(tmp), "%d %s", seqno, sip_methods[sipmethod].text);
09675 
09676    add_header(req, "Via", p->via);
09677    if (p->route) {
09678       set_destination(p, p->route->hop);
09679       add_route(req, is_strict ? p->route->next : p->route);
09680    }
09681    add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
09682 
09683    ot = get_header(orig, "To");
09684    of = get_header(orig, "From");
09685 
09686    /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
09687       as our original request, including tag (or presumably lack thereof) */
09688    if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
09689       /* Add the proper tag if we don't have it already.  If they have specified
09690          their tag, use it.  Otherwise, use our own tag */
09691       if (is_outbound && !ast_strlen_zero(p->theirtag))
09692          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
09693       else if (!is_outbound)
09694          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
09695       else
09696          snprintf(newto, sizeof(newto), "%s", ot);
09697       ot = newto;
09698    }
09699 
09700    if (is_outbound) {
09701       add_header(req, "From", of);
09702       add_header(req, "To", ot);
09703    } else {
09704       add_header(req, "From", ot);
09705       add_header(req, "To", of);
09706    }
09707    /* Do not add Contact for MESSAGE, BYE and Cancel requests */
09708    if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
09709       add_header(req, "Contact", p->our_contact);
09710 
09711    copy_header(req, orig, "Call-ID");
09712    add_header(req, "CSeq", tmp);
09713 
09714    if (!ast_strlen_zero(global_useragent))
09715       add_header(req, "User-Agent", global_useragent);
09716 
09717    if (!ast_strlen_zero(p->rpid))
09718       add_header(req, "Remote-Party-ID", p->rpid);
09719 
09720    if (!ast_strlen_zero(p->url)) {
09721       add_header(req, "Access-URL", p->url);
09722       ast_string_field_set(p, url, NULL);
09723    }
09724 
09725    /* Add Session-Timers related headers if the feature is active for this session.
09726       An exception to this behavior is the ACK request. Since Asterisk never requires 
09727       session-timers support from a remote end-point (UAS) in an INVITE, it must 
09728       not send 'Require: timer' header in the ACK request. 
09729       This should only be added in the INVITE transactions, not MESSAGE or REFER or other
09730       in-dialog messages.
09731    */
09732    if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE 
09733        && sipmethod == SIP_INVITE) {
09734       char se_hdr[256];
09735       snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval, 
09736          strefresher2str(p->stimer->st_ref));
09737       add_header(req, "Require", "timer");
09738       add_header(req, "Session-Expires", se_hdr);
09739       snprintf(se_hdr, sizeof(se_hdr), "%d", st_get_se(p, FALSE));
09740       add_header(req, "Min-SE", se_hdr);
09741    }
09742 
09743    return 0;
09744 }
09745 
09746 /*! \brief Base transmit response function */
09747 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
09748 {
09749    struct sip_request resp;
09750    int seqno = 0;
09751 
09752    if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
09753       ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
09754       return -1;
09755    }
09756    respprep(&resp, p, msg, req);
09757    /* If we are cancelling an incoming invite for some reason, add information
09758       about the reason why we are doing this in clear text */
09759    if (p->method == SIP_INVITE && msg[0] != '1' && p->owner && p->owner->hangupcause) {
09760       char buf[10];
09761 
09762       add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
09763       snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
09764       add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
09765    }
09766    return send_response(p, &resp, reliable, seqno);
09767 }
09768 
09769 static int temp_pvt_init(void *data)
09770 {
09771    struct sip_pvt *p = data;
09772 
09773    p->do_history = 0;   /* XXX do we need it ? isn't already all 0 ? */
09774    return ast_string_field_init(p, 512);
09775 }
09776 
09777 static void temp_pvt_cleanup(void *data)
09778 {
09779    struct sip_pvt *p = data;
09780 
09781    ast_string_field_free_memory(p);
09782 
09783    ast_free(data);
09784 }
09785 
09786 /*! \brief Transmit response, no retransmits, using a temporary pvt structure */
09787 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)
09788 {
09789    struct sip_pvt *p = NULL;
09790 
09791    if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
09792       ast_log(LOG_ERROR, "Failed to get temporary pvt\n");
09793       return -1;
09794    }
09795 
09796    /* XXX the structure may be dirty from previous usage.
09797     * Here we should state clearly how we should reinitialize it
09798     * before using it.
09799     * E.g. certainly the threadstorage should be left alone,
09800     * but other thihngs such as flags etc. maybe need cleanup ?
09801     */
09802     
09803    /* Initialize the bare minimum */
09804    p->method = intended_method;
09805 
09806    if (!sin)
09807       p->ourip = internip;
09808    else {
09809       p->sa = *sin;
09810       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
09811    }
09812 
09813    p->branch = ast_random();
09814    make_our_tag(p->tag, sizeof(p->tag));
09815    p->ocseq = INITIAL_CSEQ;
09816 
09817    if (useglobal_nat && sin) {
09818       ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
09819       p->recv = *sin;
09820       do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
09821    }
09822 
09823    ast_string_field_set(p, fromdomain, default_fromdomain);
09824    build_via(p);
09825    ast_string_field_set(p, callid, callid);
09826 
09827    copy_socket_data(&p->socket, &req->socket);
09828 
09829    /* Use this temporary pvt structure to send the message */
09830    __transmit_response(p, msg, req, XMIT_UNRELIABLE);
09831 
09832    /* Free the string fields, but not the pool space */
09833    ast_string_field_init(p, 0);
09834 
09835    return 0;
09836 }
09837 
09838 /*! \brief Transmit response, no retransmits */
09839 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req) 
09840 {
09841    return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
09842 }
09843 
09844 /*! \brief Transmit response, no retransmits */
09845 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported) 
09846 {
09847    struct sip_request resp;
09848    respprep(&resp, p, msg, req);
09849    append_date(&resp);
09850    add_header(&resp, "Unsupported", unsupported);
09851    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
09852 }
09853 
09854 /*! \brief Transmit 422 response with Min-SE header (Session-Timers)  */
09855 static int transmit_response_with_minse(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minse_int)
09856 {
09857    struct sip_request resp;
09858    char minse_str[20];
09859 
09860    respprep(&resp, p, msg, req);
09861    append_date(&resp);
09862 
09863    snprintf(minse_str, sizeof(minse_str), "%d", minse_int);
09864    add_header(&resp, "Min-SE", minse_str);
09865    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
09866 }
09867 
09868 
09869 /*! \brief Transmit response, Make sure you get an ACK
09870    This is only used for responses to INVITEs, where we need to make sure we get an ACK
09871 */
09872 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
09873 {
09874    return __transmit_response(p, msg, req, req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL);
09875 }
09876 
09877 /*! \brief Append date to SIP message */
09878 static void append_date(struct sip_request *req)
09879 {
09880    char tmpdat[256];
09881    struct tm tm;
09882    time_t t = time(NULL);
09883 
09884    gmtime_r(&t, &tm);
09885    strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
09886    add_header(req, "Date", tmpdat);
09887 }
09888 
09889 /*! \brief Append date and content length before transmitting response */
09890 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
09891 {
09892    struct sip_request resp;
09893    respprep(&resp, p, msg, req);
09894    append_date(&resp);
09895    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
09896 }
09897 
09898 /*! \brief Append Accept header, content length before transmitting response */
09899 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
09900 {
09901    struct sip_request resp;
09902    respprep(&resp, p, msg, req);
09903    add_header(&resp, "Accept", "application/sdp");
09904    return send_response(p, &resp, reliable, 0);
09905 }
09906 
09907 /*! \brief Respond with authorization request */
09908 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)
09909 {
09910    struct sip_request resp;
09911    char tmp[512];
09912    int seqno = 0;
09913 
09914    if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
09915       ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
09916       return -1;
09917    }
09918    /* Stale means that they sent us correct authentication, but 
09919       based it on an old challenge (nonce) */
09920    snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", sip_cfg.realm, randdata, stale ? ", stale=true" : "");
09921    respprep(&resp, p, msg, req);
09922    add_header(&resp, header, tmp);
09923    append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
09924    return send_response(p, &resp, reliable, seqno);
09925 }
09926 
09927 /* Only use a static string for the msg, here! */
09928 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp)
09929 {
09930    int res;
09931 
09932    if (!(res = with_sdp ? transmit_response_with_sdp(p, msg, req, XMIT_UNRELIABLE, FALSE) : transmit_response(p, msg, req))) {
09933       p->last_provisional = msg;
09934       update_provisional_keepalive(p, with_sdp);
09935    }
09936 
09937    return res;
09938 }
09939 
09940 /*! \brief Add text body to SIP message */
09941 static int add_text(struct sip_request *req, const char *text)
09942 {
09943    /* XXX Convert \n's to \r\n's XXX */
09944    add_header(req, "Content-Type", "text/plain;charset=UTF-8");
09945    add_content(req, text);
09946    return 0;
09947 }
09948 
09949 /*! \brief Add DTMF INFO tone to sip message 
09950    Mode =   0 for application/dtmf-relay (Cisco)
09951       1 for application/dtmf
09952 */
09953 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode)
09954 {
09955    char tmp[256];
09956    int event;
09957    if (mode) {
09958       /* Application/dtmf short version used by some implementations */
09959       if (digit == '*')
09960          event = 10;
09961       else if (digit == '#')
09962          event = 11;
09963       else if ((digit >= 'A') && (digit <= 'D'))
09964          event = 12 + digit - 'A';
09965       else
09966          event = atoi(&digit);
09967       snprintf(tmp, sizeof(tmp), "%d\r\n", event);
09968       add_header(req, "Content-Type", "application/dtmf");
09969       add_content(req, tmp);
09970    } else {
09971       /* Application/dtmf-relay as documented by Cisco */
09972       snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
09973       add_header(req, "Content-Type", "application/dtmf-relay");
09974       add_content(req, tmp);
09975    }
09976    return 0;
09977 }
09978 
09979 /*! \brief add XML encoded media control with update 
09980    \note XML: The only way to turn 0 bits of information into a few hundred. (markster) */
09981 static int add_vidupdate(struct sip_request *req)
09982 {
09983    const char *xml_is_a_huge_waste_of_space =
09984       "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
09985       " <media_control>\r\n"
09986       "  <vc_primitive>\r\n"
09987       "   <to_encoder>\r\n"
09988       "    <picture_fast_update>\r\n"
09989       "    </picture_fast_update>\r\n"
09990       "   </to_encoder>\r\n"
09991       "  </vc_primitive>\r\n"
09992       " </media_control>\r\n";
09993    add_header(req, "Content-Type", "application/media_control+xml");
09994    add_content(req, xml_is_a_huge_waste_of_space);
09995    return 0;
09996 }
09997 
09998 /*! \brief Add codec offer to SDP offer/answer body in INVITE or 200 OK */
09999 static void add_codec_to_sdp(const struct sip_pvt *p, int codec,
10000               struct ast_str **m_buf, struct ast_str **a_buf,
10001               int debug, int *min_packet_size)
10002 {
10003    int rtp_code;
10004    struct ast_format_list fmt;
10005 
10006 
10007    if (debug)
10008       ast_verbose("Adding codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
10009    if ((rtp_code = ast_rtp_lookup_code(p->rtp, 1, codec)) == -1)
10010       return;
10011 
10012    if (p->rtp) {
10013       struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
10014       fmt = ast_codec_pref_getsize(pref, codec);
10015    } 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 */
10016       return;
10017    ast_str_append(m_buf, 0, " %d", rtp_code);
10018    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10019              ast_rtp_lookup_mime_subtype(1, codec,
10020                      ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
10021              ast_rtp_lookup_sample_rate(1, codec));
10022 
10023    switch (codec) {
10024    case AST_FORMAT_G729A:
10025       /* Indicate that we don't support VAD (G.729 annex B) */
10026       ast_str_append(a_buf, 0, "a=fmtp:%d annexb=no\r\n", rtp_code);
10027       break;
10028    case AST_FORMAT_G723_1:
10029       /* Indicate that we don't support VAD (G.723.1 annex A) */
10030       ast_str_append(a_buf, 0, "a=fmtp:%d annexa=no\r\n", rtp_code);
10031       break;
10032    case AST_FORMAT_ILBC:
10033       /* Add information about us using only 20/30 ms packetization */
10034       ast_str_append(a_buf, 0, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
10035       break;
10036    case AST_FORMAT_SIREN7:
10037       /* Indicate that we only expect 32Kbps */
10038       ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=32000\r\n", rtp_code);
10039       break;
10040    case AST_FORMAT_SIREN14:
10041       /* Indicate that we only expect 48Kbps */
10042       ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=48000\r\n", rtp_code);
10043       break;
10044    }
10045 
10046    if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
10047       *min_packet_size = fmt.cur_ms;
10048 
10049    /* Our first codec packetization processed cannot be zero */
10050    if ((*min_packet_size)==0 && fmt.cur_ms)
10051       *min_packet_size = fmt.cur_ms;
10052 }
10053 
10054 /*! \brief Add video codec offer to SDP offer/answer body in INVITE or 200 OK */
10055 /* This is different to the audio one now so we can add more caps later */
10056 static void add_vcodec_to_sdp(const struct sip_pvt *p, int codec,
10057               struct ast_str **m_buf, struct ast_str **a_buf,
10058               int debug, int *min_packet_size)
10059 {
10060    int rtp_code;
10061 
10062    if (!p->vrtp)
10063       return;
10064 
10065    if (debug)
10066       ast_verbose("Adding video codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
10067 
10068    if ((rtp_code = ast_rtp_lookup_code(p->vrtp, 1, codec)) == -1)
10069       return;
10070 
10071    ast_str_append(m_buf, 0, " %d", rtp_code);
10072    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10073              ast_rtp_lookup_mime_subtype(1, codec, 0),
10074              ast_rtp_lookup_sample_rate(1, codec));
10075    /* Add fmtp code here */
10076 }
10077 
10078 /*! \brief Add text codec offer to SDP offer/answer body in INVITE or 200 OK */
10079 static void add_tcodec_to_sdp(const struct sip_pvt *p, int codec,
10080               struct ast_str **m_buf, struct ast_str **a_buf,
10081               int debug, int *min_packet_size)
10082 {
10083    int rtp_code;
10084 
10085    if (!p->trtp)
10086       return;
10087 
10088    if (debug)
10089       ast_verbose("Adding text codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
10090 
10091    if ((rtp_code = ast_rtp_lookup_code(p->trtp, 1, codec)) == -1)
10092       return;
10093 
10094    ast_str_append(m_buf, 0, " %d", rtp_code);
10095    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10096              ast_rtp_lookup_mime_subtype(1, codec, 0),
10097              ast_rtp_lookup_sample_rate(1, codec));
10098    /* Add fmtp code here */
10099 
10100    if (codec == AST_FORMAT_T140RED) {
10101       ast_str_append(a_buf, 0, "a=fmtp:%d %d/%d/%d\r\n", rtp_code,
10102           ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140),
10103           ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140),
10104           ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140));
10105 
10106    }
10107 }
10108 
10109 
10110 /*! \brief Get Max T.38 Transmission rate from T38 capabilities */
10111 static unsigned int t38_get_rate(enum ast_control_t38_rate rate)
10112 {
10113    switch (rate) {
10114    case AST_T38_RATE_2400:
10115       return 2400;
10116    case AST_T38_RATE_4800:
10117       return 4800;
10118    case AST_T38_RATE_7200:
10119       return 7200;
10120    case AST_T38_RATE_9600:
10121       return 9600;
10122    case AST_T38_RATE_12000:
10123       return 12000;
10124    case AST_T38_RATE_14400:
10125       return 14400;
10126    default:
10127       return 0;
10128    }
10129 }
10130 
10131 /*! \brief Add RFC 2833 DTMF offer to SDP */
10132 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
10133             struct ast_str **m_buf, struct ast_str **a_buf,
10134             int debug)
10135 {
10136    int rtp_code;
10137 
10138    if (debug)
10139       ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype(0, format, 0));
10140    if ((rtp_code = ast_rtp_lookup_code(p->rtp, 0, format)) == -1)
10141       return;
10142 
10143    ast_str_append(m_buf, 0, " %d", rtp_code);
10144    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10145              ast_rtp_lookup_mime_subtype(0, format, 0),
10146              ast_rtp_lookup_sample_rate(0, format));
10147    if (format == AST_RTP_DTMF)   /* Indicate we support DTMF and FLASH... */
10148       ast_str_append(a_buf, 0, "a=fmtp:%d 0-16\r\n", rtp_code);
10149 }
10150 
10151 /*! \brief Set all IP media addresses for this call 
10152    \note called from add_sdp()
10153 */
10154 static void get_our_media_address(struct sip_pvt *p, int needvideo,
10155    struct sockaddr_in *sin, struct sockaddr_in *vsin, struct sockaddr_in *tsin,
10156    struct sockaddr_in *dest, struct sockaddr_in *vdest)
10157 {
10158    /* First, get our address */
10159    ast_rtp_get_us(p->rtp, sin);
10160    if (p->vrtp)
10161       ast_rtp_get_us(p->vrtp, vsin);
10162    if (p->trtp)
10163       ast_rtp_get_us(p->trtp, tsin);
10164 
10165    /* Now, try to figure out where we want them to send data */
10166    /* Is this a re-invite to move the media out, then use the original offer from caller  */
10167    if (p->redirip.sin_addr.s_addr) {   /* If we have a redirection IP, use it */
10168       dest->sin_port = p->redirip.sin_port;
10169       dest->sin_addr = p->redirip.sin_addr;
10170    } else {
10171       dest->sin_addr = p->ourip.sin_addr;
10172       dest->sin_port = sin->sin_port;
10173    }
10174    if (needvideo) {
10175       /* Determine video destination */
10176       if (p->vredirip.sin_addr.s_addr) {
10177          vdest->sin_addr = p->vredirip.sin_addr;
10178          vdest->sin_port = p->vredirip.sin_port;
10179       } else {
10180          vdest->sin_addr = p->ourip.sin_addr;
10181          vdest->sin_port = vsin->sin_port;
10182       }
10183    }
10184 
10185 }
10186 
10187 /*! \brief Add Session Description Protocol message 
10188 
10189     If oldsdp is TRUE, then the SDP version number is not incremented. This mechanism
10190     is used in Session-Timers where RE-INVITEs are used for refreshing SIP sessions 
10191     without modifying the media session in any way. 
10192 */
10193 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38)
10194 {
10195    int alreadysent = 0;
10196 
10197    struct sockaddr_in sin;
10198    struct sockaddr_in vsin;
10199    struct sockaddr_in tsin;
10200    struct sockaddr_in dest;
10201    struct sockaddr_in udptlsin;
10202    struct sockaddr_in vdest = { 0, };
10203    struct sockaddr_in tdest = { 0, };
10204    struct sockaddr_in udptldest = { 0, };
10205 
10206    /* SDP fields */
10207    char *version =   "v=0\r\n";     /* Protocol version */
10208    char subject[256];            /* Subject of the session */
10209    char owner[256];           /* Session owner/creator */
10210    char connection[256];            /* Connection data */
10211    char *session_time = "t=0 0\r\n";         /* Time the session is active */
10212    char bandwidth[256] = "";        /* Max bitrate */
10213    char *hold = "";
10214    struct ast_str *m_audio = ast_str_alloca(256);  /* Media declaration line for audio */
10215    struct ast_str *m_video = ast_str_alloca(256);  /* Media declaration line for video */
10216    struct ast_str *m_text = ast_str_alloca(256);   /* Media declaration line for text */
10217    struct ast_str *m_modem = ast_str_alloca(256);  /* Media declaration line for modem */
10218    struct ast_str *a_audio = ast_str_alloca(1024); /* Attributes for audio */
10219    struct ast_str *a_video = ast_str_alloca(1024); /* Attributes for video */
10220    struct ast_str *a_text = ast_str_alloca(1024);  /* Attributes for text */
10221    struct ast_str *a_modem = ast_str_alloca(1024); /* Attributes for modem */
10222 
10223    int x;
10224    int capability = 0;
10225    int needaudio = FALSE;
10226    int needvideo = FALSE;
10227    int needtext = FALSE;
10228    int debug = sip_debug_test_pvt(p);
10229    int min_audio_packet_size = 0;
10230    int min_video_packet_size = 0;
10231    int min_text_packet_size = 0;
10232 
10233    char codecbuf[SIPBUFSIZE];
10234    char buf[SIPBUFSIZE];
10235    char dummy_answer[256];
10236 
10237    /* Set the SDP session name */
10238    snprintf(subject, sizeof(subject), "s=%s\r\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
10239 
10240    if (!p->rtp) {
10241       ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
10242       return AST_FAILURE;
10243    }
10244    /* XXX We should not change properties in the SIP dialog until 
10245       we have acceptance of the offer if this is a re-invite */
10246 
10247    /* Set RTP Session ID and version */
10248    if (!p->sessionid) {
10249       p->sessionid = (int)ast_random();
10250       p->sessionversion = p->sessionid;
10251    } else {
10252       if (oldsdp == FALSE)
10253          p->sessionversion++;
10254    }
10255 
10256    if (add_audio) {
10257       /* Check if we need video in this call */
10258       if ((p->jointcapability & AST_FORMAT_VIDEO_MASK) && !p->novideo) {
10259          if (p->vrtp) {
10260             needvideo = TRUE;
10261             ast_debug(2, "This call needs video offers!\n");
10262          } else
10263             ast_debug(2, "This call needs video offers, but there's no video support enabled!\n");
10264       }
10265       /* Check if we need text in this call */
10266       if ((p->jointcapability & AST_FORMAT_TEXT_MASK) && !p->notext) {
10267          if (sipdebug_text)
10268             ast_verbose("We think we can do text\n");
10269          if (p->trtp) {
10270             if (sipdebug_text) {
10271                ast_verbose("And we have a text rtp object\n");
10272             }
10273             needtext = TRUE;
10274             ast_debug(2, "This call needs text offers! \n");
10275          } else {
10276             ast_debug(2, "This call needs text offers, but there's no text support enabled ! \n");
10277          }
10278       }
10279    }
10280 
10281    get_our_media_address(p, needvideo, &sin, &vsin, &tsin, &dest, &vdest);
10282 
10283    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));
10284    snprintf(connection, sizeof(connection), "c=IN IP4 %s\r\n", ast_inet_ntoa(dest.sin_addr));
10285 
10286    if (add_audio) {
10287       capability = p->jointcapability;
10288 
10289       /* XXX note, Video and Text are negated - 'true' means 'no' */
10290       ast_debug(1, "** Our capability: %s Video flag: %s Text flag: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability), 
10291            p->novideo ? "True" : "False", p->notext ? "True" : "False");
10292       ast_debug(1, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));
10293 
10294       /* Check if we need audio */
10295       if (capability & AST_FORMAT_AUDIO_MASK)
10296          needaudio = TRUE;
10297 
10298       if (debug) 
10299          ast_verbose("Audio is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(sin.sin_port)); 
10300 
10301       /* Ok, we need video. Let's add what we need for video and set codecs.
10302          Video is handled differently than audio since we can not transcode. */
10303       if (needvideo) {
10304          ast_str_append(&m_video, 0, "m=video %d RTP/AVP", ntohs(vdest.sin_port));
10305 
10306          /* Build max bitrate string */
10307          if (p->maxcallbitrate)
10308             snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
10309          if (debug) 
10310             ast_verbose("Video is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(vdest.sin_port));  
10311       }
10312 
10313       /* Ok, we need text. Let's add what we need for text and set codecs.
10314          Text is handled differently than audio since we can not transcode. */
10315       if (needtext) {
10316          if (sipdebug_text)
10317             ast_verbose("Lets set up the text sdp\n");
10318          /* Determine text destination */
10319          if (p->tredirip.sin_addr.s_addr) {
10320             tdest.sin_addr = p->tredirip.sin_addr;
10321             tdest.sin_port = p->tredirip.sin_port;
10322          } else {
10323             tdest.sin_addr = p->ourip.sin_addr;
10324             tdest.sin_port = tsin.sin_port;
10325          }
10326          ast_str_append(&m_text, 0, "m=text %d RTP/AVP", ntohs(tdest.sin_port));
10327          if (debug) /* XXX should I use tdest below ? */
10328             ast_verbose("Text is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(tsin.sin_port)); 
10329 
10330       }
10331 
10332       /* Start building generic SDP headers */
10333 
10334       /* We break with the "recommendation" and send our IP, in order that our
10335          peer doesn't have to ast_gethostbyname() us */
10336 
10337       ast_str_append(&m_audio, 0, "m=audio %d RTP/AVP", ntohs(dest.sin_port));
10338 
10339       if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR)
10340          hold = "a=recvonly\r\n";
10341       else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE)
10342          hold = "a=inactive\r\n";
10343       else
10344          hold = "a=sendrecv\r\n";
10345 
10346       /* Now, start adding audio codecs. These are added in this order:
10347          - First what was requested by the calling channel
10348          - Then preferences in order from sip.conf device config for this peer/user
10349          - Then other codecs in capabilities, including video
10350       */
10351 
10352       /* Prefer the audio codec we were requested to use, first, no matter what 
10353          Note that p->prefcodec can include video codecs, so mask them out
10354       */
10355       if (capability & p->prefcodec) {
10356          int codec = p->prefcodec & AST_FORMAT_AUDIO_MASK;
10357 
10358          add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
10359          alreadysent |= codec;
10360       }
10361 
10362       /* Start by sending our preferred audio/video codecs */
10363       for (x = 0; x < 32; x++) {
10364          int codec;
10365 
10366          if (!(codec = ast_codec_pref_index(&p->prefs, x)))
10367             break; 
10368 
10369          if (!(capability & codec))
10370             continue;
10371 
10372          if (alreadysent & codec)
10373             continue;
10374 
10375          add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
10376          alreadysent |= codec;
10377       }
10378 
10379       /* Now send any other common audio and video codecs, and non-codec formats: */
10380       for (x = 1; x <= (needtext ? AST_FORMAT_TEXT_MASK : (needvideo ? AST_FORMAT_VIDEO_MASK : AST_FORMAT_AUDIO_MASK)); x <<= 1) {
10381          if (!(capability & x))  /* Codec not requested */
10382             continue;
10383 
10384          if (alreadysent & x) /* Already added to SDP */
10385             continue;
10386 
10387          if (x & AST_FORMAT_AUDIO_MASK)
10388             add_codec_to_sdp(p, x, &m_audio, &a_audio, debug, &min_audio_packet_size);
10389          else if (x & AST_FORMAT_VIDEO_MASK)
10390             add_vcodec_to_sdp(p, x, &m_video, &a_video, debug, &min_video_packet_size);
10391          else if (x & AST_FORMAT_TEXT_MASK)
10392             add_tcodec_to_sdp(p, x, &m_text, &a_text, debug, &min_text_packet_size);
10393       }
10394 
10395       /* Now add DTMF RFC2833 telephony-event as a codec */
10396       for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
10397          if (!(p->jointnoncodeccapability & x))
10398             continue;
10399 
10400          add_noncodec_to_sdp(p, x, &m_audio, &a_audio, debug);
10401       }
10402 
10403       ast_debug(3, "-- Done with adding codecs to SDP\n");
10404 
10405       if (!p->owner || !ast_internal_timing_enabled(p->owner))
10406          ast_str_append(&a_audio, 0, "a=silenceSupp:off - - - -\r\n");
10407 
10408       if (min_audio_packet_size)
10409          ast_str_append(&a_audio, 0, "a=ptime:%d\r\n", min_audio_packet_size);
10410 
10411       /* XXX don't think you can have ptime for video */
10412       if (min_video_packet_size)
10413          ast_str_append(&a_video, 0, "a=ptime:%d\r\n", min_video_packet_size);
10414 
10415       /* XXX don't think you can have ptime for text */
10416       if (min_text_packet_size)
10417          ast_str_append(&a_text, 0, "a=ptime:%d\r\n", min_text_packet_size);
10418  
10419       if (m_audio->len - m_audio->used < 2 || m_video->len - m_video->used < 2 ||
10420           m_text->len - m_text->used < 2 || a_text->len - a_text->used < 2 ||
10421           a_audio->len - a_audio->used < 2 || a_video->len - a_video->used < 2)
10422          ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
10423    }
10424 
10425    if (add_t38) {
10426       /* Our T.38 end is */
10427       ast_udptl_get_us(p->udptl, &udptlsin);
10428 
10429       /* Determine T.38 UDPTL destination */
10430       if (p->udptlredirip.sin_addr.s_addr) {
10431          udptldest.sin_port = p->udptlredirip.sin_port;
10432          udptldest.sin_addr = p->udptlredirip.sin_addr;
10433       } else {
10434          udptldest.sin_addr = p->ourip.sin_addr;
10435          udptldest.sin_port = udptlsin.sin_port;
10436       }
10437 
10438       if (debug)
10439          ast_debug(1, "T.38 UDPTL is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(udptlsin.sin_port));
10440 
10441       /* We break with the "recommendation" and send our IP, in order that our
10442          peer doesn't have to ast_gethostbyname() us */
10443 
10444       ast_str_append(&m_modem, 0, "m=image %d udptl t38\r\n", ntohs(udptldest.sin_port));
10445 
10446       ast_str_append(&a_modem, 0, "a=T38FaxVersion:%d\r\n", p->t38.our_parms.version);
10447       ast_str_append(&a_modem, 0, "a=T38MaxBitRate:%d\r\n", t38_get_rate(p->t38.our_parms.rate));
10448       if (p->t38.our_parms.fill_bit_removal) {
10449          ast_str_append(&a_modem, 0, "a=T38FaxFillBitRemoval\r\n");
10450       }
10451       if (p->t38.our_parms.transcoding_mmr) {
10452          ast_str_append(&a_modem, 0, "a=T38FaxTranscodingMMR\r\n");
10453       }
10454       if (p->t38.our_parms.transcoding_jbig) {
10455          ast_str_append(&a_modem, 0, "a=T38FaxTranscodingJBIG\r\n");
10456       }
10457       switch (p->t38.our_parms.rate_management) {
10458       case AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF:
10459          ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:transferredTCF\r\n");
10460          break;
10461       case AST_T38_RATE_MANAGEMENT_LOCAL_TCF:
10462          ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:localTCF\r\n");
10463          break;
10464       }
10465       ast_str_append(&a_modem, 0, "a=T38FaxMaxDatagram:%u\r\n", ast_udptl_get_local_max_datagram(p->udptl));
10466       switch (ast_udptl_get_error_correction_scheme(p->udptl)) {
10467       case UDPTL_ERROR_CORRECTION_NONE:
10468          break;
10469       case UDPTL_ERROR_CORRECTION_FEC:
10470          ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPFEC\r\n");
10471          break;
10472       case UDPTL_ERROR_CORRECTION_REDUNDANCY:
10473          ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPRedundancy\r\n");
10474          break;
10475       }
10476    }
10477 
10478    if (needaudio)
10479       ast_str_append(&m_audio, 0, "\r\n");
10480    if (needvideo)
10481       ast_str_append(&m_video, 0, "\r\n");
10482    if (needtext)
10483       ast_str_append(&m_text, 0, "\r\n");
10484 
10485    add_header(resp, "Content-Type", "application/sdp");
10486    add_content(resp, version);
10487    add_content(resp, owner);
10488    add_content(resp, subject);
10489    add_content(resp, connection);
10490    if (needvideo)    /* only if video response is appropriate */
10491       add_content(resp, bandwidth);
10492    add_content(resp, session_time);
10493    if (needaudio) {
10494       add_content(resp, m_audio->str);
10495       add_content(resp, a_audio->str);
10496       add_content(resp, hold);
10497    } else if (p->offered_media[SDP_AUDIO].offered) {
10498       snprintf(dummy_answer, sizeof(dummy_answer), "m=audio 0 RTP/AVP %s\r\n", p->offered_media[SDP_AUDIO].text);
10499       add_content(resp, dummy_answer);
10500    }
10501    if (needvideo) { /* only if video response is appropriate */
10502       add_content(resp, m_video->str);
10503       add_content(resp, a_video->str);
10504       add_content(resp, hold);   /* Repeat hold for the video stream */
10505    } else if (p->offered_media[SDP_VIDEO].offered) {
10506       snprintf(dummy_answer, sizeof(dummy_answer), "m=video 0 RTP/AVP %s\r\n", p->offered_media[SDP_VIDEO].text);
10507       add_content(resp, dummy_answer);
10508    }
10509    if (needtext) { /* only if text response is appropriate */
10510       add_content(resp, m_text->str);
10511       add_content(resp, a_text->str);
10512       add_content(resp, hold);   /* Repeat hold for the text stream */
10513    } else if (p->offered_media[SDP_TEXT].offered) {
10514       snprintf(dummy_answer, sizeof(dummy_answer), "m=text 0 RTP/AVP %s\r\n", p->offered_media[SDP_TEXT].text);
10515       add_content(resp, dummy_answer);
10516    }
10517    if (add_t38) {
10518       add_content(resp, m_modem->str);
10519       add_content(resp, a_modem->str);
10520    } else if (p->offered_media[SDP_IMAGE].offered) {
10521       add_content(resp, "m=image 0 udptl t38\r\n");
10522    }
10523 
10524    /* Update lastrtprx when we send our SDP */
10525    p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
10526 
10527    ast_debug(3, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, capability));
10528 
10529    return AST_SUCCESS;
10530 }
10531 
10532 /*! \brief Used for 200 OK and 183 early media */
10533 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
10534 {
10535    struct sip_request resp;
10536    int seqno;
10537    
10538    if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
10539       ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
10540       return -1;
10541    }
10542    respprep(&resp, p, msg, req);
10543    if (p->udptl) {
10544       add_sdp(&resp, p, 0, 0, 1);
10545    } else 
10546       ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
10547    if (retrans && !p->pendinginvite)
10548       p->pendinginvite = seqno;     /* Buggy clients sends ACK on RINGING too */
10549    return send_response(p, &resp, retrans, seqno);
10550 }
10551 
10552 /*! \brief copy SIP request (mostly used to save request for responses) */
10553 static void copy_request(struct sip_request *dst, const struct sip_request *src)
10554 {
10555    /* XXX this function can encounter memory allocation errors, perhaps it
10556     * should return a value */
10557 
10558    struct ast_str *duplicate = dst->data;
10559    struct ast_str *duplicate_content = dst->content;
10560 
10561    /* copy the entire request then restore the original data and content
10562     * members from the dst request */
10563    memcpy(dst, src, sizeof(*dst));
10564    dst->data = duplicate;
10565    dst->content = duplicate_content;
10566 
10567    /* copy the data into the dst request */
10568    if (!dst->data && !(dst->data = ast_str_create(ast_str_strlen(src->data) + 1)))
10569       return;
10570    ast_str_copy_string(&dst->data, src->data);
10571 
10572    /* copy the content into the dst request (if it exists) */
10573    if (src->content) {
10574       if (!dst->content && !(dst->content = ast_str_create(ast_str_strlen(src->content) + 1)))
10575          return;
10576       ast_str_copy_string(&dst->content, src->content);
10577    }
10578 }
10579 
10580 /*! \brief Used for 200 OK and 183 early media 
10581    \return Will return XMIT_ERROR for network errors.
10582 */
10583 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp)
10584 {
10585    struct sip_request resp;
10586    int seqno;
10587    if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
10588       ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
10589       return -1;
10590    }
10591    respprep(&resp, p, msg, req);
10592    if (p->rtp) {
10593       if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
10594          ast_debug(1, "Setting framing from config on incoming call\n");
10595          ast_rtp_codec_setpref(p->rtp, &p->prefs);
10596       }
10597       try_suggested_sip_codec(p);
10598       if (p->t38.state == T38_ENABLED) {
10599          add_sdp(&resp, p, oldsdp, TRUE, TRUE);
10600       } else {
10601          add_sdp(&resp, p, oldsdp, TRUE, FALSE);
10602       }
10603    } else 
10604       ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
10605    if (reliable && !p->pendinginvite)
10606       p->pendinginvite = seqno;     /* Buggy clients sends ACK on RINGING too */
10607    return send_response(p, &resp, reliable, seqno);
10608 }
10609 
10610 /*! \brief Parse first line of incoming SIP request */
10611 static int determine_firstline_parts(struct sip_request *req) 
10612 {
10613    char *e = ast_skip_blanks(req->data->str);   /* there shouldn't be any */
10614    char *local_rlPart1;
10615 
10616    if (!*e)
10617       return -1;
10618    req->rlPart1 = e - req->data->str;  /* method or protocol */
10619    local_rlPart1 = e;
10620    e = ast_skip_nonblanks(e);
10621    if (*e)
10622       *e++ = '\0';
10623    /* Get URI or status code */
10624    e = ast_skip_blanks(e);
10625    if ( !*e )
10626       return -1;
10627    ast_trim_blanks(e);
10628 
10629    if (!strcasecmp(local_rlPart1, "SIP/2.0") ) { /* We have a response */
10630       if (strlen(e) < 3)   /* status code is 3 digits */
10631          return -1;
10632       req->rlPart2 = e - req->data->str;
10633    } else { /* We have a request */
10634       if ( *e == '<' ) { /* XXX the spec says it must not be in <> ! */
10635          ast_debug(3, "Oops. Bogus uri in <> %s\n", e);
10636          e++;
10637          if (!*e)
10638             return -1; 
10639       }
10640       req->rlPart2 = e - req->data->str;  /* URI */
10641       e = ast_skip_nonblanks(e);
10642       if (*e)
10643          *e++ = '\0';
10644       e = ast_skip_blanks(e);
10645       if (strcasecmp(e, "SIP/2.0") ) {
10646          ast_debug(3, "Skipping packet - Bad request protocol %s\n", e);
10647          return -1;
10648       }
10649    }
10650    return 1;
10651 }
10652 
10653 /*! \brief Transmit reinvite with SDP
10654 \note    A re-invite is basically a new INVITE with the same CALL-ID and TAG as the
10655    INVITE that opened the SIP dialogue 
10656    We reinvite so that the audio stream (RTP) go directly between
10657    the SIP UAs. SIP Signalling stays with * in the path.
10658    
10659    If t38version is TRUE, we send T38 SDP for re-invite from audio/video to
10660    T38 UDPTL transmission on the channel
10661 
10662     If oldsdp is TRUE then the SDP version number is not incremented. This
10663     is needed for Session-Timers so we can send a re-invite to refresh the
10664     SIP session without modifying the media session. 
10665 */
10666 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp)
10667 {
10668    struct sip_request req;
10669    
10670    reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ?  SIP_UPDATE : SIP_INVITE, 0, 1);
10671 
10672    add_header(&req, "Allow", ALLOWED_METHODS);
10673    add_supported_header(p, &req);
10674    if (sipdebug) {
10675       if (oldsdp == TRUE)
10676          add_header(&req, "X-asterisk-Info", "SIP re-invite (Session-Timers)");
10677       else
10678          add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
10679    }
10680 
10681    if (p->do_history)
10682       append_history(p, "ReInv", "Re-invite sent");
10683    memset(p->offered_media, 0, sizeof(p->offered_media));
10684 
10685    if (t38version)
10686       add_sdp(&req, p, oldsdp, FALSE, TRUE);
10687    else
10688       add_sdp(&req, p, oldsdp, TRUE, FALSE);
10689 
10690    /* Use this as the basis */
10691    initialize_initreq(p, &req);
10692    p->lastinvite = p->ocseq;
10693    ast_set_flag(&p->flags[0], SIP_OUTGOING);       /* Change direction of this dialog */
10694 
10695    return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
10696 }
10697 
10698 /* \brief Remove URI parameters at end of URI, not in username part though */
10699 static char *remove_uri_parameters(char *uri)
10700 {
10701    char *atsign;
10702    atsign = strchr(uri, '@'); /* First, locate the at sign */
10703    if (!atsign)
10704       atsign = uri;  /* Ok hostname only, let's stick with the rest */
10705    atsign = strchr(atsign, ';'); /* Locate semi colon */
10706    if (atsign)
10707       *atsign = '\0';   /* Kill at the semi colon */
10708    return uri;
10709 }
10710 
10711 /*! \brief Check Contact: URI of SIP message */
10712 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
10713 {
10714    char stripped[SIPBUFSIZE];
10715    char *c;
10716 
10717    ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
10718    c = get_in_brackets(stripped);
10719    /* Cut the URI at the at sign after the @, not in the username part */
10720    c = remove_uri_parameters(c);
10721    if (!ast_strlen_zero(c))
10722       ast_string_field_set(p, uri, c);
10723 
10724 }
10725 
10726 /*! \brief Build contact header - the contact header we send out */
10727 static void build_contact(struct sip_pvt *p)
10728 {
10729 
10730    int ourport = ntohs(p->ourip.sin_port);
10731    /* only add port if it's non-standard for the transport type */
10732    if (!sip_standard_port(p->socket.type, ourport)) {
10733       if (p->socket.type == SIP_TRANSPORT_UDP)
10734          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);
10735       else
10736          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));
10737    } else {
10738       if (p->socket.type == SIP_TRANSPORT_UDP)
10739          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));
10740       else
10741          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));
10742    }
10743 }
10744 
10745 /*! \brief Build the Remote Party-ID & From using callingpres options */
10746 static void build_rpid(struct sip_pvt *p)
10747 {
10748    int send_pres_tags = TRUE;
10749    const char *privacy=NULL;
10750    const char *screen=NULL;
10751    char buf[256];
10752    const char *clid = default_callerid;
10753    const char *clin = NULL;
10754    const char *fromdomain;
10755 
10756    if (!ast_strlen_zero(p->rpid) || !ast_strlen_zero(p->rpid_from))  
10757       return;
10758 
10759    if (p->owner && !ast_strlen_zero(p->owner->cid.cid_num))
10760       clid = p->owner->cid.cid_num;
10761    if (p->owner && p->owner->cid.cid_name)
10762       clin = p->owner->cid.cid_name;
10763    if (ast_strlen_zero(clin))
10764       clin = clid;
10765 
10766    switch (p->callingpres) {
10767    case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
10768       privacy = "off";
10769       screen = "no";
10770       break;
10771    case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
10772       privacy = "off";
10773       screen = "yes";
10774       break;
10775    case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
10776       privacy = "off";
10777       screen = "no";
10778       break;
10779    case AST_PRES_ALLOWED_NETWORK_NUMBER:
10780       privacy = "off";
10781       screen = "yes";
10782       break;
10783    case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
10784       privacy = "full";
10785       screen = "no";
10786       break;
10787    case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
10788       privacy = "full";
10789       screen = "yes";
10790       break;
10791    case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
10792       privacy = "full";
10793       screen = "no";
10794       break;
10795    case AST_PRES_PROHIB_NETWORK_NUMBER:
10796       privacy = "full";
10797       screen = "yes";
10798       break;
10799    case AST_PRES_NUMBER_NOT_AVAILABLE:
10800       send_pres_tags = FALSE;
10801       break;
10802    default:
10803       ast_log(LOG_WARNING, "Unsupported callingpres (%d)\n", p->callingpres);
10804       if ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)
10805          privacy = "full";
10806       else
10807          privacy = "off";
10808       screen = "no";
10809       break;
10810    }
10811    
10812    fromdomain = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr));
10813 
10814    snprintf(buf, sizeof(buf), "\"%s\" <sip:%s@%s>", clin, clid, fromdomain);
10815    if (send_pres_tags)
10816       snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ";privacy=%s;screen=%s", privacy, screen);
10817    ast_string_field_set(p, rpid, buf);
10818 
10819    ast_string_field_build(p, rpid_from, "\"%s\" <sip:%s@%s>;tag=%s", clin,
10820                 S_OR(p->fromuser, clid),
10821                 fromdomain, p->tag);
10822 }
10823 
10824 /*! \brief Initiate new SIP request to peer/user */
10825 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod)
10826 {
10827    struct ast_str *invite = ast_str_alloca(256);
10828    char from[256];
10829    char to[256];
10830    char tmp_n[SIPBUFSIZE/2];  /* build a local copy of 'n' if needed */
10831    char tmp_l[SIPBUFSIZE/2];  /* build a local copy of 'l' if needed */
10832    const char *l = NULL;   /* XXX what is this, exactly ? */
10833    const char *n = NULL;   /* XXX what is this, exactly ? */
10834    const char *d = NULL;   /* domain in from header */
10835    const char *urioptions = "";
10836    int ourport;
10837 
10838    if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
10839       const char *s = p->username;  /* being a string field, cannot be NULL */
10840 
10841       /* Test p->username against allowed characters in AST_DIGIT_ANY
10842          If it matches the allowed characters list, then sipuser = ";user=phone"
10843          If not, then sipuser = ""
10844       */
10845       /* + is allowed in first position in a tel: uri */
10846       if (*s == '+')
10847          s++;
10848       for (; *s; s++) {
10849          if (!strchr(AST_DIGIT_ANYNUM, *s) )
10850             break;
10851       }
10852       /* If we have only digits, add ;user=phone to the uri */
10853       if (!*s)
10854          urioptions = ";user=phone";
10855    }
10856 
10857 
10858    snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
10859 
10860    d = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr));
10861    if (p->owner) {
10862       l = p->owner->cid.cid_num;
10863       n = p->owner->cid.cid_name;
10864    }
10865    /* if we are not sending RPID and user wants his callerid restricted */
10866    if (!ast_test_flag(&p->flags[0], SIP_SENDRPID) &&
10867        ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)) {
10868       l = CALLERID_UNKNOWN;
10869       n = l;
10870       d = FROMDOMAIN_INVALID;
10871    }
10872    if (ast_strlen_zero(l))
10873       l = default_callerid;
10874    if (ast_strlen_zero(n))
10875       n = l;
10876    /* Allow user to be overridden */
10877    if (!ast_strlen_zero(p->fromuser))
10878       l = p->fromuser;
10879    else /* Save for any further attempts */
10880       ast_string_field_set(p, fromuser, l);
10881 
10882    /* Allow user to be overridden */
10883    if (!ast_strlen_zero(p->fromname))
10884       n = p->fromname;
10885    else /* Save for any further attempts */
10886       ast_string_field_set(p, fromname, n);
10887 
10888    if (sip_cfg.pedanticsipchecking) {
10889       ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
10890       n = tmp_n;
10891       ast_uri_encode(l, tmp_l, sizeof(tmp_l), 0);
10892       l = tmp_l;
10893    }
10894 
10895    ourport = ntohs(p->ourip.sin_port);
10896    if (!sip_standard_port(p->socket.type, ourport) && ast_strlen_zero(p->fromdomain))
10897       snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=%s", n, l, d, ourport, p->tag);
10898    else
10899       snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, l, d, p->tag);
10900 
10901    /* If we're calling a registered SIP peer, use the fullcontact to dial to the peer */
10902    if (!ast_strlen_zero(p->fullcontact)) {
10903       /* If we have full contact, trust it */
10904       ast_str_append(&invite, 0, "%s", p->fullcontact);
10905    } else {
10906       /* Otherwise, use the username while waiting for registration */
10907       ast_str_append(&invite, 0, "sip:");
10908       if (!ast_strlen_zero(p->username)) {
10909          n = p->username;
10910          if (sip_cfg.pedanticsipchecking) {
10911             ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
10912             n = tmp_n;
10913          }
10914          ast_str_append(&invite, 0, "%s@", n);
10915       }
10916       ast_str_append(&invite, 0, "%s", p->tohost);
10917       if (p->portinuri)
10918          ast_str_append(&invite, 0, ":%d", ntohs(p->sa.sin_port));
10919       ast_str_append(&invite, 0, "%s", urioptions);
10920    }
10921 
10922    /* If custom URI options have been provided, append them */
10923    if (p->options && !ast_strlen_zero(p->options->uri_options))
10924       ast_str_append(&invite, 0, ";%s", p->options->uri_options);
10925    
10926    /* This is the request URI, which is the next hop of the call
10927       which may or may not be the destination of the call
10928    */
10929    ast_string_field_set(p, uri, invite->str);
10930   
10931    if (!ast_strlen_zero(p->todnid)) {
10932       /*! \todo Need to add back the VXML URL here at some point, possibly use build_string for all this junk */
10933       if (!strchr(p->todnid, '@')) {
10934          /* We have no domain in the dnid */
10935          snprintf(to, sizeof(to), "<sip:%s@%s>%s%s", p->todnid, p->tohost, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
10936       } else {
10937          snprintf(to, sizeof(to), "<sip:%s>%s%s", p->todnid, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
10938       }
10939    } else {
10940       if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) { 
10941          /* If this is a NOTIFY, use the From: tag in the subscribe (RFC 3265) */
10942          snprintf(to, sizeof(to), "<%s%s>;tag=%s", (strncasecmp(p->uri, "sip:", 4) ? "sip:" : ""), p->uri, p->theirtag);
10943       } else if (p->options && p->options->vxml_url) {
10944          /* If there is a VXML URL append it to the SIP URL */
10945          snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
10946       } else 
10947          snprintf(to, sizeof(to), "<%s>", p->uri);
10948    }
10949 
10950    init_req(req, sipmethod, p->uri);
10951    /* now tmp_n is available so reuse it to build the CSeq */
10952    snprintf(tmp_n, sizeof(tmp_n), "%d %s", ++p->ocseq, sip_methods[sipmethod].text);
10953 
10954    add_header(req, "Via", p->via);
10955    add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
10956    /* This will be a no-op most of the time. However, under certain circumstances,
10957     * NOTIFY messages will use this function for preparing the request and should
10958     * have Route headers present.
10959     */
10960    add_route(req, p->route);
10961 
10962    /* Build Remote Party-ID and From */
10963    if (ast_test_flag(&p->flags[0], SIP_SENDRPID) && (sipmethod == SIP_INVITE)) {
10964       build_rpid(p);
10965       add_header(req, "From", p->rpid_from);
10966    } else 
10967       add_header(req, "From", from);
10968    add_header(req, "To", to);
10969    ast_string_field_set(p, exten, l);
10970    build_contact(p);
10971    add_header(req, "Contact", p->our_contact);
10972    add_header(req, "Call-ID", p->callid);
10973    add_header(req, "CSeq", tmp_n);
10974    if (!ast_strlen_zero(global_useragent))
10975       add_header(req, "User-Agent", global_useragent);
10976    if (!ast_strlen_zero(p->rpid))
10977       add_header(req, "Remote-Party-ID", p->rpid);
10978 }
10979 
10980 /*! \brief Build REFER/INVITE/OPTIONS/SUBSCRIBE message and transmit it 
10981    \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
10982  \param p sip_pvt structure
10983  \param sdp unknown 
10984  \param sipmethod unknown 
10985  
10986 */
10987 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init)
10988 {
10989    struct sip_request req;
10990    struct ast_variable *var;
10991    
10992    req.method = sipmethod;
10993    if (init) {/* Bump branch even on initial requests */
10994       p->branch ^= ast_random();
10995       p->invite_branch = p->branch;
10996       build_via(p);
10997    }
10998    if (init > 1)
10999       initreqprep(&req, p, sipmethod);
11000    else
11001       /* If init=1, we should not generate a new branch. If it's 0, we need a new branch. */
11002       reqprep(&req, p, sipmethod, 0, init ? 0 : 1);
11003       
11004    if (p->options && p->options->auth)
11005       add_header(&req, p->options->authheader, p->options->auth);
11006    append_date(&req);
11007    if (sipmethod == SIP_REFER) { /* Call transfer */
11008       if (p->refer) {
11009          char buf[SIPBUFSIZE];
11010          if (!ast_strlen_zero(p->refer->refer_to))
11011             add_header(&req, "Refer-To", p->refer->refer_to);
11012          if (!ast_strlen_zero(p->refer->referred_by)) {
11013             snprintf(buf, sizeof(buf), "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
11014             add_header(&req, "Referred-By", buf);
11015          }
11016       }
11017    } else if (sipmethod == SIP_SUBSCRIBE) { /* We only support sending MWI subscriptions right now */
11018       char buf[SIPBUFSIZE];
11019 
11020       add_header(&req, "Event", "message-summary");
11021       add_header(&req, "Accept", "application/simple-message-summary");
11022       snprintf(buf, sizeof(buf), "%d", mwi_expiry);
11023       add_header(&req, "Expires", buf);
11024    }
11025 
11026    /* This new INVITE is part of an attended transfer. Make sure that the
11027    other end knows and replace the current call with this new call */
11028    if (p->options && !ast_strlen_zero(p->options->replaces)) {
11029       add_header(&req, "Replaces", p->options->replaces);
11030       add_header(&req, "Require", "replaces");
11031    }
11032 
11033    /* Add Session-Timers related headers */
11034    if (st_get_mode(p) == SESSION_TIMER_MODE_ORIGINATE) {
11035       char i2astr[10];
11036 
11037       if (!p->stimer->st_interval)
11038          p->stimer->st_interval = st_get_se(p, TRUE);
11039 
11040       p->stimer->st_active = TRUE;
11041       
11042       snprintf(i2astr, sizeof(i2astr), "%d", p->stimer->st_interval);
11043       add_header(&req, "Session-Expires", i2astr);
11044       snprintf(i2astr, sizeof(i2astr), "%d", st_get_se(p, FALSE));
11045       add_header(&req, "Min-SE", i2astr);
11046    }
11047 
11048    add_header(&req, "Allow", ALLOWED_METHODS);
11049    add_supported_header(p, &req);
11050 
11051    if(p->notify_headers) {
11052       char buf[512];
11053       for (var = p->notify_headers; var; var = var->next) {
11054          ast_copy_string(buf, var->value, sizeof(buf));
11055          add_header(&req, var->name, ast_unescape_semicolon(buf));
11056       }
11057    }
11058    if (p->options && p->options->addsipheaders && p->owner) {
11059       struct ast_channel *chan = p->owner; /* The owner channel */
11060       struct varshead *headp;
11061    
11062       ast_channel_lock(chan);
11063 
11064       headp = &chan->varshead;
11065 
11066       if (!headp)
11067          ast_log(LOG_WARNING, "No Headp for the channel...ooops!\n");
11068       else {
11069          const struct ast_var_t *current;
11070          AST_LIST_TRAVERSE(headp, current, entries) {  
11071             /* SIPADDHEADER: Add SIP header to outgoing call */
11072             if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
11073                char *content, *end;
11074                const char *header = ast_var_value(current);
11075                char *headdup = ast_strdupa(header);
11076 
11077                /* Strip of the starting " (if it's there) */
11078                if (*headdup == '"')
11079                   headdup++;
11080                if ((content = strchr(headdup, ':'))) {
11081                   *content++ = '\0';
11082                   content = ast_skip_blanks(content); /* Skip white space */
11083                   /* Strip the ending " (if it's there) */
11084                   end = content + strlen(content) -1; 
11085                   if (*end == '"')
11086                      *end = '\0';
11087                
11088                   add_header(&req, headdup, content);
11089                   if (sipdebug)
11090                      ast_debug(1, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
11091                }
11092             }
11093          }
11094       }
11095 
11096       ast_channel_unlock(chan);
11097    }
11098    if (sdp) {
11099       memset(p->offered_media, 0, sizeof(p->offered_media));
11100       if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
11101          ast_debug(1, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
11102          add_sdp(&req, p, FALSE, FALSE, TRUE);
11103       } else if (p->rtp) 
11104          add_sdp(&req, p, FALSE, TRUE, FALSE);
11105    }
11106 
11107    if (!p->initreq.headers || init > 2)
11108       initialize_initreq(p, &req);
11109    p->lastinvite = p->ocseq;
11110    return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
11111 }
11112 
11113 /*! \brief Send a subscription or resubscription for MWI */
11114 static int sip_subscribe_mwi_do(const void *data)
11115 {
11116    struct sip_subscription_mwi *mwi = (struct sip_subscription_mwi*)data;
11117    
11118    if (!mwi) {
11119       return -1;
11120    }
11121    
11122    mwi->resub = -1;
11123    __sip_subscribe_mwi_do(mwi);
11124    ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
11125    
11126    return 0;
11127 }
11128 
11129 /*! \brief Actually setup an MWI subscription or resubscribe */
11130 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi)
11131 {
11132    /* If we have no DNS manager let's do a lookup */
11133    if (!mwi->dnsmgr) {
11134       char transport[MAXHOSTNAMELEN];
11135       snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(mwi->transport), get_srv_protocol(mwi->transport));
11136       ast_dnsmgr_lookup(mwi->hostname, &mwi->us, &mwi->dnsmgr, sip_cfg.srvlookup ? transport : NULL);
11137    }
11138 
11139    /* If we already have a subscription up simply send a resubscription */
11140    if (mwi->call) {
11141       transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 0);
11142       return 0;
11143    }
11144    
11145    /* Create a dialog that we will use for the subscription */
11146    if (!(mwi->call = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
11147       return -1;
11148    }
11149 
11150    ref_proxy(mwi->call, obproxy_get(mwi->call, NULL));
11151 
11152    if (!mwi->us.sin_port && mwi->portno) {
11153       mwi->us.sin_port = htons(mwi->portno);
11154    }
11155    
11156    /* Setup the destination of our subscription */
11157    if (create_addr(mwi->call, mwi->hostname, &mwi->us, 0)) {
11158       dialog_unlink_all(mwi->call, TRUE, TRUE);
11159       mwi->call = dialog_unref(mwi->call, "unref dialog after unlink_all");
11160       return 0;
11161    }
11162    
11163    if (!mwi->dnsmgr && mwi->portno) {
11164       mwi->call->sa.sin_port = htons(mwi->portno);
11165       mwi->call->recv.sin_port = htons(mwi->portno);
11166    } else {
11167       mwi->portno = ntohs(mwi->call->sa.sin_port);
11168    }
11169    
11170    /* Set various other information */
11171    if (!ast_strlen_zero(mwi->authuser)) {
11172       ast_string_field_set(mwi->call, peername, mwi->authuser);
11173       ast_string_field_set(mwi->call, authname, mwi->authuser);
11174       ast_string_field_set(mwi->call, fromuser, mwi->authuser);
11175    } else {
11176       ast_string_field_set(mwi->call, peername, mwi->username);
11177       ast_string_field_set(mwi->call, authname, mwi->username);
11178       ast_string_field_set(mwi->call, fromuser, mwi->username);
11179    }
11180    ast_string_field_set(mwi->call, username, mwi->username);
11181    if (!ast_strlen_zero(mwi->secret)) {
11182       ast_string_field_set(mwi->call, peersecret, mwi->secret);
11183    }
11184    set_socket_transport(&mwi->call->socket, mwi->transport);
11185    mwi->call->socket.port = htons(mwi->portno);
11186    ast_sip_ouraddrfor(&mwi->call->sa.sin_addr, &mwi->call->ourip, mwi->call);
11187    build_contact(mwi->call);
11188    build_via(mwi->call);
11189    build_callid_pvt(mwi->call);
11190    ast_set_flag(&mwi->call->flags[0], SIP_OUTGOING);
11191    
11192    /* Associate the call with us */
11193    mwi->call->mwi = ASTOBJ_REF(mwi);
11194    
11195    /* Actually send the packet */
11196    transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 2);
11197 
11198    return 0;
11199 }
11200 
11201 static int find_calling_channel(struct ast_channel *c, void *data) {
11202    struct sip_pvt *p = data;
11203 
11204    return (c->pbx &&
11205          (!strcasecmp(c->macroexten, p->exten) || !strcasecmp(c->exten, p->exten)) &&
11206          (sip_cfg.notifycid == IGNORE_CONTEXT || !strcasecmp(c->context, p->context)));
11207 }
11208 
11209 /*! \brief Used in the SUBSCRIBE notification subsystem (RFC3265) */
11210 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
11211 {
11212    struct ast_str *tmp = ast_str_alloca(4000);
11213    char from[256], to[256];
11214    char *c, *mfrom, *mto;
11215    struct sip_request req;
11216    char hint[AST_MAX_EXTENSION];
11217    char *statestring = "terminated";
11218    const struct cfsubscription_types *subscriptiontype;
11219    enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
11220    char *pidfstate = "--";
11221    char *pidfnote= "Ready";
11222    
11223    memset(from, 0, sizeof(from));
11224    memset(to, 0, sizeof(to));
11225 
11226    switch (state) {
11227    case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
11228       statestring = (sip_cfg.notifyringing) ? "early" : "confirmed";
11229       local_state = NOTIFY_INUSE;
11230       pidfstate = "busy";
11231       pidfnote = "Ringing";
11232       break;
11233    case AST_EXTENSION_RINGING:
11234       statestring = "early";
11235       local_state = NOTIFY_INUSE;
11236       pidfstate = "busy";
11237       pidfnote = "Ringing";
11238       break;
11239    case AST_EXTENSION_INUSE:
11240       statestring = "confirmed";
11241       local_state = NOTIFY_INUSE;
11242       pidfstate = "busy";
11243       pidfnote = "On the phone";
11244       break;
11245    case AST_EXTENSION_BUSY:
11246       statestring = "confirmed";
11247       local_state = NOTIFY_CLOSED;
11248       pidfstate = "busy";
11249       pidfnote = "On the phone";
11250       break;
11251    case AST_EXTENSION_UNAVAILABLE:
11252       statestring = "terminated";
11253       local_state = NOTIFY_CLOSED;
11254       pidfstate = "away";
11255       pidfnote = "Unavailable";
11256       break;
11257    case AST_EXTENSION_ONHOLD:
11258       statestring = "confirmed";
11259       local_state = NOTIFY_CLOSED;
11260       pidfstate = "busy";
11261       pidfnote = "On hold";
11262       break;
11263    case AST_EXTENSION_NOT_INUSE:
11264    default:
11265       /* Default setting */
11266       break;
11267    }
11268 
11269    subscriptiontype = find_subscription_type(p->subscribed);
11270    
11271    /* Check which device/devices we are watching  and if they are registered */
11272    if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten)) {
11273       char *hint2 = hint, *individual_hint = NULL;
11274       int hint_count = 0, unavailable_count = 0;
11275 
11276       while ((individual_hint = strsep(&hint2, "&"))) {
11277          hint_count++;
11278 
11279          if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
11280             unavailable_count++;
11281       }
11282 
11283       /* If none of the hinted devices are registered, we will
11284        * override notification and show no availability.
11285        */
11286       if (hint_count > 0 && hint_count == unavailable_count) {
11287          local_state = NOTIFY_CLOSED;
11288          pidfstate = "away";
11289          pidfnote = "Not online";
11290       }
11291    }
11292 
11293    ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
11294    c = get_in_brackets(from);
11295    if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
11296       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
11297       return -1;
11298    }
11299    
11300    mfrom = remove_uri_parameters(c);
11301 
11302    ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
11303    c = get_in_brackets(to);
11304    if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
11305       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
11306       return -1;
11307    }
11308    mto = remove_uri_parameters(c);
11309 
11310    reqprep(&req, p, SIP_NOTIFY, 0, 1);
11311 
11312    
11313    add_header(&req, "Event", subscriptiontype->event);
11314    add_header(&req, "Content-Type", subscriptiontype->mediatype);
11315    switch(state) {
11316    case AST_EXTENSION_DEACTIVATED:
11317       if (timeout)
11318          add_header(&req, "Subscription-State", "terminated;reason=timeout");
11319       else {
11320          add_header(&req, "Subscription-State", "terminated;reason=probation");
11321          add_header(&req, "Retry-After", "60");
11322       }
11323       break;
11324    case AST_EXTENSION_REMOVED:
11325       add_header(&req, "Subscription-State", "terminated;reason=noresource");
11326       break;
11327    default:
11328       if (p->expiry)
11329          add_header(&req, "Subscription-State", "active");
11330       else  /* Expired */
11331          add_header(&req, "Subscription-State", "terminated;reason=timeout");
11332    }
11333    switch (p->subscribed) {
11334    case XPIDF_XML:
11335    case CPIM_PIDF_XML:
11336       ast_str_append(&tmp, 0,
11337          "<?xml version=\"1.0\"?>\n"
11338          "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n"
11339          "<presence>\n");
11340       ast_str_append(&tmp, 0, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
11341       ast_str_append(&tmp, 0, "<atom id=\"%s\">\n", p->exten);
11342       ast_str_append(&tmp, 0, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
11343       ast_str_append(&tmp, 0, "<status status=\"%s\" />\n", (local_state ==  NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
11344       ast_str_append(&tmp, 0, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
11345       ast_str_append(&tmp, 0, "</address>\n</atom>\n</presence>\n");
11346       break;
11347    case PIDF_XML: /* Eyebeam supports this format */
11348       ast_str_append(&tmp, 0,
11349          "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
11350          "<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);
11351       ast_str_append(&tmp, 0, "<pp:person><status>\n");
11352       if (pidfstate[0] != '-')
11353          ast_str_append(&tmp, 0, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
11354       ast_str_append(&tmp, 0, "</status></pp:person>\n");
11355       ast_str_append(&tmp, 0, "<note>%s</note>\n", pidfnote); /* Note */
11356       ast_str_append(&tmp, 0, "<tuple id=\"%s\">\n", p->exten); /* Tuple start */
11357       ast_str_append(&tmp, 0, "<contact priority=\"1\">%s</contact>\n", mto);
11358       if (pidfstate[0] == 'b') /* Busy? Still open ... */
11359          ast_str_append(&tmp, 0, "<status><basic>open</basic></status>\n");
11360       else
11361          ast_str_append(&tmp, 0, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
11362       ast_str_append(&tmp, 0, "</tuple>\n</presence>\n");
11363       break;
11364    case DIALOG_INFO_XML: /* SNOM subscribes in this format */
11365       ast_str_append(&tmp, 0, "<?xml version=\"1.0\"?>\n");
11366       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);
11367       if ((state & AST_EXTENSION_RINGING) && sip_cfg.notifyringing) {
11368          const char *local_display = p->exten;
11369          char *local_target = mto;
11370 
11371          /* There are some limitations to how this works.  The primary one is that the
11372             callee must be dialing the same extension that is being monitored.  Simply dialing
11373             the hint'd device is not sufficient. */
11374          if (sip_cfg.notifycid) {
11375             struct ast_channel *caller = ast_channel_search_locked(find_calling_channel, p);
11376 
11377             if (caller) {
11378                int need = strlen(caller->cid.cid_num) + strlen(p->fromdomain) + sizeof("sip:@");
11379                local_target = alloca(need);
11380                snprintf(local_target, need, "sip:%s@%s", caller->cid.cid_num, p->fromdomain);
11381                if (!(ast_strlen_zero(caller->cid.cid_name))) {
11382                   local_display = ast_strdupa(caller->cid.cid_name);
11383                }
11384                ast_channel_unlock(caller);
11385                caller = NULL;
11386             }
11387             /* We create a fake call-id which the phone will send back in an INVITE
11388              * Replaces header which we can grab and do some magic with. */
11389             if (sip_cfg.pedanticsipchecking) {
11390                ast_str_append(&tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" local-tag=\"%s\" remote-tag=\"%s\" direction=\"recipient\">\n",
11391                   p->exten, p->callid, p->theirtag, p->tag);
11392             } else {
11393                ast_str_append(&tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" direction=\"recipient\">\n",
11394                   p->exten, p->callid);
11395             }
11396             ast_str_append(&tmp, 0, 
11397                   "<remote>\n"
11398                   /* See the limitations of this above.  Luckily the phone seems to still be
11399                      happy when these values are not correct. */
11400                   "<identity display=\"%s\">%s</identity>\n"
11401                   "<target uri=\"%s\"/>\n"
11402                   "</remote>\n"
11403                   "<local>\n"
11404                   "<identity>%s</identity>\n"
11405                   "<target uri=\"%s\"/>\n"
11406                   "</local>\n",
11407                   local_display, local_target, local_target, mto, mto);
11408          } else {
11409             ast_str_append(&tmp, 0, "<dialog id=\"%s\" direction=\"recipient\">\n", p->exten);
11410          }
11411       } else {
11412          ast_str_append(&tmp, 0, "<dialog id=\"%s\">\n", p->exten);
11413       }
11414       ast_str_append(&tmp, 0, "<state>%s</state>\n", statestring);
11415       if (state == AST_EXTENSION_ONHOLD) {
11416          ast_str_append(&tmp, 0, "<local>\n<target uri=\"%s\">\n"
11417                                          "<param pname=\"+sip.rendering\" pvalue=\"no\"/>\n"
11418                                          "</target>\n</local>\n", mto);
11419       }
11420       ast_str_append(&tmp, 0, "</dialog>\n</dialog-info>\n");
11421       break;
11422    case NONE:
11423    default:
11424       break;
11425    }
11426 
11427    add_content(&req, tmp->str);
11428 
11429    p->pendinginvite = p->ocseq;  /* Remember that we have a pending NOTIFY in order not to confuse the NOTIFY subsystem */
11430 
11431    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11432 }
11433 
11434 /*! \brief Notify user of messages waiting in voicemail (RFC3842)
11435 \note - Notification only works for registered peers with mailbox= definitions
11436    in sip.conf
11437    - We use the SIP Event package message-summary
11438     MIME type defaults to  "application/simple-message-summary";
11439  */
11440 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten)
11441 {
11442    struct sip_request req;
11443    struct ast_str *out = ast_str_alloca(500);
11444    int ourport = ntohs(p->ourip.sin_port);
11445    const char *exten = S_OR(vmexten, default_vmexten);
11446 
11447    initreqprep(&req, p, SIP_NOTIFY);
11448    add_header(&req, "Event", "message-summary");
11449    add_header(&req, "Content-Type", default_notifymime);
11450    ast_str_append(&out, 0, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
11451 
11452    if (!ast_strlen_zero(p->fromdomain)) {
11453       ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, p->fromdomain);
11454    } else if (!sip_standard_port(p->socket.type, ourport)) {
11455       if (p->socket.type == SIP_TRANSPORT_UDP) {
11456          ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr), ourport);
11457       } else {
11458          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));
11459       }
11460    } else {
11461       if (p->socket.type == SIP_TRANSPORT_UDP) {
11462          ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr));
11463       } else {
11464          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));
11465       }
11466    }
11467    /* Cisco has a bug in the SIP stack where it can't accept the
11468       (0/0) notification. This can temporarily be disabled in
11469       sip.conf with the "buggymwi" option */
11470    ast_str_append(&out, 0, "Voice-Message: %d/%d%s\r\n",
11471       newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));
11472 
11473    if (p->subscribed) {
11474       if (p->expiry)
11475          add_header(&req, "Subscription-State", "active");
11476       else  /* Expired */
11477          add_header(&req, "Subscription-State", "terminated;reason=timeout");
11478    }
11479 
11480    add_content(&req, out->str);
11481 
11482    if (!p->initreq.headers) 
11483       initialize_initreq(p, &req);
11484    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11485 }
11486 
11487 /*! \brief Notify a transferring party of the status of transfer (RFC3515) */
11488 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
11489 {
11490    struct sip_request req;
11491    char tmp[SIPBUFSIZE/2];
11492    
11493    reqprep(&req, p, SIP_NOTIFY, 0, 1);
11494    snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
11495    add_header(&req, "Event", tmp);
11496    add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
11497    add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
11498    add_header(&req, "Allow", ALLOWED_METHODS);
11499    add_supported_header(p, &req);
11500 
11501    snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
11502    add_content(&req, tmp);
11503 
11504    if (!p->initreq.headers)
11505       initialize_initreq(p, &req);
11506 
11507    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11508 }
11509 
11510 /*! \brief Notify device with custom headers from sip_notify.conf */
11511 static int transmit_notify_custom(struct sip_pvt *p, struct ast_variable *vars) {
11512    struct sip_request req;
11513    struct ast_variable *var, *newvar;
11514 
11515    initreqprep(&req, p, SIP_NOTIFY);
11516 
11517    /* Copy notify vars and add headers */
11518    p->notify_headers = newvar = ast_variable_new("Subscription-State", "terminated", "");
11519    add_header(&req, newvar->name, newvar->value);
11520    for (var = vars; var; var = var->next) {
11521       char buf[512];
11522 
11523       if (!strcasecmp(var->name, "Content-Length")) {
11524          ast_debug(2, "Ignoring pair %s=%s\n", var->name, var->value);
11525          continue; /* ignore content-length, it is calculated automatically */
11526       }
11527 
11528       ast_debug(2, "  Adding pair %s=%s\n", var->name, var->value);
11529       ast_copy_string(buf, var->value, sizeof(buf));
11530       add_header(&req, var->name, ast_unescape_semicolon(buf));
11531       newvar->next = ast_variable_new(var->name, var->value, "");
11532       newvar = newvar->next;
11533    }
11534 
11535    if (!p->initreq.headers) { /* Initialize first request before sending */
11536       initialize_initreq(p, &req);
11537    }
11538 
11539    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11540 }
11541 
11542 static int manager_sipnotify(struct mansession *s, const struct message *m)
11543 {
11544    const char *channame = astman_get_header(m, "Channel");
11545    struct ast_variable *vars = astman_get_variables(m);
11546    struct sip_pvt *p;
11547 
11548    if (ast_strlen_zero(channame)) {
11549       astman_send_error(s, m, "SIPNotify requires a channel name");
11550       return 0;
11551    }
11552 
11553    if (!strncasecmp(channame, "sip/", 4)) {
11554       channame += 4;
11555    }
11556 
11557    if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
11558       astman_send_error(s, m, "Unable to build sip pvt data for notify (memory/socket error)");
11559       return 0;
11560    }
11561 
11562    if (create_addr(p, channame, NULL, 0)) {
11563       /* Maybe they're not registered, etc. */
11564       dialog_unlink_all(p, TRUE, TRUE);
11565       dialog_unref(p, "unref dialog inside for loop" );
11566       /* sip_destroy(p); */
11567       astman_send_error(s, m, "Could not create address");
11568       return 0;
11569    }
11570 
11571    /* Notify is outgoing call */
11572    ast_set_flag(&p->flags[0], SIP_OUTGOING);
11573 
11574    /* Recalculate our side, and recalculate Call ID */
11575    ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
11576    build_via(p);
11577    ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
11578    build_callid_pvt(p);
11579    ao2_t_link(dialogs, p, "Linking in new name");
11580    dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
11581    sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
11582 
11583    if (!transmit_notify_custom(p, vars)) {
11584       astman_send_ack(s, m, "Notify Sent");
11585    } else {
11586       astman_send_error(s, m, "Unable to send notify");
11587    }
11588    ast_variables_destroy(vars);
11589    return 0;
11590 }
11591 
11592 static char mandescr_sipnotify[] =
11593 "Description: Sends a SIP Notify event\n"
11594 "All parameters for this event must be specified in the body of this request\n"
11595 "via multiple Variable: name=value sequences.\n"
11596 "Variables: \n"
11597 "  *Channel: <peername>       Peer to receive the notify. Required.\n"
11598 "  *Variable: <name>=<value>  At least one variable pair must be specified.\n"
11599 "  ActionID: <id>             Action ID for this transaction. Will be returned.\n";
11600 
11601 static const struct _map_x_s regstatestrings[] = {
11602    { REG_STATE_FAILED,     "Failed" },
11603    { REG_STATE_UNREGISTERED, "Unregistered"},
11604    { REG_STATE_REGSENT, "Request Sent"},
11605    { REG_STATE_AUTHSENT, "Auth. Sent"},
11606    { REG_STATE_REGISTERED, "Registered"},
11607    { REG_STATE_REJECTED, "Rejected"},
11608    { REG_STATE_TIMEOUT, "Timeout"},
11609    { REG_STATE_NOAUTH, "No Authentication"},
11610    { -1, NULL } /* terminator */
11611 };
11612 
11613 /*! \brief Convert registration state status to string */
11614 static const char *regstate2str(enum sipregistrystate regstate)
11615 {
11616    return map_x_s(regstatestrings, regstate, "Unknown");
11617 }
11618 
11619 /*! \brief Update registration with SIP Proxy.
11620  * Called from the scheduler when the previous registration expires,
11621  * so we don't have to cancel the pending event.
11622  * We assume the reference so the sip_registry is valid, since it
11623  * is stored in the scheduled event anyways.
11624  */
11625 static int sip_reregister(const void *data) 
11626 {
11627    /* if we are here, we know that we need to reregister. */
11628    struct sip_registry *r= (struct sip_registry *) data;
11629 
11630    /* if we couldn't get a reference to the registry object, punt */
11631    if (!r)
11632       return 0;
11633 
11634    if (r->call && r->call->do_history)
11635       append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
11636    /* Since registry's are only added/removed by the the monitor thread, this
11637       may be overkill to reference/dereference at all here */
11638    if (sipdebug)
11639       ast_log(LOG_NOTICE, "   -- Re-registration for  %s@%s\n", r->username, r->hostname);
11640 
11641    r->expire = -1;
11642    r->expiry = r->configured_expiry;
11643    __sip_do_register(r);
11644    registry_unref(r, "unref the re-register scheduled event");
11645    return 0;
11646 }
11647 
11648 /*! \brief Register with SIP proxy */
11649 static int __sip_do_register(struct sip_registry *r)
11650 {
11651    int res;
11652 
11653    res = transmit_register(r, SIP_REGISTER, NULL, NULL);
11654    return res;
11655 }
11656 
11657 /*! \brief Registration timeout, register again
11658  * Registered as a timeout handler during transmit_register(),
11659  * to retransmit the packet if a reply does not come back.
11660  * This is called by the scheduler so the event is not pending anymore when
11661  * we are called.
11662  */
11663 static int sip_reg_timeout(const void *data)
11664 {
11665 
11666    /* if we are here, our registration timed out, so we'll just do it over */
11667    struct sip_registry *r = (struct sip_registry *)data; /* the ref count should have been bumped when the sched item was added */
11668    struct sip_pvt *p;
11669    int res;
11670 
11671    /* if we couldn't get a reference to the registry object, punt */
11672    if (!r)
11673       return 0;
11674 
11675    if (r->dnsmgr) {
11676       /* If the registration has timed out, maybe the IP changed.  Force a refresh. */
11677       ast_dnsmgr_refresh(r->dnsmgr);
11678    }
11679 
11680    ast_log(LOG_NOTICE, "   -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts); 
11681    /* If the initial tranmission failed, we may not have an existing dialog,
11682     * so it is possible that r->call == NULL.
11683     * Otherwise destroy it, as we have a timeout so we don't want it.
11684     */
11685    if (r->call) {
11686       /* Unlink us, destroy old call.  Locking is not relevant here because all this happens
11687          in the single SIP manager thread. */
11688       p = r->call;
11689       sip_pvt_lock(p);
11690       pvt_set_needdestroy(p, "registration timeout");
11691       /* Pretend to ACK anything just in case */
11692       __sip_pretend_ack(p);
11693       sip_pvt_unlock(p);
11694 
11695       /* decouple the two objects */
11696       /* p->registry == r, so r has 2 refs, and the unref won't take the object away */
11697       if (p->registry)
11698          p->registry = registry_unref(p->registry, "p->registry unreffed");
11699       r->call = dialog_unref(r->call, "unrefing r->call");
11700    }
11701    /* If we have a limit, stop registration and give up */
11702    r->timeout = -1;
11703    if (global_regattempts_max && r->regattempts > global_regattempts_max) {
11704       /* Ok, enough is enough. Don't try any more */
11705       /* We could add an external notification here... 
11706          steal it from app_voicemail :-) */
11707       ast_log(LOG_NOTICE, "   -- Giving up forever trying to register '%s@%s'\n", r->username, r->hostname);
11708       r->regstate = REG_STATE_FAILED;
11709    } else {
11710       r->regstate = REG_STATE_UNREGISTERED;
11711       res=transmit_register(r, SIP_REGISTER, NULL, NULL);
11712    }
11713    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));
11714    registry_unref(r, "unreffing registry_unref r");
11715    return 0;
11716 }
11717 
11718 /*! \brief Transmit register to SIP proxy or UA
11719  * auth = NULL on the initial registration (from sip_reregister())
11720  */
11721 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
11722 {
11723    struct sip_request req;
11724    char from[256];
11725    char to[256];
11726    char tmp[80];
11727    char addr[80];
11728    struct sip_pvt *p;
11729    struct sip_peer *peer = NULL;
11730    int res;
11731    char *fromdomain;
11732    char *domainport = NULL;
11733 
11734    /* exit if we are already in process with this registrar ?*/
11735    if (r == NULL || ((auth == NULL) && (r->regstate == REG_STATE_REGSENT || r->regstate == REG_STATE_AUTHSENT))) {
11736       if (r) {
11737          ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
11738       }
11739       return 0;
11740    }
11741 
11742    if (r->dnsmgr == NULL) {
11743       char transport[MAXHOSTNAMELEN];
11744       peer = find_peer(r->hostname, NULL, TRUE, FINDPEERS, FALSE, 0);
11745       snprintf(transport, sizeof(transport), "_%s._%s",get_srv_service(r->transport), get_srv_protocol(r->transport)); /* have to use static get_transport function */
11746       ast_dnsmgr_lookup(peer ? peer->tohost : r->hostname, &r->us, &r->dnsmgr, sip_cfg.srvlookup ? transport : NULL);
11747       if (peer) {
11748          peer = unref_peer(peer, "removing peer ref for dnsmgr_lookup");
11749       }
11750    }
11751 
11752    if (r->call) { /* We have a registration */
11753       if (!auth) {
11754          ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
11755          return 0;
11756       } else {
11757          p = dialog_ref(r->call, "getting a copy of the r->call dialog in transmit_register");
11758          make_our_tag(p->tag, sizeof(p->tag));  /* create a new local tag for every register attempt */
11759          ast_string_field_set(p, theirtag, NULL);  /* forget their old tag, so we don't match tags when getting response */
11760       }
11761    } else {
11762       /* Build callid for registration if we haven't registered before */
11763       if (!r->callid_valid) {
11764          build_callid_registry(r, internip.sin_addr, default_fromdomain);
11765          r->callid_valid = TRUE;
11766       }
11767       /* Allocate SIP dialog for registration */
11768       if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER, NULL))) {
11769          ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
11770          return 0;
11771       }
11772       
11773       if (p->do_history)
11774          append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
11775 
11776       /* Use port number specified if no SRV record was found */
11777       if (!r->us.sin_port && r->portno)
11778          r->us.sin_port = htons(r->portno);
11779 
11780       /* Find address to hostname */
11781       if (create_addr(p, S_OR(r->peername, r->hostname), &r->us, 0)) {
11782          /* we have what we hope is a temporary network error,
11783           * probably DNS.  We need to reschedule a registration try */
11784          dialog_unlink_all(p, TRUE, TRUE);
11785          p = dialog_unref(p, "unref dialog after unlink_all");
11786          if (r->timeout > -1) {
11787             AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
11788                               registry_unref(_data, "del for REPLACE of registry ptr"), 
11789                               registry_unref(r, "object ptr dec when SCHED_REPLACE add failed"),
11790                               registry_addref(r,"add for REPLACE registry ptr"));
11791             ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
11792          } else {
11793             r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, registry_addref(r, "add for REPLACE registry ptr"));
11794             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);
11795          }
11796          r->regattempts++;
11797          return 0;
11798       }
11799 
11800       /* Copy back Call-ID in case create_addr changed it */
11801       ast_string_field_set(r, callid, p->callid);
11802       if (!r->dnsmgr && r->portno) {
11803          p->sa.sin_port = htons(r->portno);
11804          p->recv.sin_port = htons(r->portno);
11805       } else { /* Set registry port to the port set from the peer definition/srv or default */
11806          r->portno = ntohs(p->sa.sin_port);
11807       }
11808       ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Registration is outgoing call */
11809       r->call = dialog_ref(p, "copying dialog into registry r->call");     /* Save pointer to SIP dialog */
11810       p->registry = registry_addref(r, "transmit_register: addref to p->registry in transmit_register"); /* Add pointer to registry in packet */
11811       if (!ast_strlen_zero(r->secret)) {  /* Secret (password) */
11812          ast_string_field_set(p, peersecret, r->secret);
11813       }
11814       if (!ast_strlen_zero(r->md5secret))
11815          ast_string_field_set(p, peermd5secret, r->md5secret);
11816       /* User name in this realm  
11817       - if authuser is set, use that, otherwise use username */
11818       if (!ast_strlen_zero(r->authuser)) {   
11819          ast_string_field_set(p, peername, r->authuser);
11820          ast_string_field_set(p, authname, r->authuser);
11821       } else if (!ast_strlen_zero(r->username)) {
11822          ast_string_field_set(p, peername, r->username);
11823          ast_string_field_set(p, authname, r->username);
11824          ast_string_field_set(p, fromuser, r->username);
11825       }
11826       if (!ast_strlen_zero(r->username))
11827          ast_string_field_set(p, username, r->username);
11828       /* Save extension in packet */
11829       if (!ast_strlen_zero(r->callback))
11830          ast_string_field_set(p, exten, r->callback);
11831 
11832       /* Set transport and port so the correct contact is built */
11833       set_socket_transport(&p->socket, r->transport);
11834       if (r->transport == SIP_TRANSPORT_TLS || r->transport == SIP_TRANSPORT_TCP) {
11835          p->socket.port = sip_tcp_desc.local_address.sin_port;
11836       }
11837 
11838       /*
11839         check which address we should use in our contact header 
11840         based on whether the remote host is on the external or
11841         internal network so we can register through nat
11842        */
11843       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
11844       build_contact(p);
11845    }
11846 
11847    /* set up a timeout */
11848    if (auth == NULL)  {
11849       if (r->timeout > -1)
11850          ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
11851       AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
11852                         registry_unref(_data,"reg ptr unrefed from del in SCHED_REPLACE"),
11853                         registry_unref(r,"reg ptr unrefed from add failure in SCHED_REPLACE"),
11854                         registry_addref(r,"reg ptr reffed from add in SCHED_REPLACE"));
11855       ast_debug(1, "Scheduled a registration timeout for %s id  #%d \n", r->hostname, r->timeout);
11856    }
11857 
11858    if ((fromdomain = strchr(r->username, '@'))) {
11859       /* the domain name is just behind '@' */
11860       fromdomain++ ;
11861       /* We have a domain in the username for registration */
11862       snprintf(from, sizeof(from), "<sip:%s>;tag=%s", r->username, p->tag);
11863       if (!ast_strlen_zero(p->theirtag))
11864          snprintf(to, sizeof(to), "<sip:%s>;tag=%s", r->username, p->theirtag);
11865       else
11866          snprintf(to, sizeof(to), "<sip:%s>", r->username);
11867 
11868       /* If the registration username contains '@', then the domain should be used as
11869          the equivalent of "fromdomain" for the registration */
11870       if (ast_strlen_zero(p->fromdomain)) {
11871          ast_string_field_set(p, fromdomain, fromdomain);
11872       }
11873    } else {
11874       snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->tag);
11875       if (!ast_strlen_zero(p->theirtag))
11876          snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->theirtag);
11877       else
11878          snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, p->tohost);
11879    }
11880    
11881    /* Fromdomain is what we are registering to, regardless of actual
11882       host name from SRV */
11883    if (!ast_strlen_zero(p->fromdomain)) {
11884       domainport = strrchr(p->fromdomain, ':');
11885       if (domainport) {
11886          *domainport++ = '\0'; /* trim off domainport from p->fromdomain */
11887          if (ast_strlen_zero(domainport))
11888             domainport = NULL;
11889       }     
11890       if (domainport) {       
11891          if (atoi(domainport) != STANDARD_SIP_PORT)
11892             snprintf(addr, sizeof(addr), "sip:%s:%s", p->fromdomain, domainport);
11893          else
11894             snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
11895       } else {
11896          if (r->portno && r->portno != STANDARD_SIP_PORT)
11897             snprintf(addr, sizeof(addr), "sip:%s:%d", p->fromdomain, r->portno);
11898          else
11899             snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
11900       }
11901    } else {
11902       if (r->portno && r->portno != STANDARD_SIP_PORT)
11903          snprintf(addr, sizeof(addr), "sip:%s:%d", r->hostname, r->portno);
11904       else
11905          snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
11906    }
11907    ast_string_field_set(p, uri, addr);
11908 
11909    p->branch ^= ast_random();
11910 
11911    init_req(&req, sipmethod, addr);
11912 
11913    /* Add to CSEQ */
11914    snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
11915    p->ocseq = r->ocseq;
11916 
11917    build_via(p);
11918    add_header(&req, "Via", p->via);
11919    add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
11920    add_header(&req, "From", from);
11921    add_header(&req, "To", to);
11922    add_header(&req, "Call-ID", p->callid);
11923    add_header(&req, "CSeq", tmp);
11924    if (!ast_strlen_zero(global_useragent))
11925       add_header(&req, "User-Agent", global_useragent);
11926 
11927    
11928    if (auth)   /* Add auth header */
11929       add_header(&req, authheader, auth);
11930    else if (!ast_strlen_zero(r->nonce)) {
11931       char digest[1024];
11932 
11933       /* We have auth data to reuse, build a digest header.
11934        * Note, this is not always useful because some parties do not
11935        * like nonces to be reused (for good reasons!) so they will
11936        * challenge us anyways.
11937        */
11938       if (sipdebug)
11939          ast_debug(1, "   >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
11940       ast_string_field_set(p, realm, r->realm);
11941       ast_string_field_set(p, nonce, r->nonce);
11942       ast_string_field_set(p, domain, r->domain);
11943       ast_string_field_set(p, opaque, r->opaque);
11944       ast_string_field_set(p, qop, r->qop);
11945       p->noncecount = ++r->noncecount;
11946 
11947       memset(digest, 0, sizeof(digest));
11948       if(!build_reply_digest(p, sipmethod, digest, sizeof(digest)))
11949          add_header(&req, "Authorization", digest);
11950       else
11951          ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
11952    
11953    }
11954 
11955    snprintf(tmp, sizeof(tmp), "%d", r->expiry);
11956    add_header(&req, "Expires", tmp);
11957    add_header(&req, "Contact", p->our_contact);
11958 
11959    initialize_initreq(p, &req);
11960    if (sip_debug_test_pvt(p)) {
11961       ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
11962    }
11963    r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
11964    r->regattempts++; /* Another attempt */
11965    ast_debug(4, "REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
11966    res = send_request(p, &req, XMIT_CRITICAL, p->ocseq);
11967    dialog_unref(p, "p is finished here at the end of transmit_register");
11968    return res;
11969 }
11970 
11971 /*! \brief Transmit text with SIP MESSAGE method */
11972 static int transmit_message_with_text(struct sip_pvt *p, const char *text)
11973 {
11974    struct sip_request req;
11975    
11976    reqprep(&req, p, SIP_MESSAGE, 0, 1);
11977    add_text(&req, text);
11978    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11979 }
11980 
11981 /*! \brief Allocate SIP refer structure */
11982 static int sip_refer_allocate(struct sip_pvt *p)
11983 {
11984    p->refer = ast_calloc(1, sizeof(struct sip_refer)); 
11985    return p->refer ? 1 : 0;
11986 }
11987 
11988 /*! \brief Transmit SIP REFER message (initiated by the transfer() dialplan application
11989    \note this is currently broken as we have no way of telling the dialplan
11990    engine whether a transfer succeeds or fails.
11991    \todo Fix the transfer() dialplan function so that a transfer may fail
11992 */
11993 static int transmit_refer(struct sip_pvt *p, const char *dest)
11994 {
11995    struct sip_request req = { 
11996       .headers = 0,  
11997    };
11998    char from[256];
11999    const char *of;
12000    char *c;
12001    char referto[256];
12002    char *ttag, *ftag;
12003    char *theirtag = ast_strdupa(p->theirtag);
12004    int   use_tls=FALSE;
12005 
12006    if (sipdebug)
12007       ast_debug(1, "SIP transfer of %s to %s\n", p->callid, dest);
12008 
12009    /* Are we transfering an inbound or outbound call ? */
12010    if (ast_test_flag(&p->flags[0], SIP_OUTGOING))  {
12011       of = get_header(&p->initreq, "To");
12012       ttag = theirtag;
12013       ftag = p->tag;
12014    } else {
12015       of = get_header(&p->initreq, "From");
12016       ftag = theirtag;
12017       ttag = p->tag;
12018    }
12019 
12020    ast_copy_string(from, of, sizeof(from));
12021    of = get_in_brackets(from);
12022    ast_string_field_set(p, from, of);
12023    if (!strncasecmp(of, "sip:", 4)) {
12024       of += 4;
12025    }else if (!strncasecmp(of, "sips:", 5)) {
12026       of += 5;
12027       use_tls = TRUE;
12028    } else {
12029       ast_log(LOG_NOTICE, "From address missing 'sip(s):', assuming sip:\n");
12030    }
12031    /* Get just the username part */
12032    if ((c = strchr(dest, '@')))
12033       c = NULL;
12034    else if ((c = strchr(of, '@')))
12035       *c++ = '\0';
12036    if (c) 
12037       snprintf(referto, sizeof(referto), "<sip%s:%s@%s>", use_tls ? "s" : "", dest, c);
12038    else
12039       snprintf(referto, sizeof(referto), "<sip%s:%s>", use_tls ? "s" : "", dest);
12040 
12041    /* save in case we get 407 challenge */
12042    sip_refer_allocate(p);
12043    ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
12044    ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
12045    p->refer->status = REFER_SENT;   /* Set refer status */
12046 
12047    reqprep(&req, p, SIP_REFER, 0, 1);
12048 
12049    add_header(&req, "Refer-To", referto);
12050    add_header(&req, "Allow", ALLOWED_METHODS);
12051    add_supported_header(p, &req);
12052    if (!ast_strlen_zero(p->our_contact))
12053       add_header(&req, "Referred-By", p->our_contact);
12054 
12055    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12056 
12057    /* We should propably wait for a NOTIFY here until we ack the transfer */
12058    /* Maybe fork a new thread and wait for a STATUS of REFER_200OK on the refer status before returning to app_transfer */
12059 
12060    /*! \todo In theory, we should hang around and wait for a reply, before
12061    returning to the dial plan here. Don't know really how that would
12062    affect the transfer() app or the pbx, but, well, to make this
12063    useful we should have a STATUS code on transfer().
12064    */
12065 }
12066 
12067 
12068 /*! \brief Send SIP INFO dtmf message, see Cisco documentation on cisco.com */
12069 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
12070 {
12071    struct sip_request req;
12072    
12073    reqprep(&req, p, SIP_INFO, 0, 1);
12074    add_digit(&req, digit, duration, (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO));
12075    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12076 }
12077 
12078 /*! \brief Send SIP INFO with video update request */
12079 static int transmit_info_with_vidupdate(struct sip_pvt *p)
12080 {
12081    struct sip_request req;
12082    
12083    reqprep(&req, p, SIP_INFO, 0, 1);
12084    add_vidupdate(&req);
12085    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12086 }
12087 
12088 /*! \brief Transmit generic SIP request 
12089    returns XMIT_ERROR if transmit failed with a critical error (don't retry)
12090 */
12091 static int transmit_request(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
12092 {
12093    struct sip_request resp;
12094    
12095    if (sipmethod == SIP_ACK)
12096       p->invitestate = INV_CONFIRMED;
12097 
12098    reqprep(&resp, p, sipmethod, seqno, newbranch);
12099    if (sipmethod == SIP_CANCEL && p->answered_elsewhere) 
12100       add_header(&resp, "Reason", "SIP;cause=200;text=\"Call completed elsewhere\"");
12101 
12102    return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
12103 }
12104 
12105 /*! \brief return the request and response heade for a 401 or 407 code */
12106 static void auth_headers(enum sip_auth_type code, char **header, char **respheader)
12107 {
12108    if (code == WWW_AUTH) {       /* 401 */
12109       *header = "WWW-Authenticate";
12110       *respheader = "Authorization";
12111    } else if (code == PROXY_AUTH) { /* 407 */
12112       *header = "Proxy-Authenticate";
12113       *respheader = "Proxy-Authorization";
12114    } else {
12115       ast_verbose("-- wrong response code %d\n", code);
12116       *header = *respheader = "Invalid";
12117    }
12118 }
12119 
12120 /*! \brief Transmit SIP request, auth added */
12121 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
12122 {
12123    struct sip_request resp;
12124    
12125    reqprep(&resp, p, sipmethod, seqno, newbranch);
12126    if (!ast_strlen_zero(p->realm)) {
12127       char digest[1024];
12128 
12129       memset(digest, 0, sizeof(digest));
12130       if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
12131          char *dummy, *response;
12132          enum sip_auth_type code = p->options ? p->options->auth_type : PROXY_AUTH; /* XXX force 407 if unknown */
12133          auth_headers(code, &dummy, &response);
12134          add_header(&resp, response, digest);
12135       } else
12136          ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
12137    }
12138    /* If we are hanging up and know a cause for that, send it in clear text to make
12139       debugging easier. */
12140    if (sipmethod == SIP_BYE)  {
12141       char buf[10];
12142 
12143       add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->hangupcause));
12144       snprintf(buf, sizeof(buf), "%d", p->hangupcause);
12145       add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
12146    }
12147 
12148    return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);   
12149 }
12150 
12151 /*! \brief Remove registration data from realtime database or AST/DB when registration expires */
12152 static void destroy_association(struct sip_peer *peer)
12153 {
12154    int realtimeregs = ast_check_realtime("sipregs");
12155    char *tablename = (realtimeregs) ? "sipregs" : "sippeers";
12156 
12157    if (!sip_cfg.ignore_regexpire) {
12158       if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
12159          ast_update_realtime(tablename, "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", "regserver", "", "useragent", "", "lastms", "", SENTINEL);
12160       } else {
12161          ast_db_del("SIP/Registry", peer->name);
12162       }
12163    }
12164 }
12165 
12166 static void set_socket_transport(struct sip_socket *socket, int transport)
12167 {
12168    /* if the transport type changes, clear all socket data */
12169    if (socket->type != transport) {
12170       socket->fd = -1;
12171       socket->type = transport;
12172       if (socket->tcptls_session) {
12173          ao2_ref(socket->tcptls_session, -1);
12174          socket->tcptls_session = NULL;
12175       }
12176    }
12177 }
12178 
12179 /*! \brief Expire registration of SIP peer */
12180 static int expire_register(const void *data)
12181 {
12182    struct sip_peer *peer = (struct sip_peer *)data;
12183 
12184    if (!peer)     /* Hmmm. We have no peer. Weird. */
12185       return 0;
12186 
12187    peer->expire = -1;
12188    peer->portinuri = 0;
12189 
12190    destroy_association(peer); /* remove registration data from storage */
12191    set_socket_transport(&peer->socket, peer->default_outbound_transport);
12192 
12193    if (peer->socket.tcptls_session) {
12194       ao2_ref(peer->socket.tcptls_session, -1);
12195       peer->socket.tcptls_session = NULL;
12196    }
12197 
12198    manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
12199    register_peer_exten(peer, FALSE);   /* Remove regexten */
12200    ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
12201 
12202    /* Do we need to release this peer from memory? 
12203       Only for realtime peers and autocreated peers
12204    */
12205    if (peer->is_realtime)
12206       ast_debug(3, "-REALTIME- peer expired registration. Name: %s. Realtime peer objects now %d\n", peer->name, rpeerobjs);
12207 
12208    if (peer->selfdestruct ||
12209        ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
12210       unlink_peer_from_tables(peer);
12211    }
12212 
12213    /* Only clear the addr after we check for destruction.  The addr must remain
12214     * in order to unlink from the peers_by_ip container correctly */
12215    memset(&peer->addr, 0, sizeof(peer->addr));
12216 
12217    unref_peer(peer, "removing peer ref for expire_register");
12218 
12219    return 0;
12220 }
12221 
12222 /*! \brief Poke peer (send qualify to check if peer is alive and well) */
12223 static int sip_poke_peer_s(const void *data)
12224 {
12225    struct sip_peer *peer = (struct sip_peer *)data;
12226    struct sip_peer *foundpeer;
12227 
12228    peer->pokeexpire = -1;
12229 
12230    foundpeer = ao2_find(peers, peer, OBJ_POINTER);
12231    if (!foundpeer) {
12232       unref_peer(peer, "removing poke peer ref");
12233       return 0;
12234    } else if (foundpeer->name != peer->name) {
12235       unref_peer(foundpeer, "removing above peer ref");
12236       unref_peer(peer, "removing poke peer ref");
12237       return 0;
12238    }
12239 
12240    unref_peer(foundpeer, "removing above peer ref");
12241    sip_poke_peer(peer, 0);
12242    unref_peer(peer, "removing poke peer ref");
12243 
12244    return 0;
12245 }
12246 
12247 /*! \brief Get registration details from Asterisk DB */
12248 static void reg_source_db(struct sip_peer *peer)
12249 {
12250    char data[256];
12251    struct in_addr in;
12252    int expire;
12253    int port;
12254    char *scan, *addr, *port_str, *expiry_str, *username, *contact;
12255 
12256    if (peer->rt_fromcontact) 
12257       return;
12258    if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data)))
12259       return;
12260 
12261    scan = data;
12262    addr = strsep(&scan, ":");
12263    port_str = strsep(&scan, ":");
12264    expiry_str = strsep(&scan, ":");
12265    username = strsep(&scan, ":");
12266    contact = scan;   /* Contact include sip: and has to be the last part of the database entry as long as we use : as a separator */
12267 
12268    if (!inet_aton(addr, &in))
12269       return;
12270 
12271    if (port_str)
12272       port = atoi(port_str);
12273    else
12274       return;
12275 
12276    if (expiry_str)
12277       expire = atoi(expiry_str);
12278    else
12279       return;
12280 
12281    if (username)
12282       ast_string_field_set(peer, username, username);
12283    if (contact)
12284       ast_string_field_set(peer, fullcontact, contact);
12285 
12286    ast_debug(2, "SIP Seeding peer from astdb: '%s' at %s@%s:%d for %d\n",
12287        peer->name, peer->username, ast_inet_ntoa(in), port, expire);
12288 
12289    memset(&peer->addr, 0, sizeof(peer->addr));
12290    peer->addr.sin_family = AF_INET;
12291    peer->addr.sin_addr = in;
12292    peer->addr.sin_port = htons(port);
12293    if (sipsock < 0) {
12294       /* SIP isn't up yet, so schedule a poke only, pretty soon */
12295       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ast_random() % 5000 + 1, sip_poke_peer_s, peer,
12296             unref_peer(_data, "removing poke peer ref"),
12297             unref_peer(peer, "removing poke peer ref"),
12298             ref_peer(peer, "adding poke peer ref"));
12299    } else {
12300       sip_poke_peer(peer, 0);
12301    }
12302    AST_SCHED_REPLACE_UNREF(peer->expire, sched, (expire + 10) * 1000, expire_register, peer,
12303          unref_peer(_data, "remove registration ref"),
12304          unref_peer(peer, "remove registration ref"),
12305          ref_peer(peer, "add registration ref"));
12306    register_peer_exten(peer, TRUE);
12307 }
12308 
12309 /*! \brief Save contact header for 200 OK on INVITE */
12310 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
12311 {
12312    char contact[SIPBUFSIZE]; 
12313    char *c;
12314 
12315    /* Look for brackets */
12316    ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
12317    c = get_in_brackets(contact);
12318 
12319    /* Save full contact to call pvt for later bye or re-invite */
12320    ast_string_field_set(pvt, fullcontact, c);
12321 
12322    /* Save URI for later ACKs, BYE or RE-invites */
12323    ast_string_field_set(pvt, okcontacturi, c);
12324 
12325    /* We should return false for URI:s we can't handle,
12326       like tel:, mailto:,ldap: etc */
12327    return TRUE;      
12328 }
12329 
12330 static int __set_address_from_contact(const char *fullcontact, struct sockaddr_in *sin, int tcp)
12331 {
12332    struct hostent *hp;
12333    struct ast_hostent ahp;
12334    int port = STANDARD_SIP_PORT;
12335    char *host, *pt, *transport;
12336    char contact_buf[256];
12337    char *contact;
12338 
12339    /* Work on a copy */
12340    ast_copy_string(contact_buf, fullcontact, sizeof(contact_buf));
12341    contact = contact_buf;
12342 
12343    /* 
12344     * We have only the part in <brackets> here so we just need to parse a SIP URI.
12345     *
12346     * Note: The outbound proxy could be using UDP between the proxy and Asterisk.
12347     * We still need to be able to send to the remote agent through the proxy.
12348     */
12349 
12350    if (parse_uri(contact, "sip:,sips:", &contact, NULL, &host, &pt, NULL, &transport)) {
12351       ast_log(LOG_WARNING, "Invalid contact uri %s (missing sip: or sips:), attempting to use anyway\n", fullcontact);
12352    }
12353 
12354    /* set port */
12355    if (((get_transport_str2enum(transport) == SIP_TRANSPORT_TLS)) || !(strncasecmp(fullcontact, "sips", 4))) {
12356       port = port_str2int(pt, STANDARD_TLS_PORT);
12357    } else {
12358       port = port_str2int(pt, STANDARD_SIP_PORT);
12359    }
12360 
12361 
12362    /* XXX This could block for a long time XXX */
12363    /* We should only do this if it's a name, not an IP */
12364    /* \todo - if there's no PORT number in contact - we are required to check NAPTR/SRV records
12365       to find transport, port address and hostname. If there's a port number, we have to
12366       assume that the domain part is a host name and only look for an A/AAAA record in DNS.
12367    */
12368    hp = ast_gethostbyname(host, &ahp);
12369    if (!hp)  {
12370       ast_log(LOG_WARNING, "Invalid host name in Contact: (can't resolve in DNS) : '%s'\n", host);
12371       return -1;
12372    }
12373    sin->sin_family = AF_INET;
12374    memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
12375    sin->sin_port = htons(port);
12376 
12377    return 0;
12378 }
12379 
12380 /*! \brief Change the other partys IP address based on given contact */
12381 static int set_address_from_contact(struct sip_pvt *pvt)
12382 {
12383    if (ast_test_flag(&pvt->flags[0], SIP_NAT_ROUTE)) {
12384       /* NAT: Don't trust the contact field.  Just use what they came to us
12385          with. */
12386       /*! \todo We need to save the TRANSPORT here too */
12387       pvt->sa = pvt->recv;
12388       return 0;
12389    }
12390 
12391    return __set_address_from_contact(pvt->fullcontact, &pvt->sa, pvt->socket.type == SIP_TRANSPORT_TLS ? 1 : 0);
12392 }
12393 
12394 /*! \brief Parse contact header and save registration (peer registration) */
12395 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
12396 {
12397    char contact[SIPBUFSIZE];
12398    char data[SIPBUFSIZE];
12399    const char *expires = get_header(req, "Expires");
12400    int expire = atoi(expires);
12401    char *curi, *host, *pt, *transport;
12402    int port;
12403    int transport_type;
12404    const char *useragent;
12405    struct hostent *hp;
12406    struct ast_hostent ahp;
12407    struct sockaddr_in oldsin, testsin;
12408    char *firstcuri = NULL;
12409    int start = 0;
12410    int wildcard_found = 0;
12411    int single_binding_found;
12412 
12413    ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
12414 
12415    if (ast_strlen_zero(expires)) {  /* No expires header, try look in Contact: */
12416       char *s = strcasestr(contact, ";expires=");
12417       if (s) {
12418          expires = strsep(&s, ";"); /* trim ; and beyond */
12419          if (sscanf(expires + 9, "%30d", &expire) != 1)
12420             expire = default_expiry;
12421       } else {
12422          /* Nothing has been specified */
12423          expire = default_expiry;
12424       }
12425    }
12426 
12427    copy_socket_data(&pvt->socket, &req->socket);
12428 
12429    do {
12430       /* Look for brackets */
12431       curi = contact;
12432       if (strchr(contact, '<') == NULL)   /* No <, check for ; and strip it */
12433          strsep(&curi, ";");  /* This is Header options, not URI options */
12434       curi = get_in_brackets(contact);
12435       if (!firstcuri) {
12436          firstcuri = ast_strdupa(curi);
12437       }
12438 
12439       if (!strcasecmp(curi, "*")) {
12440          wildcard_found = 1;
12441       } else {
12442          single_binding_found = 1;
12443       }
12444 
12445       if (wildcard_found && (ast_strlen_zero(expires) || expire != 0 || single_binding_found)) {
12446          /* Contact header parameter "*" detected, so punt if: Expires header is missing,
12447           * Expires value is not zero, or another Contact header is present. */
12448          return PARSE_REGISTER_FAILED;
12449       }
12450 
12451       ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
12452    } while (!ast_strlen_zero(contact));
12453    curi = firstcuri;
12454 
12455    /* if they did not specify Contact: or Expires:, they are querying
12456       what we currently have stored as their contact address, so return
12457       it
12458    */
12459    if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
12460       /* If we have an active registration, tell them when the registration is going to expire */
12461       if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact))
12462          pvt->expiry = ast_sched_when(sched, peer->expire);
12463       return PARSE_REGISTER_QUERY;
12464    } else if (!strcasecmp(curi, "*") || !expire) { /* Unregister this peer */
12465       /* This means remove all registrations and return OK */
12466       memset(&peer->addr, 0, sizeof(peer->addr));
12467       set_socket_transport(&peer->socket, peer->default_outbound_transport);
12468 
12469       AST_SCHED_DEL_UNREF(sched, peer->expire,
12470             unref_peer(peer, "remove register expire ref"));
12471 
12472       destroy_association(peer);
12473 
12474       register_peer_exten(peer, FALSE);   /* Remove extension from regexten= setting in sip.conf */
12475       ast_string_field_set(peer, fullcontact, "");
12476       ast_string_field_set(peer, useragent, "");
12477       peer->sipoptions = 0;
12478       peer->lastms = 0;
12479       peer->portinuri = 0;
12480       pvt->expiry = 0;
12481 
12482       ast_verb(3, "Unregistered SIP '%s'\n", peer->name);
12483 
12484       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\n", peer->name);
12485       return PARSE_REGISTER_UPDATE;
12486    }
12487 
12488    /* Store whatever we got as a contact from the client */
12489    ast_string_field_set(peer, fullcontact, curi);
12490 
12491    /* For the 200 OK, we should use the received contact */
12492    ast_string_field_build(pvt, our_contact, "<%s>", curi);
12493 
12494    /* Make sure it's a SIP URL */
12495    if (parse_uri(curi, "sip:,sips:", &curi, NULL, &host, &pt, NULL, &transport)) {
12496       ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:) trying to use anyway\n");
12497    }
12498 
12499    /* If we have a port number in the given URI, make sure we do remember to not check for NAPTR/SRV records. 
12500       The domain part is actually a host. */
12501    peer->portinuri = !ast_strlen_zero(pt) ? TRUE : FALSE;
12502 
12503    /* handle the transport type specified in Contact header. */
12504    if ((transport_type = get_transport_str2enum(transport))) {
12505       /* if the port is not specified but the transport is, make sure to set the
12506        * default port to match the specified transport.  This may or may not be the
12507        * same transport used by the pvt struct for the Register dialog. */
12508       
12509       port = port_str2int(pt, (transport_type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
12510    } else {
12511       port = port_str2int(pt, STANDARD_SIP_PORT);
12512       transport_type = pvt->socket.type;
12513    }
12514 
12515    /* if the peer's socket type is different than the Registration
12516     * transport type, change it.  If it got this far, it is a
12517     * supported type, but check just in case */
12518    if ((peer->socket.type != transport_type) && (peer->transports & transport_type)) {
12519       set_socket_transport(&peer->socket, transport_type);
12520    }
12521 
12522    oldsin = peer->addr;
12523 
12524    /* If we were already linked into the peers_by_ip container unlink ourselves so nobody can find us */
12525    if (peer->addr.sin_addr.s_addr) {
12526       ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
12527    }
12528 
12529    if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE)) {
12530       /* use the data provided in the Contact header for call routing */
12531       ast_debug(1, "Store REGISTER's Contact header for call routing.\n");
12532       /* XXX This could block for a long time XXX */
12533       /*! \todo Check NAPTR/SRV if we have not got a port in the URI */
12534       hp = ast_gethostbyname(host, &ahp);
12535       if (!hp)  {
12536          ast_log(LOG_WARNING, "Invalid host '%s'\n", host);
12537          ast_string_field_set(peer, fullcontact, "");
12538          ast_string_field_set(pvt, our_contact, "");
12539          return PARSE_REGISTER_FAILED;
12540       }
12541       peer->addr.sin_family = AF_INET;
12542       memcpy(&peer->addr.sin_addr, hp->h_addr, sizeof(peer->addr.sin_addr));
12543       peer->addr.sin_port = htons(port);
12544    } else {
12545       /* Don't trust the contact field.  Just use what they came to us
12546          with */
12547       ast_debug(1, "Store REGISTER's src-IP:port for call routing.\n");
12548       peer->addr = pvt->recv;
12549    }
12550 
12551    /* Check that they're allowed to register at this IP */
12552    memcpy(&testsin.sin_addr, &peer->addr.sin_addr, sizeof(testsin.sin_addr));
12553    if (ast_apply_ha(global_contact_ha, &testsin) != AST_SENSE_ALLOW ||
12554          ast_apply_ha(peer->contactha, &testsin) != AST_SENSE_ALLOW) {
12555       ast_log(LOG_WARNING, "Host '%s' disallowed by contact ACL (violating IP %s)\n", host, ast_inet_ntoa(testsin.sin_addr));
12556       ast_string_field_set(peer, fullcontact, "");
12557       ast_string_field_set(pvt, our_contact, "");
12558       return PARSE_REGISTER_DENIED;
12559    }
12560 
12561    /* if the Contact header information copied into peer->addr matches the
12562     * received address, and the transport types are the same, then copy socket
12563     * data into the peer struct */
12564    if ((peer->socket.type == pvt->socket.type) &&
12565       (peer->addr.sin_addr.s_addr == pvt->recv.sin_addr.s_addr) &&
12566       (peer->addr.sin_port == pvt->recv.sin_port)){
12567 
12568       copy_socket_data(&peer->socket, &pvt->socket);
12569    }
12570 
12571    /* Now that our address has been updated put ourselves back into the container for lookups */
12572    ao2_t_link(peers_by_ip, peer, "ao2_link into peers_by_ip table");
12573 
12574    /* Save SIP options profile */
12575    peer->sipoptions = pvt->sipoptions;
12576 
12577    if (!ast_strlen_zero(curi) && ast_strlen_zero(peer->username))
12578       ast_string_field_set(peer, username, curi);
12579 
12580    AST_SCHED_DEL_UNREF(sched, peer->expire,
12581          unref_peer(peer, "remove register expire ref"));
12582 
12583    if (expire > max_expiry)
12584       expire = max_expiry;
12585    if (expire < min_expiry)
12586       expire = min_expiry;
12587    if (peer->is_realtime && !ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
12588       peer->expire = -1;
12589    } else {
12590       peer->expire = ast_sched_add(sched, (expire + 10) * 1000, expire_register,
12591             ref_peer(peer, "add registration ref"));
12592       if (peer->expire == -1) {
12593          unref_peer(peer, "remote registration ref");
12594       }
12595    }
12596    pvt->expiry = expire;
12597    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);
12598    /* Saving TCP connections is useless, we won't be able to reconnect 
12599       XXX WHY???? XXX
12600       \todo Fix this immediately.
12601    */
12602    if (!peer->rt_fromcontact && (peer->socket.type & SIP_TRANSPORT_UDP))
12603       ast_db_put("SIP/Registry", peer->name, data);
12604    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));
12605 
12606    /* Is this a new IP address for us? */
12607    if (VERBOSITY_ATLEAST(2) && inaddrcmp(&peer->addr, &oldsin)) {
12608       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));
12609    }
12610    sip_poke_peer(peer, 0);
12611    register_peer_exten(peer, 1);
12612    
12613    /* Save User agent */
12614    useragent = get_header(req, "User-Agent");
12615    if (strcasecmp(useragent, peer->useragent)) {
12616       ast_string_field_set(peer, useragent, useragent);
12617       ast_verb(4, "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
12618    }
12619    return PARSE_REGISTER_UPDATE;
12620 }
12621 
12622 /*! \brief Remove route from route list */
12623 static void free_old_route(struct sip_route *route)
12624 {
12625    struct sip_route *next;
12626 
12627    while (route) {
12628       next = route->next;
12629       ast_free(route);
12630       route = next;
12631    }
12632 }
12633 
12634 /*! \brief List all routes - mostly for debugging */
12635 static void list_route(struct sip_route *route)
12636 {
12637    if (!route)
12638       ast_verbose("list_route: no route\n");
12639    else {
12640       for (;route; route = route->next)
12641          ast_verbose("list_route: hop: <%s>\n", route->hop);
12642    }
12643 }
12644 
12645 /*! \brief Build route list from Record-Route header */
12646 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
12647 {
12648    struct sip_route *thishop, *head, *tail;
12649    int start = 0;
12650    int len;
12651    const char *rr, *contact, *c;
12652 
12653    /* Once a persistant route is set, don't fool with it */
12654    if (p->route && p->route_persistant) {
12655       ast_debug(1, "build_route: Retaining previous route: <%s>\n", p->route->hop);
12656       return;
12657    }
12658 
12659    if (p->route) {
12660       free_old_route(p->route);
12661       p->route = NULL;
12662    }
12663 
12664    /* We only want to create the route set the first time this is called */
12665    p->route_persistant = 1;
12666    
12667    /* Build a tailq, then assign it to p->route when done.
12668     * If backwards, we add entries from the head so they end up
12669     * in reverse order. However, we do need to maintain a correct
12670     * tail pointer because the contact is always at the end.
12671     */
12672    head = NULL;
12673    tail = head;
12674    /* 1st we pass through all the hops in any Record-Route headers */
12675    for (;;) {
12676       /* Each Record-Route header */
12677       rr = __get_header(req, "Record-Route", &start);
12678       if (*rr == '\0')
12679          break;
12680       for (; (rr = strchr(rr, '<')) ; rr += len) { /* Each route entry */
12681          ++rr;
12682          len = strcspn(rr, ">") + 1;
12683          /* Make a struct route */
12684          if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
12685             /* ast_calloc is not needed because all fields are initialized in this block */
12686             ast_copy_string(thishop->hop, rr, len);
12687             ast_debug(2, "build_route: Record-Route hop: <%s>\n", thishop->hop);
12688             /* Link in */
12689             if (backwards) {
12690                /* Link in at head so they end up in reverse order */
12691                thishop->next = head;
12692                head = thishop;
12693                /* If this was the first then it'll be the tail */
12694                if (!tail)
12695                   tail = thishop;
12696             } else {
12697                thishop->next = NULL;
12698                /* Link in at the end */
12699                if (tail)
12700                   tail->next = thishop;
12701                else
12702                   head = thishop;
12703                tail = thishop;
12704             }
12705          }
12706       }
12707    }
12708 
12709    /* Only append the contact if we are dealing with a strict router */
12710    if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop, ";lr") == NULL) ) {
12711       /* 2nd append the Contact: if there is one */
12712       /* Can be multiple Contact headers, comma separated values - we just take the first */
12713       contact = get_header(req, "Contact");
12714       if (!ast_strlen_zero(contact)) {
12715          ast_debug(2, "build_route: Contact hop: %s\n", contact);
12716          /* Look for <: delimited address */
12717          c = strchr(contact, '<');
12718          if (c) {
12719             /* Take to > */
12720             ++c;
12721             len = strcspn(c, ">") + 1;
12722          } else {
12723             /* No <> - just take the lot */
12724             c = contact;
12725             len = strlen(contact) + 1;
12726          }
12727          if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
12728             /* ast_calloc is not needed because all fields are initialized in this block */
12729             ast_copy_string(thishop->hop, c, len);
12730             thishop->next = NULL;
12731             /* Goes at the end */
12732             if (tail)
12733                tail->next = thishop;
12734             else
12735                head = thishop;
12736          }
12737       }
12738    }
12739 
12740    /* Store as new route */
12741    p->route = head;
12742 
12743    /* For debugging dump what we ended up with */
12744    if (sip_debug_test_pvt(p))
12745       list_route(p->route);
12746 }
12747 
12748 /*! \brief builds the sip_pvt's randdata field which is used for the nonce
12749  *  challenge.  When forceupdate is not set, the nonce is only updated if
12750  *  the current one is stale.  In this case, a stalenonce is one which
12751  *  has already received a response, if a nonce has not received a response
12752  *  it is not always necessary or beneficial to create a new one. */
12753 
12754 static void set_nonce_randdata(struct sip_pvt *p, int forceupdate)
12755 {
12756    if (p->stalenonce || forceupdate || ast_strlen_zero(p->randdata)) {
12757       ast_string_field_build(p, randdata, "%08lx", ast_random()); /* Create nonce for challenge */
12758       p->stalenonce = 0;
12759    }
12760 }
12761 
12762 AST_THREADSTORAGE(check_auth_buf);
12763 #define CHECK_AUTH_BUF_INITLEN   256
12764 
12765 /*! \brief  Check user authorization from peer definition 
12766    Some actions, like REGISTER and INVITEs from peers require
12767    authentication (if peer have secret set) 
12768     \return 0 on success, non-zero on error
12769 */
12770 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
12771                 const char *secret, const char *md5secret, int sipmethod,
12772                 char *uri, enum xmittype reliable, int ignore)
12773 {
12774    const char *response;
12775    char *reqheader, *respheader;
12776    const char *authtoken;
12777    char a1_hash[256];
12778    char resp_hash[256]="";
12779    char *c;
12780    int  wrongnonce = FALSE;
12781    int  good_response;
12782    const char *usednonce = p->randdata;
12783    struct ast_str *buf;
12784    int res;
12785 
12786    /* table of recognised keywords, and their value in the digest */
12787    enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
12788    struct x {
12789       const char *key;
12790       const char *s;
12791    } *i, keys[] = {
12792       [K_RESP] = { "response=", "" },
12793       [K_URI] = { "uri=", "" },
12794       [K_USER] = { "username=", "" },
12795       [K_NONCE] = { "nonce=", "" },
12796       [K_LAST] = { NULL, NULL}
12797    };
12798 
12799    /* Always OK if no secret */
12800    if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
12801       return AUTH_SUCCESSFUL;
12802 
12803    /* Always auth with WWW-auth since we're NOT a proxy */
12804    /* Using proxy-auth in a B2BUA may block proxy authorization in the same transaction */
12805    response = "401 Unauthorized";
12806 
12807    /*
12808     * Note the apparent swap of arguments below, compared to other
12809     * usages of auth_headers().
12810     */
12811    auth_headers(WWW_AUTH, &respheader, &reqheader);
12812 
12813    authtoken =  get_header(req, reqheader);  
12814    if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
12815       /* This is a retransmitted invite/register/etc, don't reconstruct authentication
12816          information */
12817       if (!reliable) {
12818          /* Resend message if this was NOT a reliable delivery.   Otherwise the
12819             retransmission should get it */
12820          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
12821          /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
12822          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12823       }
12824       return AUTH_CHALLENGE_SENT;
12825    } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
12826       /* We have no auth, so issue challenge and request authentication */
12827       set_nonce_randdata(p, 1); /* Create nonce for challenge */
12828       transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
12829       /* Schedule auto destroy in 32 seconds */
12830       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12831       return AUTH_CHALLENGE_SENT;
12832    } 
12833 
12834    /* --- We have auth, so check it */
12835 
12836    /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
12837       an example in the spec of just what it is you're doing a hash on. */
12838 
12839    if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN)))
12840       return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
12841 
12842    /* Make a copy of the response and parse it */
12843    res = ast_str_set(&buf, 0, "%s", authtoken);
12844 
12845    if (res == AST_DYNSTR_BUILD_FAILED)
12846       return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
12847 
12848    c = buf->str;
12849 
12850    while(c && *(c = ast_skip_blanks(c)) ) { /* lookup for keys */
12851       for (i = keys; i->key != NULL; i++) {
12852          const char *separator = ",";  /* default */
12853 
12854          if (strncasecmp(c, i->key, strlen(i->key)) != 0)
12855             continue;
12856          /* Found. Skip keyword, take text in quotes or up to the separator. */
12857          c += strlen(i->key);
12858          if (*c == '"') { /* in quotes. Skip first and look for last */
12859             c++;
12860             separator = "\"";
12861          }
12862          i->s = c;
12863          strsep(&c, separator);
12864          break;
12865       }
12866       if (i->key == NULL) /* not found, jump after space or comma */
12867          strsep(&c, " ,");
12868    }
12869 
12870    /* Verify that digest username matches  the username we auth as */
12871    if (strcmp(username, keys[K_USER].s)) {
12872       ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
12873          username, keys[K_USER].s);
12874       /* Oops, we're trying something here */
12875       return AUTH_USERNAME_MISMATCH;
12876    }
12877 
12878    /* Verify nonce from request matches our nonce, and the nonce has not already been responded to.
12879     * If this check fails, send 401 with new nonce */
12880    if (strcasecmp(p->randdata, keys[K_NONCE].s) || p->stalenonce) { /* XXX it was 'n'casecmp ? */
12881       wrongnonce = TRUE;
12882       usednonce = keys[K_NONCE].s;
12883    } else {
12884       p->stalenonce = 1; /* now, since the nonce has a response, mark it as stale so it can't be sent or responded to again */
12885    }
12886 
12887    if (!ast_strlen_zero(md5secret))
12888       ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
12889    else {
12890       char a1[256];
12891       snprintf(a1, sizeof(a1), "%s:%s:%s", username, sip_cfg.realm, secret);
12892       ast_md5_hash(a1_hash, a1);
12893    }
12894 
12895    /* compute the expected response to compare with what we received */
12896    {
12897       char a2[256];
12898       char a2_hash[256];
12899       char resp[256];
12900 
12901       snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
12902             S_OR(keys[K_URI].s, uri));
12903       ast_md5_hash(a2_hash, a2);
12904       snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
12905       ast_md5_hash(resp_hash, resp);
12906    }
12907 
12908    good_response = keys[K_RESP].s &&
12909          !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
12910    if (wrongnonce) {
12911       if (good_response) {
12912          if (sipdebug)
12913             ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "From"));
12914          /* We got working auth token, based on stale nonce . */
12915          set_nonce_randdata(p, 0);
12916          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
12917       } else {
12918          /* Everything was wrong, so give the device one more try with a new challenge */
12919          if (!req->ignore) {
12920             if (sipdebug)
12921                ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
12922             set_nonce_randdata(p, 1);
12923          } else {
12924             if (sipdebug)
12925                ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", get_header(req, "To"));
12926          }
12927          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
12928       }
12929 
12930       /* Schedule auto destroy in 32 seconds */
12931       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12932       return AUTH_CHALLENGE_SENT;
12933    } 
12934    if (good_response) {
12935       append_history(p, "AuthOK", "Auth challenge successful for %s", username);
12936       return AUTH_SUCCESSFUL;
12937    }
12938 
12939    /* Ok, we have a bad username/secret pair */
12940    /* Tell the UAS not to re-send this authentication data, because
12941       it will continue to fail
12942    */
12943 
12944    return AUTH_SECRET_FAILED;
12945 }
12946 
12947 /*! \brief Change onhold state of a peer using a pvt structure */
12948 static void sip_peer_hold(struct sip_pvt *p, int hold)
12949 {
12950    struct sip_peer *peer = find_peer(p->peername, NULL, 1, FINDALLDEVICES, FALSE, 0);
12951 
12952    if (!peer)
12953       return;
12954 
12955    /* If they put someone on hold, increment the value... otherwise decrement it */
12956    ast_atomic_fetchadd_int(&peer->onHold, (hold ? +1 : -1));
12957 
12958    /* Request device state update */
12959    ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
12960    unref_peer(peer, "sip_peer_hold: from find_peer operation");
12961    
12962    return;
12963 }
12964 
12965 /*! \brief Receive MWI events that we have subscribed to */
12966 static void mwi_event_cb(const struct ast_event *event, void *userdata)
12967 {
12968    struct sip_peer *peer = userdata;
12969 
12970    ao2_lock(peer);
12971    sip_send_mwi_to_peer(peer, event, 0);
12972    ao2_unlock(peer);
12973 }
12974 
12975 /*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem
12976 \note If you add an "hint" priority to the extension in the dial plan,
12977    you will get notifications on device state changes */
12978 static int cb_extensionstate(char *context, char* exten, int state, void *data)
12979 {
12980    struct sip_pvt *p = data;
12981 
12982    sip_pvt_lock(p);
12983 
12984    switch(state) {
12985    case AST_EXTENSION_DEACTIVATED:  /* Retry after a while */
12986    case AST_EXTENSION_REMOVED:   /* Extension is gone */
12987       if (p->autokillid > -1 && sip_cancel_destroy(p))   /* Remove subscription expiry for renewals */
12988          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
12989       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);  /* Delete subscription in 32 secs */
12990       ast_verb(2, "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
12991       p->stateid = -1;
12992       p->subscribed = NONE;
12993       append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
12994       break;
12995    default: /* Tell user */
12996       p->laststate = state;
12997       break;
12998    }
12999    if (p->subscribed != NONE) {  /* Only send state NOTIFY if we know the format */
13000       if (!p->pendinginvite) {
13001          transmit_state_notify(p, state, 1, FALSE);
13002       } else {
13003          /* We already have a NOTIFY sent that is not answered. Queue the state up.
13004             if many state changes happen meanwhile, we will only send a notification of the last one */
13005          ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
13006       }
13007    }
13008    ast_verb(2, "Extension Changed %s[%s] new state %s for Notify User %s %s\n", exten, context, ast_extension_state2str(state), p->username,
13009          ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
13010 
13011    sip_pvt_unlock(p);
13012 
13013    return 0;
13014 }
13015 
13016 /*! \brief Send a fake 401 Unauthorized response when the administrator
13017   wants to hide the names of local devices  from fishers
13018  */
13019 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable)
13020 {
13021    /* We have to emulate EXACTLY what we'd get with a good peer
13022     * and a bad password, or else we leak information. */
13023    const char *response = "407 Proxy Authentication Required";
13024    const char *reqheader = "Proxy-Authorization";
13025    const char *respheader = "Proxy-Authenticate";
13026    const char *authtoken;
13027    struct ast_str *buf;
13028    char *c;
13029 
13030    /* table of recognised keywords, and their value in the digest */
13031    enum keys { K_NONCE, K_LAST };
13032    struct x {
13033       const char *key;
13034       const char *s;
13035    } *i, keys[] = {
13036       [K_NONCE] = { "nonce=", "" },
13037       [K_LAST] = { NULL, NULL}
13038    };
13039 
13040    if (sipmethod == SIP_REGISTER || sipmethod == SIP_SUBSCRIBE) {
13041       response = "401 Unauthorized";
13042       reqheader = "Authorization";
13043       respheader = "WWW-Authenticate";
13044    }
13045    authtoken = get_header(req, reqheader);
13046    if (req->ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
13047       /* This is a retransmitted invite/register/etc, don't reconstruct authentication
13048        * information */
13049       transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
13050       /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
13051       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13052       return;
13053    } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
13054       /* We have no auth, so issue challenge and request authentication */
13055       set_nonce_randdata(p, 1);
13056       transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
13057       /* Schedule auto destroy in 32 seconds */
13058       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13059       return;
13060    }
13061 
13062    if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
13063       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
13064       return;
13065    }
13066 
13067    /* Make a copy of the response and parse it */
13068    if (ast_str_set(&buf, 0, "%s", authtoken) == AST_DYNSTR_BUILD_FAILED) {
13069       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
13070       return;
13071    }
13072 
13073    c = buf->str;
13074 
13075    while (c && *(c = ast_skip_blanks(c))) { /* lookup for keys */
13076       for (i = keys; i->key != NULL; i++) {
13077          const char *separator = ",";  /* default */
13078 
13079          if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
13080             continue;
13081          }
13082          /* Found. Skip keyword, take text in quotes or up to the separator. */
13083          c += strlen(i->key);
13084          if (*c == '"') { /* in quotes. Skip first and look for last */
13085             c++;
13086             separator = "\"";
13087          }
13088          i->s = c;
13089          strsep(&c, separator);
13090          break;
13091       }
13092       if (i->key == NULL) { /* not found, jump after space or comma */
13093          strsep(&c, " ,");
13094       }
13095    }
13096 
13097    /* Verify nonce from request matches our nonce.  If not, send 401 with new nonce */
13098    if (strcasecmp(p->randdata, keys[K_NONCE].s)) {
13099       if (!req->ignore) {
13100          set_nonce_randdata(p, 1);
13101       }
13102       transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
13103 
13104       /* Schedule auto destroy in 32 seconds */
13105       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13106    } else {
13107       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
13108    }
13109 }
13110 
13111 /*!
13112  * Terminate the uri at the first ';' or space.
13113  * Technically we should ignore escaped space per RFC3261 (19.1.1 etc)
13114  * but don't do it for the time being. Remember the uri format is:
13115  * (User-parameters was added after RFC 3261)
13116  *\verbatim
13117  *
13118  * sip:user:password;user-parameters@host:port;uri-parameters?headers
13119  * sips:user:password;user-parameters@host:port;uri-parameters?headers
13120  *
13121  *\endverbatim
13122  * \todo As this function does not support user-parameters, it's considered broken
13123  * and needs fixing.
13124  */
13125 static char *terminate_uri(char *uri)
13126 {
13127    char *t = uri;
13128    while (*t && *t > ' ' && *t != ';')
13129       t++;
13130    *t = '\0';
13131    return uri;
13132 }
13133 
13134 /*! \brief Verify registration of user 
13135    - Registration is done in several steps, first a REGISTER without auth
13136      to get a challenge (nonce) then a second one with auth
13137    - Registration requests are only matched with peers that are marked as "dynamic"
13138  */
13139 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
13140                      struct sip_request *req, char *uri)
13141 {
13142    enum check_auth_result res = AUTH_NOT_FOUND;
13143    struct sip_peer *peer;
13144    char tmp[256];
13145    char *name, *c;
13146    char *domain;
13147 
13148    terminate_uri(uri);  /* warning, overwrite the string */
13149 
13150    ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
13151    if (sip_cfg.pedanticsipchecking)
13152       ast_uri_decode(tmp);
13153 
13154    c = get_in_brackets(tmp);
13155    c = remove_uri_parameters(c);
13156 
13157    if (!strncasecmp(c, "sip:", 4)) {
13158       name = c + 4;
13159    } else if (!strncasecmp(c, "sips:", 5)) {
13160       name = c + 5;
13161    } else {
13162       name = c;
13163       ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_inet_ntoa(sin->sin_addr));
13164    }
13165 
13166    /*! \todo XXX here too we interpret a missing @domain as a name-only
13167     * URI, whereas the RFC says this is a domain-only uri.
13168     */
13169    /* Strip off the domain name */
13170    if ((c = strchr(name, '@'))) {
13171       *c++ = '\0';
13172       domain = c;
13173       if ((c = strchr(domain, ':')))   /* Remove :port */
13174          *c = '\0';
13175       if (!AST_LIST_EMPTY(&domain_list)) {
13176          if (!check_sip_domain(domain, NULL, 0)) {
13177             transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
13178             return AUTH_UNKNOWN_DOMAIN;
13179          }
13180       }
13181    }
13182    c = strchr(name, ';');  /* Remove any Username parameters */
13183    if (c)
13184       *c = '\0';
13185 
13186    ast_string_field_set(p, exten, name);
13187    build_contact(p);
13188    if (req->ignore) {
13189       /* Expires is a special case, where we only want to load the peer if this isn't a deregistration attempt */
13190       const char *expires = get_header(req, "Expires");
13191       int expire = atoi(expires);
13192 
13193       if (ast_strlen_zero(expires)) { /* No expires header; look in Contact */
13194          if ((expires = strcasestr(get_header(req, "Contact"), ";expires="))) {
13195             expire = atoi(expires + 9);
13196          }
13197       }
13198       if (!ast_strlen_zero(expires) && expire == 0) {
13199          transmit_response_with_date(p, "200 OK", req);
13200          return 0;
13201       }
13202    }
13203    peer = find_peer(name, NULL, TRUE, FINDPEERS, FALSE, 0);
13204    if (!(peer && ast_apply_ha(peer->ha, sin))) {
13205       /* Peer fails ACL check */
13206       if (peer) {
13207          unref_peer(peer, "register_verify: unref_peer: from find_peer operation");
13208          peer = NULL;
13209          res = AUTH_ACL_FAILED;
13210       } else
13211          res = AUTH_NOT_FOUND;
13212    }
13213 
13214    if (peer) {
13215       /*! \todo OEJ Remove this - there's never RTP in a REGISTER dialog... */
13216       /* Set Frame packetization */
13217       if (p->rtp) {
13218          ast_rtp_codec_setpref(p->rtp, &peer->prefs);
13219          p->autoframing = peer->autoframing;
13220       }
13221       if (!peer->host_dynamic) {
13222          ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
13223          res = AUTH_PEER_NOT_DYNAMIC;
13224       } else {
13225          ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT);
13226          if (ast_test_flag(&p->flags[1], SIP_PAGE2_REGISTERTRYING))
13227             transmit_response(p, "100 Trying", req);
13228          if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri, XMIT_UNRELIABLE, req->ignore))) {
13229             if (sip_cancel_destroy(p))
13230                ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
13231 
13232             if (check_request_transport(peer, req)) {
13233                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
13234                transmit_response_with_date(p, "403 Forbidden", req);
13235                res = AUTH_BAD_TRANSPORT;
13236             } else {
13237 
13238                /* We have a successful registration attempt with proper authentication,
13239                   now, update the peer */
13240                switch (parse_register_contact(p, peer, req)) {
13241                case PARSE_REGISTER_DENIED:
13242                   ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
13243                   transmit_response_with_date(p, "603 Denied", req);
13244                   peer->lastmsgssent = -1;
13245                   res = 0;
13246                   break;
13247                case PARSE_REGISTER_FAILED:
13248                   ast_log(LOG_WARNING, "Failed to parse contact info\n");
13249                   transmit_response_with_date(p, "400 Bad Request", req);
13250                   peer->lastmsgssent = -1;
13251                   res = 0;
13252                   break;
13253                case PARSE_REGISTER_QUERY:
13254                   ast_string_field_set(p, fullcontact, peer->fullcontact);
13255                   transmit_response_with_date(p, "200 OK", req);
13256                   peer->lastmsgssent = -1;
13257                   res = 0;
13258                   break;
13259                case PARSE_REGISTER_UPDATE:
13260                   ast_string_field_set(p, fullcontact, peer->fullcontact);
13261                   update_peer(peer, p->expiry);
13262                   /* Say OK and ask subsystem to retransmit msg counter */
13263                   transmit_response_with_date(p, "200 OK", req);
13264                   if (!ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY))
13265                      peer->lastmsgssent = -1;
13266                   res = 0;
13267                   break;
13268                }
13269             }
13270 
13271          } 
13272       }
13273    }
13274    if (!peer && sip_cfg.autocreatepeer) {
13275       /* Create peer if we have autocreate mode enabled */
13276       peer = temp_peer(name);
13277       if (peer) {
13278          ao2_t_link(peers, peer, "link peer into peer table");
13279          if (peer->addr.sin_addr.s_addr) {
13280             ao2_t_link(peers_by_ip, peer, "link peer into peers-by-ip table");
13281          }
13282          
13283          if (sip_cancel_destroy(p))
13284             ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
13285          switch (parse_register_contact(p, peer, req)) {
13286          case PARSE_REGISTER_DENIED:
13287             ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
13288             transmit_response_with_date(p, "403 Forbidden (ACL)", req);
13289             peer->lastmsgssent = -1;
13290             res = 0;
13291             break;
13292          case PARSE_REGISTER_FAILED:
13293             ast_log(LOG_WARNING, "Failed to parse contact info\n");
13294             transmit_response_with_date(p, "400 Bad Request", req);
13295             peer->lastmsgssent = -1;
13296             res = 0;
13297             break;
13298          case PARSE_REGISTER_QUERY:
13299             ast_string_field_set(p, fullcontact, peer->fullcontact);
13300             transmit_response_with_date(p, "200 OK", req);
13301             peer->lastmsgssent = -1;
13302             res = 0;
13303             break;
13304          case PARSE_REGISTER_UPDATE:
13305             ast_string_field_set(p, fullcontact, peer->fullcontact);
13306             /* Say OK and ask subsystem to retransmit msg counter */
13307             transmit_response_with_date(p, "200 OK", req);
13308             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));
13309             peer->lastmsgssent = -1;
13310             res = 0;
13311             break;
13312          }
13313       }
13314    }
13315    if (!peer && sip_cfg.alwaysauthreject) {
13316       /* If we found a peer, we transmit a 100 Trying.  Therefore, if we're
13317        * trying to avoid leaking information, we MUST also transmit the same
13318        * response when we DON'T find a peer. */
13319       transmit_response(p, "100 Trying", req);
13320       /* Insert a fake delay between the 100 and the subsequent failure. */
13321       sched_yield();
13322    }
13323    if (!res) {
13324       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
13325    }
13326    if (res < 0) {
13327       switch (res) {
13328       case AUTH_SECRET_FAILED:
13329          /* Wrong password in authentication. Go away, don't try again until you fixed it */
13330          transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
13331          if (global_authfailureevents)
13332             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", 
13333                name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13334          break;
13335       case AUTH_USERNAME_MISMATCH:
13336          /* Username and digest username does not match.
13337             Asterisk uses the From: username for authentication. We need the
13338             devices to use the same authentication user name until we support
13339             proper authentication by digest auth name */
13340       case AUTH_NOT_FOUND:
13341       case AUTH_PEER_NOT_DYNAMIC:
13342       case AUTH_ACL_FAILED:
13343          if (sip_cfg.alwaysauthreject) {
13344             transmit_fake_auth_response(p, SIP_REGISTER, &p->initreq, XMIT_UNRELIABLE);
13345             if (global_authfailureevents) {
13346                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",
13347                   name, res == AUTH_PEER_NOT_DYNAMIC ? "AUTH_PEER_NOT_DYNAMIC" : "URI_NOT_FOUND",
13348                   ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13349             }
13350          } else {
13351             /* URI not found */
13352             if (res == AUTH_PEER_NOT_DYNAMIC) {
13353                transmit_response(p, "403 Forbidden", &p->initreq);
13354                if (global_authfailureevents) {
13355                   manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
13356                      "ChannelType: SIP\r\n"
13357                      "Peer: SIP/%s\r\n"
13358                      "PeerStatus: Rejected\r\n"
13359                      "Cause: AUTH_PEER_NOT_DYNAMIC\r\n"
13360                      "Address: %s\r\n"
13361                      "Port: %d\r\n",
13362                      name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13363                }
13364             } else {
13365                transmit_response(p, "404 Not found", &p->initreq);
13366                if (global_authfailureevents) {
13367                   manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
13368                      "ChannelType: SIP\r\n"
13369                      "Peer: SIP/%s\r\n"
13370                      "PeerStatus: Rejected\r\n"
13371                      "Cause: %s\r\n"
13372                      "Address: %s\r\n"
13373                      "Port: %d\r\n",
13374                      name,
13375                      (res == AUTH_USERNAME_MISMATCH) ? "AUTH_USERNAME_MISMATCH" : "URI_NOT_FOUND",
13376                      ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13377                }
13378             }
13379          }
13380          break;
13381       case AUTH_BAD_TRANSPORT:
13382       default:
13383          break;
13384       }
13385    }
13386    if (peer)
13387       unref_peer(peer, "register_verify: unref_peer: tossing stack peer pointer at end of func");
13388 
13389    return res;
13390 }
13391 
13392 /*! \brief Translate referring cause */
13393 static void sip_set_redirstr(struct sip_pvt *p, char *reason) {
13394 
13395    if (!strcmp(reason, "unknown")) {
13396       ast_string_field_set(p, redircause, "UNKNOWN");
13397    } else if (!strcmp(reason, "user-busy")) {
13398       ast_string_field_set(p, redircause, "BUSY");
13399    } else if (!strcmp(reason, "no-answer")) {
13400       ast_string_field_set(p, redircause, "NOANSWER");
13401    } else if (!strcmp(reason, "unavailable")) {
13402       ast_string_field_set(p, redircause, "UNREACHABLE");
13403    } else if (!strcmp(reason, "unconditional")) {
13404       ast_string_field_set(p, redircause, "UNCONDITIONAL");
13405    } else if (!strcmp(reason, "time-of-day")) {
13406       ast_string_field_set(p, redircause, "UNKNOWN");
13407    } else if (!strcmp(reason, "do-not-disturb")) {
13408       ast_string_field_set(p, redircause, "UNKNOWN");
13409    } else if (!strcmp(reason, "deflection")) {
13410       ast_string_field_set(p, redircause, "UNKNOWN");
13411    } else if (!strcmp(reason, "follow-me")) {
13412       ast_string_field_set(p, redircause, "UNKNOWN");
13413    } else if (!strcmp(reason, "out-of-service")) {
13414       ast_string_field_set(p, redircause, "UNREACHABLE");
13415    } else if (!strcmp(reason, "away")) {
13416       ast_string_field_set(p, redircause, "UNREACHABLE");
13417    } else {
13418       ast_string_field_set(p, redircause, "UNKNOWN");
13419    }
13420 }
13421 
13422 /*! \brief Get referring dnis */
13423 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq)
13424 {
13425    char tmp[256], *exten, *rexten, *rdomain;
13426    char *params, *reason = NULL;
13427    struct sip_request *req;
13428    
13429    req = oreq ? oreq : &p->initreq;
13430 
13431    ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
13432    if (ast_strlen_zero(tmp))
13433       return 0;
13434 
13435    /*! \todo This function does not take user-parameters into consideration.
13436       First look for @, then start looking for ; to find uri-parameters.
13437    */
13438    params = strchr(tmp, ';');
13439 
13440    exten = get_in_brackets(tmp);
13441    if (!strncasecmp(exten, "sip:", 4)) {
13442       exten += 4;
13443    } else if (!strncasecmp(exten, "sips:", 5)) {
13444       exten += 5;
13445    } else {
13446       ast_log(LOG_WARNING, "Huh?  Not an RDNIS SIP header (%s)?\n", exten);
13447       return -1;
13448    }
13449 
13450    /* Get diversion-reason param if present */
13451    if (params) {
13452       *params = '\0';   /* Cut off parameters  */
13453       params++;
13454       while (*params == ';' || *params == ' ')
13455          params++;
13456       /* Check if we have a reason parameter */
13457       if ((reason = strcasestr(params, "reason="))) {
13458          reason+=7;
13459          /* Remove enclosing double-quotes */
13460          if (*reason == '"') 
13461             ast_strip_quoted(reason, "\"", "\"");
13462          if (!ast_strlen_zero(reason)) {
13463             sip_set_redirstr(p, reason);
13464             if (p->owner) {
13465                pbx_builtin_setvar_helper(p->owner, "__PRIREDIRECTREASON", p->redircause);
13466                pbx_builtin_setvar_helper(p->owner, "__SIPREDIRECTREASON", reason);
13467             }
13468          }
13469       }
13470    }
13471 
13472    rdomain = exten;
13473    rexten = strsep(&rdomain, "@");  /* trim anything after @ */
13474    if (p->owner) 
13475       pbx_builtin_setvar_helper(p->owner, "__SIPRDNISDOMAIN", rdomain);
13476 
13477    if (sip_debug_test_pvt(p))
13478       ast_verbose("RDNIS for this call is is %s (reason %s)\n", exten, reason ? reason : "");
13479 
13480    ast_string_field_set(p, rdnis, rexten);
13481 
13482    return 0;
13483 }
13484 
13485 /*! \brief Find out who the call is for.
13486    We use the request uri as a destination. 
13487    This code assumes authentication has been done, so that the
13488    device (peer/user) context is already set.
13489    \return 0 on success (found a matching extension),
13490    1 for pickup extension or overlap dialling support (if we support it),
13491    -1 on error.
13492 
13493   \note If the incoming uri is a SIPS: uri, we are required to carry this across
13494    the dialplan, so that the outbound call also is a sips: call or encrypted
13495    IAX2 call. If that's not available, the call should FAIL.
13496 */
13497 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
13498 {
13499    char tmp[256] = "", *uri, *a;
13500    char tmpf[256] = "", *from = NULL;
13501    struct sip_request *req;
13502    char *colon;
13503    char *decoded_uri;
13504    
13505    req = oreq;
13506    if (!req)
13507       req = &p->initreq;
13508 
13509    /* Find the request URI */
13510    if (req->rlPart2)
13511       ast_copy_string(tmp, REQ_OFFSET_TO_STR(req, rlPart2), sizeof(tmp));
13512    
13513    if (sip_cfg.pedanticsipchecking)
13514       ast_uri_decode(tmp);
13515 
13516    uri = get_in_brackets(tmp);
13517    
13518    if (!strncasecmp(uri, "sip:", 4)) {
13519       uri += 4;
13520    } else if (!strncasecmp(uri, "sips:", 5)) {
13521       uri += 5;
13522    } else {
13523       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", uri);
13524       return -1;
13525    }
13526 
13527    /* Now find the From: caller ID and name */
13528    /* XXX Why is this done in get_destination? Isn't it already done?
13529       Needs to be checked 
13530         */
13531    ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
13532    if (!ast_strlen_zero(tmpf)) {
13533       if (sip_cfg.pedanticsipchecking)
13534          ast_uri_decode(tmpf);
13535       from = get_in_brackets(tmpf);
13536    } 
13537    
13538    if (!ast_strlen_zero(from)) {
13539       if (!strncasecmp(from, "sip:", 4)) {
13540          from += 4;
13541       } else if (!strncasecmp(from, "sips:", 5)) {
13542          from += 5;
13543       } else {
13544          ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", from);
13545          return -1;
13546       }
13547       if ((a = strchr(from, '@')))
13548          *a++ = '\0';
13549       else
13550          a = from;   /* just a domain */
13551       from = strsep(&from, ";"); /* Remove userinfo options */
13552       a = strsep(&a, ";");    /* Remove URI options */
13553       ast_string_field_set(p, fromdomain, a);
13554    }
13555 
13556    /* Skip any options and find the domain */
13557 
13558    /* Get the target domain */
13559    if ((a = strchr(uri, '@'))) {
13560       *a++ = '\0';
13561    } else { /* No username part */
13562       a = uri;
13563       uri = "s";  /* Set extension to "s" */
13564    }
13565    colon = strchr(a, ':'); /* Remove :port */
13566    if (colon)
13567       *colon = '\0';
13568 
13569    uri = strsep(&uri, ";");   /* Remove userinfo options */
13570    a = strsep(&a, ";");    /* Remove URI options */
13571 
13572    ast_string_field_set(p, domain, a);
13573 
13574    if (!AST_LIST_EMPTY(&domain_list)) {
13575       char domain_context[AST_MAX_EXTENSION];
13576 
13577       domain_context[0] = '\0';
13578       if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
13579          if (!sip_cfg.allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
13580             ast_debug(1, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
13581             return -2;
13582          }
13583       }
13584       /* If we don't have a peer (i.e. we're a guest call),
13585        * overwrite the original context */
13586       if (!ast_test_flag(&p->flags[1], SIP_PAGE2_HAVEPEERCONTEXT) && !ast_strlen_zero(domain_context))
13587          ast_string_field_set(p, context, domain_context);
13588    }
13589 
13590    /* If the request coming in is a subscription and subscribecontext has been specified use it */
13591    if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext))
13592       ast_string_field_set(p, context, p->subscribecontext);
13593 
13594    if (sip_debug_test_pvt(p))
13595       ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
13596 
13597    /* Since extensions.conf can have unescaped characters, try matching a
13598     * decoded uri in addition to the non-decoded uri. */
13599    decoded_uri = ast_strdupa(uri);
13600    ast_uri_decode(decoded_uri);
13601 
13602    /* If this is a subscription we actually just need to see if a hint exists for the extension */
13603    if (req->method == SIP_SUBSCRIBE) {
13604       char hint[AST_MAX_EXTENSION];
13605       int which = 0;
13606       if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, uri) ||
13607           (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, decoded_uri) && (which = 1))) {
13608          if (!oreq) {
13609             ast_string_field_set(p, exten, which ? decoded_uri : uri);
13610          }
13611          return 0;
13612       } else {
13613          return -1;
13614       }
13615    } else {
13616       int which = 0;
13617       /* Check the dialplan for the username part of the request URI,
13618          the domain will be stored in the SIPDOMAIN variable
13619          Return 0 if we have a matching extension */
13620       if (ast_exists_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from)) ||
13621           (ast_exists_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from)) && (which = 1)) ||
13622           !strcmp(decoded_uri, ast_pickup_ext())) {
13623          if (!oreq) {
13624             ast_string_field_set(p, exten, which ? decoded_uri : uri);
13625          }
13626          return 0;
13627       }
13628    }
13629 
13630    /* Return 1 for pickup extension or overlap dialling support (if we support it) */
13631    if((ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) && 
13632        ast_canmatch_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))) ||
13633        !strncmp(decoded_uri, ast_pickup_ext(), strlen(decoded_uri))) {
13634       return 1;
13635    }
13636    
13637    return -1;
13638 }
13639 
13640 /*! \brief Lock dialog lock and find matching pvt lock  
13641    \return a reference, remember to release it when done 
13642 */
13643 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag) 
13644 {
13645    struct sip_pvt *sip_pvt_ptr;
13646    struct sip_pvt tmp_dialog = {
13647       .callid = callid,
13648    };
13649 
13650    if (totag)
13651       ast_debug(4, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
13652 
13653    /* Search dialogs and find the match */
13654    
13655    sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find of dialog in dialogs table");
13656    if (sip_pvt_ptr) {
13657       /* Go ahead and lock it (and its owner) before returning */
13658       sip_pvt_lock(sip_pvt_ptr);
13659       if (sip_cfg.pedanticsipchecking) {
13660          unsigned char frommismatch = 0, tomismatch = 0;
13661 
13662          if (ast_strlen_zero(fromtag)) {
13663             sip_pvt_unlock(sip_pvt_ptr);
13664             ast_debug(4, "Matched %s call for callid=%s - no from tag specified, pedantic check fails\n",
13665                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
13666             return NULL;
13667          }
13668 
13669          if (ast_strlen_zero(totag)) {
13670             sip_pvt_unlock(sip_pvt_ptr);
13671             ast_debug(4, "Matched %s call for callid=%s - no to tag specified, pedantic check fails\n",
13672                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
13673             return NULL;
13674          }
13675          /* RFC 3891
13676           * > 3.  User Agent Server Behavior: Receiving a Replaces Header
13677           * > The Replaces header contains information used to match an existing
13678           * > SIP dialog (call-id, to-tag, and from-tag).  Upon receiving an INVITE
13679           * > with a Replaces header, the User Agent (UA) attempts to match this
13680           * > information with a confirmed or early dialog.  The User Agent Server
13681           * > (UAS) matches the to-tag and from-tag parameters as if they were tags
13682           * > present in an incoming request.  In other words, the to-tag parameter
13683           * > is compared to the local tag, and the from-tag parameter is compared
13684           * > to the remote tag.
13685           *
13686           * Thus, the totag is always compared to the local tag, regardless if
13687           * this our call is an incoming or outgoing call.
13688           */
13689          frommismatch = !!strcmp(fromtag, sip_pvt_ptr->theirtag);
13690          tomismatch = !!strcmp(totag, sip_pvt_ptr->tag);
13691 
13692          if (frommismatch || tomismatch) {
13693             sip_pvt_unlock(sip_pvt_ptr);
13694             if (frommismatch) {
13695                ast_debug(4, "Matched %s call for callid=%s - pedantic from tag check fails; their tag is %s our tag is %s\n",
13696                     sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid, 
13697                     fromtag, sip_pvt_ptr->theirtag);
13698             }
13699             if (tomismatch) {
13700                ast_debug(4, "Matched %s call for callid=%s - pedantic to tag check fails; their tag is %s our tag is %s\n",
13701                     sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid, 
13702                     totag, sip_pvt_ptr->tag);
13703             }
13704             return NULL;
13705          }
13706       }
13707       
13708       if (totag)
13709          ast_debug(4, "Matched %s call - their tag is %s Our tag is %s\n",
13710                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING",
13711                  sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
13712 
13713       /* deadlock avoidance... */
13714       while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
13715          sip_pvt_unlock(sip_pvt_ptr);
13716          usleep(1);
13717          sip_pvt_lock(sip_pvt_ptr);
13718       }
13719    }
13720    
13721    return sip_pvt_ptr;
13722 }
13723 
13724 /*! \brief Call transfer support (the REFER method) 
13725  *    Extracts Refer headers into pvt dialog structure 
13726  *
13727  * \note If we get a SIPS uri in the refer-to header, we're required to set up a secure signalling path
13728  * to that extension. As a minimum, this needs to be added to a channel variable, if not a channel
13729  * flag.
13730  */
13731 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
13732 {
13733 
13734    const char *p_referred_by = NULL;
13735    char *h_refer_to = NULL; 
13736    char *h_referred_by = NULL;
13737    char *refer_to;
13738    const char *p_refer_to;
13739    char *referred_by_uri = NULL;
13740    char *ptr;
13741    struct sip_request *req = NULL;
13742    const char *transfer_context = NULL;
13743    struct sip_refer *referdata;
13744 
13745 
13746    req = outgoing_req;
13747    referdata = transferer->refer;
13748 
13749    if (!req)
13750       req = &transferer->initreq;
13751 
13752    p_refer_to = get_header(req, "Refer-To");
13753    if (ast_strlen_zero(p_refer_to)) {
13754       ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
13755       return -2;  /* Syntax error */
13756    }
13757    h_refer_to = ast_strdupa(p_refer_to);
13758    refer_to = get_in_brackets(h_refer_to);
13759    if (sip_cfg.pedanticsipchecking)
13760       ast_uri_decode(refer_to);
13761 
13762    if (!strncasecmp(refer_to, "sip:", 4)) {
13763       refer_to += 4;       /* Skip sip: */
13764    } else if (!strncasecmp(refer_to, "sips:", 5)) {
13765       refer_to += 5;
13766    } else {
13767       ast_log(LOG_WARNING, "Can't transfer to non-sip: URI.  (Refer-to: %s)?\n", refer_to);
13768       return -3;
13769    }
13770 
13771    /* Get referred by header if it exists */
13772    p_referred_by = get_header(req, "Referred-By");
13773 
13774    /* Give useful transfer information to the dialplan */
13775    if (transferer->owner) {
13776       struct ast_channel *peer = ast_bridged_channel(transferer->owner);
13777       if (peer) {
13778          pbx_builtin_setvar_helper(peer, "SIPREFERRINGCONTEXT", transferer->context);
13779          pbx_builtin_setvar_helper(peer, "SIPREFERREDBYHDR", p_referred_by);
13780       }
13781    }
13782 
13783    if (!ast_strlen_zero(p_referred_by)) {
13784       char *lessthan;
13785       h_referred_by = ast_strdupa(p_referred_by);
13786       if (sip_cfg.pedanticsipchecking)
13787          ast_uri_decode(h_referred_by);
13788 
13789       /* Store referrer's caller ID name */
13790       ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
13791       if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
13792          *(lessthan - 1) = '\0'; /* Space */
13793       }
13794 
13795       referred_by_uri = get_in_brackets(h_referred_by);
13796       if (!strncasecmp(referred_by_uri, "sip:", 4)) {
13797          referred_by_uri += 4;      /* Skip sip: */
13798       } else if (!strncasecmp(referred_by_uri, "sips:", 5)) {
13799          referred_by_uri += 5;      /* Skip sips: */
13800       } else {
13801          ast_log(LOG_WARNING, "Huh?  Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
13802          referred_by_uri = NULL;
13803       }
13804    }
13805 
13806    /* Check for arguments in the refer_to header */
13807    if ((ptr = strcasestr(refer_to, "replaces="))) {
13808       char *to = NULL, *from = NULL;
13809       
13810       /* This is an attended transfer */
13811       referdata->attendedtransfer = 1;
13812       ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
13813       ast_uri_decode(referdata->replaces_callid);
13814       if ((ptr = strchr(referdata->replaces_callid, ';')))  /* Find options */ {
13815          *ptr++ = '\0';
13816       }
13817       
13818       if (ptr) {
13819          /* Find the different tags before we destroy the string */
13820          to = strcasestr(ptr, "to-tag=");
13821          from = strcasestr(ptr, "from-tag=");
13822       }
13823       
13824       /* Grab the to header */
13825       if (to) {
13826          ptr = to + 7;
13827          if ((to = strchr(ptr, '&')))
13828             *to = '\0';
13829          if ((to = strchr(ptr, ';')))
13830             *to = '\0';
13831          ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
13832       }
13833       
13834       if (from) {
13835          ptr = from + 9;
13836          if ((to = strchr(ptr, '&')))
13837             *to = '\0';
13838          if ((to = strchr(ptr, ';')))
13839             *to = '\0';
13840          ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
13841       }
13842       
13843       if (!sip_cfg.pedanticsipchecking)
13844          ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
13845       else
13846          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>" );
13847    }
13848    
13849    if ((ptr = strchr(refer_to, '@'))) {   /* Separate domain */
13850       char *urioption = NULL, *domain;
13851       *ptr++ = '\0';
13852 
13853       if ((urioption = strchr(ptr, ';'))) /* Separate urioptions */
13854          *urioption++ = '\0';
13855       
13856       domain = ptr;
13857       if ((ptr = strchr(domain, ':'))) /* Remove :port */
13858          *ptr = '\0';
13859       
13860       /* Save the domain for the dial plan */
13861       ast_copy_string(referdata->refer_to_domain, domain, sizeof(referdata->refer_to_domain));
13862       if (urioption)
13863          ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
13864    }
13865 
13866    if ((ptr = strchr(refer_to, ';')))  /* Remove options */
13867       *ptr = '\0';
13868    ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
13869    
13870    if (referred_by_uri) {
13871       if ((ptr = strchr(referred_by_uri, ';')))    /* Remove options */
13872          *ptr = '\0';
13873       ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
13874    } else {
13875       referdata->referred_by[0] = '\0';
13876    }
13877 
13878    /* Determine transfer context */
13879    if (transferer->owner)  /* Mimic behaviour in res_features.c */
13880       transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
13881 
13882    /* By default, use the context in the channel sending the REFER */
13883    if (ast_strlen_zero(transfer_context)) {
13884       transfer_context = S_OR(transferer->owner->macrocontext,
13885                S_OR(transferer->context, sip_cfg.default_context));
13886    }
13887 
13888    ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
13889    
13890    /* Either an existing extension or the parking extension */
13891    if (referdata->attendedtransfer || ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
13892       if (sip_debug_test_pvt(transferer)) {
13893          ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
13894       }
13895       /* We are ready to transfer to the extension */
13896       return 0;
13897    } 
13898    if (sip_debug_test_pvt(transferer))
13899       ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
13900 
13901    /* Failure, we can't find this extension */
13902    return -1;
13903 }
13904 
13905 
13906 /*! \brief Call transfer support (old way, deprecated by the IETF)
13907  * \note does not account for SIPS: uri requirements, nor check transport
13908  */
13909 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
13910 {
13911    char tmp[256] = "", *c, *a;
13912    struct sip_request *req = oreq ? oreq : &p->initreq;
13913    struct sip_refer *referdata = NULL;
13914    const char *transfer_context = NULL;
13915    
13916    if (!p->refer && !sip_refer_allocate(p))
13917       return -1;
13918 
13919    referdata = p->refer;
13920 
13921    ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
13922    c = get_in_brackets(tmp);
13923 
13924    if (sip_cfg.pedanticsipchecking)
13925       ast_uri_decode(c);
13926 
13927    if (!strncasecmp(c, "sip:", 4)) {
13928       c += 4;
13929    } else if (!strncasecmp(c, "sips:", 5)) {
13930       c += 5;
13931    } else {
13932       ast_log(LOG_WARNING, "Huh?  Not a SIP header in Also: transfer (%s)?\n", c);
13933       return -1;
13934    }
13935 
13936    if ((a = strchr(c, ';')))  /* Remove arguments */
13937       *a = '\0';
13938    
13939    if ((a = strchr(c, '@'))) {   /* Separate Domain */
13940       *a++ = '\0';
13941       ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
13942    }
13943    
13944    if (sip_debug_test_pvt(p))
13945       ast_verbose("Looking for %s in %s\n", c, p->context);
13946 
13947    if (p->owner)  /* Mimic behaviour in res_features.c */
13948       transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
13949 
13950    /* By default, use the context in the channel sending the REFER */
13951    if (ast_strlen_zero(transfer_context)) {
13952       transfer_context = S_OR(p->owner->macrocontext,
13953                S_OR(p->context, sip_cfg.default_context));
13954    }
13955    if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
13956       /* This is a blind transfer */
13957       ast_debug(1, "SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
13958       ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
13959       ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
13960       ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
13961       referdata->refer_call = dialog_unref(referdata->refer_call, "unreffing referdata->refer_call");
13962       /* Set new context */
13963       ast_string_field_set(p, context, transfer_context);
13964       return 0;
13965    } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
13966       return 1;
13967    }
13968 
13969    return -1;
13970 }
13971 
13972 /*! \brief check received= and rport= in a SIP response.
13973  * If we get a response with received= and/or rport= in the Via:
13974  * line, use them as 'p->ourip' (see RFC 3581 for rport,
13975  * and RFC 3261 for received).
13976  * Using these two fields SIP can produce the correct
13977  * address and port in the SIP headers without the need for STUN.
13978  * The address part is also reused for the media sessions.
13979  * Note that ast_sip_ouraddrfor() still rewrites p->ourip
13980  * if you specify externip/seternaddr/stunaddr.
13981  */
13982 static attribute_unused void check_via_response(struct sip_pvt *p, struct sip_request *req)
13983 {
13984    char via[256];
13985    char *cur, *opts;
13986 
13987    ast_copy_string(via, get_header(req, "Via"), sizeof(via));
13988 
13989    /* Work on the leftmost value of the topmost Via header */
13990    opts = strchr(via, ',');
13991    if (opts)
13992       *opts = '\0';
13993 
13994    /* parse all relevant options */
13995    opts = strchr(via, ';');
13996    if (!opts)
13997       return;  /* no options to parse */
13998    *opts++ = '\0';
13999    while ( (cur = strsep(&opts, ";")) ) {
14000       if (!strncmp(cur, "rport=", 6)) {
14001          int port = strtol(cur+6, NULL, 10);
14002          /* XXX add error checking */
14003          p->ourip.sin_port = ntohs(port);
14004       } else if (!strncmp(cur, "received=", 9)) {
14005          if (ast_parse_arg(cur+9, PARSE_INADDR, &p->ourip))
14006             ;  /* XXX add error checking */
14007       }
14008    }
14009 }
14010 
14011 /*! \brief check Via: header for hostname, port and rport request/answer */
14012 static void check_via(struct sip_pvt *p, struct sip_request *req)
14013 {
14014    char via[512];
14015    char *c, *pt, *maddr;
14016    struct hostent *hp;
14017    struct ast_hostent ahp;
14018 
14019    ast_copy_string(via, get_header(req, "Via"), sizeof(via));
14020 
14021    /* Work on the leftmost value of the topmost Via header */
14022    c = strchr(via, ',');
14023    if (c)
14024       *c = '\0';
14025 
14026    /* Check for rport */
14027    c = strstr(via, ";rport");
14028    if (c && (c[6] != '=')) /* rport query, not answer */
14029       ast_set_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT);
14030 
14031    /* Check for maddr */
14032    maddr = strstr(via, "maddr=");
14033    if (maddr) {
14034       maddr += 6;
14035       c = maddr + strspn(maddr, "0123456789.");
14036       *c = '\0';
14037    }
14038 
14039    c = strchr(via, ';');
14040    if (c)
14041       *c = '\0';
14042 
14043    c = strchr(via, ' ');
14044    if (c) {
14045       *c = '\0';
14046       c = ast_skip_blanks(c+1);
14047       if (strcasecmp(via, "SIP/2.0/UDP") && strcasecmp(via, "SIP/2.0/TCP") && strcasecmp(via, "SIP/2.0/TLS")) {
14048          ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
14049          return;
14050       }
14051       pt = strchr(c, ':');
14052       if (pt)
14053          *pt++ = '\0';  /* remember port pointer */
14054       /* Use maddr if found */
14055       if (maddr)
14056          c = maddr;
14057       hp = ast_gethostbyname(c, &ahp);
14058       if (!hp) {
14059          ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
14060          return;
14061       }
14062       memset(&p->sa, 0, sizeof(p->sa));
14063       p->sa.sin_family = AF_INET;
14064       memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
14065       p->sa.sin_port = htons(port_str2int(pt, STANDARD_SIP_PORT));
14066 
14067       if (sip_debug_test_pvt(p)) {
14068          const struct sockaddr_in *dst = sip_real_dst(p);
14069          ast_verbose("Sending to %s : %d (%s)\n", ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), sip_nat_mode(p));
14070       }
14071    }
14072 }
14073 
14074 /*! \brief  Get caller id name from SIP headers */
14075 static char *get_calleridname(const char *input, char *output, size_t outputsize)
14076 {
14077    const char *end = strchr(input, '<');  /* first_bracket */
14078    const char *tmp = strchr(input, '"');  /* first quote */
14079    int bytes = 0;
14080    int maxbytes = outputsize - 1;
14081 
14082    if (!end || end == input)  /* we require a part in brackets */
14083       return NULL;
14084 
14085    end--; /* move just before "<" */
14086 
14087    if (tmp && tmp <= end) {
14088       /* The quote (tmp) precedes the bracket (end+1).
14089        * Find the matching quote and return the content.
14090        */
14091       end = strchr(tmp+1, '"');
14092       if (!end)
14093          return NULL;
14094       bytes = (int) (end - tmp);
14095       /* protect the output buffer */
14096       if (bytes > maxbytes)
14097          bytes = maxbytes;
14098       ast_copy_string(output, tmp + 1, bytes);
14099    } else {
14100       /* No quoted string, or it is inside brackets. */
14101       /* clear the empty characters in the begining*/
14102       input = ast_skip_blanks(input);
14103       /* clear the empty characters in the end */
14104       while(*end && *end < 33 && end > input)
14105          end--;
14106       if (end >= input) {
14107          bytes = (int) (end - input) + 2;
14108          /* protect the output buffer */
14109          if (bytes > maxbytes)
14110             bytes = maxbytes;
14111          ast_copy_string(output, input, bytes);
14112       } else
14113          return NULL;
14114    }
14115    return output;
14116 }
14117 
14118 /*! \brief  Get caller id number from Remote-Party-ID header field 
14119  * Returns true if number should be restricted (privacy setting found)
14120  * output is set to NULL if no number found
14121  */
14122 static int get_rpid_num(const char *input, char *output, int maxlen)
14123 {
14124    char *start;
14125    char *end;
14126 
14127    start = strchr(input, ':');
14128    if (!start) {
14129       output[0] = '\0';
14130       return 0;
14131    }
14132    start++;
14133 
14134    /* we found "number" */
14135    ast_copy_string(output, start, maxlen);
14136    output[maxlen-1] = '\0';
14137 
14138    end = strchr(output, '@');
14139    if (end)
14140       *end = '\0';
14141    else
14142       output[0] = '\0';
14143    if (strstr(input, "privacy=full") || strstr(input, "privacy=uri"))
14144       return AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
14145 
14146    return 0;
14147 }
14148 
14149 
14150 /*! \brief helper function for check_{user|peer}_ok() */
14151 static void replace_cid(struct sip_pvt *p, const char *rpid_num, const char *calleridname)
14152 {
14153    /* replace callerid if rpid found, and not restricted */
14154    if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
14155       char *tmp = ast_strdupa(rpid_num); /* XXX the copy can be done later */
14156       if (!ast_strlen_zero(calleridname))
14157          ast_string_field_set(p, cid_name, calleridname);
14158       if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
14159          ast_shrink_phone_number(tmp);
14160       ast_string_field_set(p, cid_num, tmp);
14161    }
14162 }
14163 
14164 /*! \brief Validate device authentication */
14165 static enum check_auth_result check_peer_ok(struct sip_pvt *p, char *of,
14166    struct sip_request *req, int sipmethod, struct sockaddr_in *sin,
14167    struct sip_peer **authpeer,
14168    enum xmittype reliable,
14169    char *rpid_num, char *calleridname, char *uri2)
14170 {
14171    enum check_auth_result res;
14172    int debug=sip_debug_test_addr(sin);
14173    struct sip_peer *peer;
14174 
14175    if (sipmethod == SIP_SUBSCRIBE) {
14176       /* For subscribes, match on device name only; for other methods,
14177       * match on IP address-port of the incoming request.
14178       */
14179       peer = find_peer(of, NULL, TRUE, FINDALLDEVICES, FALSE, 0);
14180    } else {
14181       /* First find devices based on username (avoid all type=peer's) */
14182       peer = find_peer(of, NULL, TRUE, FINDUSERS, FALSE, 0);
14183 
14184       /* Then find devices based on IP */
14185       if (!peer) {
14186          peer = find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
14187       }
14188    }
14189 
14190    if (!peer) {
14191       if (debug)
14192          ast_verbose("No matching peer for '%s' from '%s:%d'\n",
14193             of, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
14194       return AUTH_DONT_KNOW;
14195    }
14196    if (!ast_apply_ha(peer->ha, sin)) {
14197       ast_debug(2, "Found peer '%s' for '%s', but fails host access\n", peer->name, of);
14198       unref_peer(peer, "unref_peer: check_peer_ok: from find_peer call, early return of AUTH_ACL_FAILED");
14199       return AUTH_ACL_FAILED;
14200    }
14201    if (debug)
14202       ast_verbose("Found peer '%s' for '%s' from %s:%d\n",
14203          peer->name, of, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
14204 
14205    /* XXX what about p->prefs = peer->prefs; ? */
14206    /* Set Frame packetization */
14207    if (p->rtp) {
14208       ast_rtp_codec_setpref(p->rtp, &peer->prefs);
14209       p->autoframing = peer->autoframing;
14210    }
14211 
14212    /* Take the peer */
14213    ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
14214    ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
14215 
14216    if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && p->udptl) {
14217       p->t38_maxdatagram = peer->t38_maxdatagram;
14218       set_t38_capabilities(p);
14219    }
14220 
14221    /* Copy SIP extensions profile to peer */
14222    /* XXX is this correct before a successful auth ? */
14223    if (p->sipoptions)
14224       peer->sipoptions = p->sipoptions;
14225 
14226    replace_cid(p, rpid_num, calleridname);
14227    do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE));
14228 
14229    ast_string_field_set(p, peersecret, peer->secret);
14230    ast_string_field_set(p, peermd5secret, peer->md5secret);
14231    ast_string_field_set(p, subscribecontext, peer->subscribecontext);
14232    ast_string_field_set(p, mohinterpret, peer->mohinterpret);
14233    ast_string_field_set(p, mohsuggest, peer->mohsuggest);
14234    ast_string_field_set(p, parkinglot, peer->parkinglot);
14235    if (peer->callingpres)  /* Peer calling pres setting will override RPID */
14236       p->callingpres = peer->callingpres;
14237    if (peer->maxms && peer->lastms)
14238       p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
14239    else
14240       p->timer_t1 = peer->timer_t1;
14241  
14242    /* Set timer B to control transaction timeouts */
14243    if (peer->timer_b)
14244       p->timer_b = peer->timer_b;
14245    else
14246       p->timer_b = 64 * p->timer_t1;
14247  
14248    if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
14249       /* Pretend there is no required authentication */
14250       ast_string_field_set(p, peersecret, NULL);
14251       ast_string_field_set(p, peermd5secret, NULL);
14252    }
14253    if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, req->ignore))) {
14254       ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
14255       ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
14256       /* If we have a call limit, set flag */
14257       if (peer->call_limit)
14258          ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
14259       ast_string_field_set(p, peername, peer->name);
14260       ast_string_field_set(p, authname, peer->name);
14261 
14262       if (sipmethod == SIP_INVITE) {
14263          /* copy channel vars */
14264          p->chanvars = copy_vars(peer->chanvars);
14265       }
14266 
14267       if (authpeer) {
14268          ao2_t_ref(peer, 1, "copy pointer into (*authpeer)");
14269          (*authpeer) = peer;  /* Add a ref to the object here, to keep it in memory a bit longer if it is realtime */
14270       }
14271 
14272       if (!ast_strlen_zero(peer->username)) {
14273          ast_string_field_set(p, username, peer->username);
14274          /* Use the default username for authentication on outbound calls */
14275          /* XXX this takes the name from the caller... can we override ? */
14276          ast_string_field_set(p, authname, peer->username);
14277       }
14278       if (!ast_strlen_zero(peer->cid_num)) {
14279          char *tmp = ast_strdupa(peer->cid_num);
14280          if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
14281             ast_shrink_phone_number(tmp);
14282          ast_string_field_set(p, cid_num, tmp);
14283       }
14284       if (!ast_strlen_zero(peer->cid_name)) 
14285          ast_string_field_set(p, cid_name, peer->cid_name);
14286       ast_string_field_set(p, fullcontact, peer->fullcontact);
14287       if (!ast_strlen_zero(peer->context))
14288          ast_string_field_set(p, context, peer->context);
14289       ast_string_field_set(p, peersecret, peer->secret);
14290       ast_string_field_set(p, peermd5secret, peer->md5secret);
14291       ast_string_field_set(p, language, peer->language);
14292       ast_string_field_set(p, accountcode, peer->accountcode);
14293       p->amaflags = peer->amaflags;
14294       p->callgroup = peer->callgroup;
14295       p->pickupgroup = peer->pickupgroup;
14296       p->capability = peer->capability;
14297       p->prefs = peer->prefs;
14298       p->jointcapability = peer->capability;
14299       if (p->peercapability)
14300          p->jointcapability &= p->peercapability;
14301       p->maxcallbitrate = peer->maxcallbitrate;
14302       if (!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) &&
14303             (!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
14304                !(p->capability & AST_FORMAT_VIDEO_MASK)) &&
14305             p->vrtp) {
14306          ast_rtp_destroy(p->vrtp);
14307          p->vrtp = NULL;
14308       }
14309       if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) || !(p->capability & AST_FORMAT_TEXT_MASK)) && p->trtp) {
14310          ast_rtp_destroy(p->trtp);
14311          p->trtp = NULL;
14312       }
14313       if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
14314           (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
14315          p->noncodeccapability |= AST_RTP_DTMF;
14316       else
14317          p->noncodeccapability &= ~AST_RTP_DTMF;
14318       p->jointnoncodeccapability = p->noncodeccapability;
14319    }
14320    unref_peer(peer, "check_peer_ok: unref_peer: tossing temp ptr to peer from find_peer");
14321    return res;
14322 }
14323 
14324 
14325 /*! \brief  Check if matching user or peer is defined 
14326    Match user on From: user name and peer on IP/port
14327    This is used on first invite (not re-invites) and subscribe requests 
14328     \return 0 on success, non-zero on failure
14329 */
14330 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
14331                      int sipmethod, char *uri, enum xmittype reliable,
14332                      struct sockaddr_in *sin, struct sip_peer **authpeer)
14333 {
14334    char from[256];
14335    char *dummy;   /* dummy return value for parse_uri */
14336    char *domain;  /* dummy return value for parse_uri */
14337    char *of;
14338    char rpid_num[50];
14339    const char *rpid;
14340    enum check_auth_result res;
14341    char calleridname[50];
14342    char *uri2 = ast_strdupa(uri);
14343 
14344    terminate_uri(uri2); /* trim extra stuff */
14345 
14346    ast_copy_string(from, get_header(req, "From"), sizeof(from));
14347    if (sip_cfg.pedanticsipchecking)
14348       ast_uri_decode(from);
14349    /* XXX here tries to map the username for invite things */
14350    memset(calleridname, 0, sizeof(calleridname));
14351    get_calleridname(from, calleridname, sizeof(calleridname));
14352    if (calleridname[0])
14353       ast_string_field_set(p, cid_name, calleridname);
14354 
14355    rpid = get_header(req, "Remote-Party-ID");
14356    memset(rpid_num, 0, sizeof(rpid_num));
14357    if (!ast_strlen_zero(rpid)) 
14358       p->callingpres = get_rpid_num(rpid, rpid_num, sizeof(rpid_num));
14359 
14360    of = get_in_brackets(from);
14361    if (ast_strlen_zero(p->exten)) {
14362       char *t = uri2;
14363       if (!strncasecmp(t, "sip:", 4))
14364          t+= 4;
14365       else if (!strncasecmp(t, "sips:", 5))
14366          t += 5;
14367       ast_string_field_set(p, exten, t);
14368       t = strchr(p->exten, '@');
14369       if (t)
14370          *t = '\0';
14371       if (ast_strlen_zero(p->our_contact))
14372          build_contact(p);
14373    }
14374    /* save the URI part of the From header */
14375    ast_string_field_set(p, from, of);
14376 
14377    /* ignore all fields but name */
14378    if (parse_uri(of, "sip:,sips:", &of, &dummy, &domain, &dummy, &dummy, NULL)) {
14379       ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
14380    }
14381 
14382    if (ast_strlen_zero(of)) {
14383       /* XXX note: the original code considered a missing @host
14384        * as a username-only URI. The SIP RFC (19.1.1) says that
14385        * this is wrong, and it should be considered as a domain-only URI.
14386        * For backward compatibility, we keep this block, but it is
14387        * really a mistake and should go away.
14388        */
14389       of = domain;
14390    } else {
14391       char *tmp = ast_strdupa(of);
14392       /* We need to be able to handle auth-headers looking like
14393          <sip:8164444422;phone-context=+1@1.2.3.4:5060;user=phone;tag=SDadkoa01-gK0c3bdb43>
14394       */
14395       tmp = strsep(&tmp, ";");
14396       if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
14397          ast_shrink_phone_number(tmp);
14398       ast_string_field_set(p, cid_num, tmp);
14399    }
14400 
14401    if (global_match_auth_username) {
14402       /*
14403        * XXX This is experimental code to grab the search key from the
14404        * Auth header's username instead of the 'From' name, if available.
14405        * Do not enable this block unless you understand the side effects (if any!)
14406        * Note, the search for "username" should be done in a more robust way.
14407        * Note2, at the moment we check both fields, though maybe we should
14408        * pick one or another depending on the request ? XXX
14409        */
14410       const char *hdr = get_header(req, "Authorization");
14411       if (ast_strlen_zero(hdr))
14412          hdr = get_header(req, "Proxy-Authorization");
14413 
14414       if ( !ast_strlen_zero(hdr) && (hdr = strstr(hdr, "username=\"")) ) {
14415          ast_copy_string(from, hdr + strlen("username=\""), sizeof(from));
14416          of = from;
14417          of = strsep(&of, "\"");
14418       }
14419    }
14420 
14421    res = check_peer_ok(p, of, req, sipmethod, sin,
14422          authpeer, reliable, rpid_num, calleridname, uri2);
14423    if (res != AUTH_DONT_KNOW)
14424       return res;
14425 
14426    /* Finally, apply the guest policy */
14427    if (sip_cfg.allowguest) {
14428       replace_cid(p, rpid_num, calleridname);
14429       res = AUTH_SUCCESSFUL;
14430    } else if (sip_cfg.alwaysauthreject)
14431       res = AUTH_FAKE_AUTH; /* reject with fake authorization request */
14432    else
14433       res = AUTH_SECRET_FAILED; /* we don't want any guests, authentication will fail */
14434 
14435 
14436    if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT)) {
14437       ast_set_flag(&p->flags[0], SIP_NAT_ROUTE);
14438    }
14439 
14440    return res;
14441 }
14442 
14443 /*! \brief  Find user 
14444    If we get a match, this will add a reference pointer to the user object in ASTOBJ, that needs to be unreferenced
14445 */
14446 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin)
14447 {
14448    return check_user_full(p, req, sipmethod, uri, reliable, sin, NULL);
14449 }
14450 
14451 /*! \brief  Get text out of a SIP MESSAGE packet */
14452 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline)
14453 {
14454    int x;
14455    int y;
14456 
14457    buf[0] = '\0';
14458    /*XXX isn't strlen(buf) going to always be 0? */
14459    y = len - strlen(buf) - 5;
14460    if (y < 0)
14461       y = 0;
14462    for (x = 0; x < req->lines; x++) {
14463       char *line = REQ_OFFSET_TO_STR(req, line[x]);
14464       strncat(buf, line, y); /* safe */
14465       y -= strlen(line) + 1;
14466       if (y < 0)
14467          y = 0;
14468       if (y != 0 && addnewline)
14469          strcat(buf, "\n"); /* safe */
14470    }
14471    return 0;
14472 }
14473 
14474 
14475 /*! \brief  Receive SIP MESSAGE method messages
14476 \note We only handle messages within current calls currently 
14477    Reference: RFC 3428 */
14478 static void receive_message(struct sip_pvt *p, struct sip_request *req)
14479 {
14480    char buf[1400];   
14481    struct ast_frame f;
14482    const char *content_type = get_header(req, "Content-Type");
14483 
14484    if (strncmp(content_type, "text/plain", strlen("text/plain"))) { /* No text/plain attachment */
14485       transmit_response(p, "415 Unsupported Media Type", req); /* Good enough, or? */
14486       if (!p->owner)
14487          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14488       return;
14489    }
14490 
14491    if (get_msg_text(buf, sizeof(buf), req, FALSE)) {
14492       ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
14493       transmit_response(p, "202 Accepted", req);
14494       if (!p->owner)
14495          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14496       return;
14497    }
14498 
14499    if (p->owner) {
14500       if (sip_debug_test_pvt(p))
14501          ast_verbose("SIP Text message received: '%s'\n", buf);
14502       memset(&f, 0, sizeof(f));
14503       f.frametype = AST_FRAME_TEXT;
14504       f.subclass = 0;
14505       f.offset = 0;
14506       f.data.ptr = buf;
14507       f.datalen = strlen(buf);
14508       ast_queue_frame(p->owner, &f);
14509       transmit_response(p, "202 Accepted", req); /* We respond 202 accepted, since we relay the message */
14510       return;
14511    }
14512 
14513    /* Message outside of a call, we do not support that */
14514    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);
14515    transmit_response(p, "405 Method Not Allowed", req);
14516    sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14517    return;
14518 }
14519 
14520 /*! \brief  CLI Command to show calls within limits set by call_limit */
14521 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14522 {
14523 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
14524 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
14525    char ilimits[40];
14526    char iused[40];
14527    int showall = FALSE;
14528    struct ao2_iterator i;
14529    struct sip_peer *peer;
14530    
14531    switch (cmd) {
14532    case CLI_INIT:
14533       e->command = "sip show inuse";
14534       e->usage =
14535          "Usage: sip show inuse [all]\n"
14536          "       List all SIP devices usage counters and limits.\n"
14537          "       Add option \"all\" to show all devices, not only those with a limit.\n";
14538       return NULL;
14539    case CLI_GENERATE:
14540       return NULL;
14541    }
14542 
14543    if (a->argc < 3) 
14544       return CLI_SHOWUSAGE;
14545 
14546    if (a->argc == 4 && !strcmp(a->argv[3], "all")) 
14547       showall = TRUE;
14548    
14549    ast_cli(a->fd, FORMAT, "* Peer name", "In use", "Limit");
14550 
14551    i = ao2_iterator_init(peers, 0);
14552    while ((peer = ao2_t_iterator_next(&i, "iterate thru peer table"))) {
14553       ao2_lock(peer);
14554       if (peer->call_limit)
14555          snprintf(ilimits, sizeof(ilimits), "%d", peer->call_limit);
14556       else 
14557          ast_copy_string(ilimits, "N/A", sizeof(ilimits));
14558       snprintf(iused, sizeof(iused), "%d/%d/%d", peer->inUse, peer->inRinging, peer->onHold);
14559       if (showall || peer->call_limit)
14560          ast_cli(a->fd, FORMAT2, peer->name, iused, ilimits);
14561       ao2_unlock(peer);
14562       unref_peer(peer, "toss iterator pointer");
14563    }
14564    ao2_iterator_destroy(&i);
14565 
14566    return CLI_SUCCESS;
14567 #undef FORMAT
14568 #undef FORMAT2
14569 }
14570 
14571 
14572 /*! \brief Convert transfer mode to text string */
14573 static char *transfermode2str(enum transfermodes mode)
14574 {
14575    if (mode == TRANSFER_OPENFORALL)
14576       return "open";
14577    else if (mode == TRANSFER_CLOSED)
14578       return "closed";
14579    return "strict";
14580 }
14581 
14582 static struct _map_x_s natmodes[] = {
14583    { SIP_NAT_NEVER,        "No"},
14584    { SIP_NAT_ROUTE,        "Route"},
14585    { SIP_NAT_ALWAYS,       "Always"},
14586    { SIP_NAT_RFC3581,      "RFC3581"},
14587    { -1,                   NULL}, /* terminator */
14588 };
14589 
14590 /*! \brief  Convert NAT setting to text string */
14591 static const char *nat2str(int nat)
14592 {
14593    return map_x_s(natmodes, nat, "Unknown");
14594 }
14595 
14596 #ifdef NOTUSED
14597 /* OEJ: This is not used, but may be useful in the future, so I don't want to 
14598    delete it. Keeping it enabled generates compiler warnings.
14599  */
14600 
14601 static struct _map_x_s natcfgmodes[] = {
14602    { SIP_NAT_NEVER,        "never"},
14603    { SIP_NAT_ROUTE,        "route"},
14604    { SIP_NAT_ALWAYS,       "yes"},
14605    { SIP_NAT_RFC3581,      "no"},
14606    { -1,                   NULL}, /* terminator */
14607 };
14608 
14609 /*! \brief  Convert NAT setting to text string appropriate for config files */
14610 static const char *nat2strconfig(int nat)
14611 {
14612    return map_x_s(natcfgmodes, nat, "Unknown");
14613 }
14614 #endif
14615 
14616 /*! \brief  Report Peer status in character string
14617  *  \return 0 if peer is unreachable, 1 if peer is online, -1 if unmonitored
14618  */
14619 
14620 
14621 /* Session-Timer Modes */
14622 static struct _map_x_s stmodes[] = {
14623         { SESSION_TIMER_MODE_ACCEPT,    "Accept"},
14624         { SESSION_TIMER_MODE_ORIGINATE, "Originate"},
14625         { SESSION_TIMER_MODE_REFUSE,    "Refuse"},
14626         { -1,                           NULL},
14627 };
14628 
14629 static const char *stmode2str(enum st_mode m)
14630 {
14631    return map_x_s(stmodes, m, "Unknown");
14632 }
14633 
14634 static enum st_mode str2stmode(const char *s)
14635 {
14636    return map_s_x(stmodes, s, -1);
14637 }
14638 
14639 /* Session-Timer Refreshers */
14640 static struct _map_x_s strefreshers[] = {
14641         { SESSION_TIMER_REFRESHER_AUTO,     "auto"},
14642         { SESSION_TIMER_REFRESHER_UAC,      "uac"},
14643         { SESSION_TIMER_REFRESHER_UAS,      "uas"},
14644         { -1,                               NULL},
14645 };
14646 
14647 static const char *strefresher2str(enum st_refresher r)
14648 {
14649    return map_x_s(strefreshers, r, "Unknown");
14650 }
14651 
14652 static enum st_refresher str2strefresher(const char *s)
14653 {
14654    return map_s_x(strefreshers, s, -1);
14655 }
14656 
14657 
14658 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
14659 {
14660    int res = 0;
14661    if (peer->maxms) {
14662       if (peer->lastms < 0) {
14663          ast_copy_string(status, "UNREACHABLE", statuslen);
14664       } else if (peer->lastms > peer->maxms) {
14665          snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
14666          res = 1;
14667       } else if (peer->lastms) {
14668          snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
14669          res = 1;
14670       } else {
14671          ast_copy_string(status, "UNKNOWN", statuslen);
14672       }
14673    } else { 
14674       ast_copy_string(status, "Unmonitored", statuslen);
14675       /* Checking if port is 0 */
14676       res = -1;
14677    }
14678    return res;
14679 }
14680 
14681 /*! \brief return Yes or No depending on the argument.
14682  * This is used in many places in CLI command, having a function to generate
14683  * this helps maintaining a consistent output (and possibly emitting the
14684  * output in other languages, at some point).
14685  */
14686 static const char *cli_yesno(int x)
14687 {
14688    return x ? "Yes" : "No";
14689 }
14690 
14691 /*! \brief  Show active TCP connections */
14692 static char *sip_show_tcp(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14693 {
14694    struct sip_threadinfo *th;
14695    struct ao2_iterator i;
14696 
14697 #define FORMAT2 "%-30.30s %3.6s %9.9s %6.6s\n"
14698 #define FORMAT  "%-30.30s %-6d %-9.9s %-6.6s\n"
14699 
14700    switch (cmd) {
14701    case CLI_INIT:
14702       e->command = "sip show tcp";
14703       e->usage =
14704          "Usage: sip show tcp\n"
14705          "       Lists all active TCP/TLS sessions.\n";
14706       return NULL;
14707    case CLI_GENERATE:
14708       return NULL;
14709    }
14710 
14711    if (a->argc != 3)
14712       return CLI_SHOWUSAGE;
14713 
14714    ast_cli(a->fd, FORMAT2, "Host", "Port", "Transport", "Type");
14715    i = ao2_iterator_init(threadt, 0);
14716    while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
14717       ast_cli(a->fd, FORMAT, ast_inet_ntoa(th->tcptls_session->remote_address.sin_addr), 
14718          ntohs(th->tcptls_session->remote_address.sin_port), 
14719          get_transport(th->type), 
14720          (th->tcptls_session->client ? "Client" : "Server"));
14721       ao2_t_ref(th, -1, "decrement ref from iterator");
14722    }
14723    ao2_iterator_destroy(&i);
14724    return CLI_SUCCESS;
14725 #undef FORMAT
14726 #undef FORMAT2
14727 }
14728 
14729 /*! \brief  CLI Command 'SIP Show Users' */
14730 static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14731 {
14732    regex_t regexbuf;
14733    int havepattern = FALSE;
14734    struct ao2_iterator user_iter;
14735    struct sip_peer *user;
14736 
14737 #define FORMAT  "%-25.25s  %-15.15s  %-15.15s  %-15.15s  %-5.5s%-10.10s\n"
14738 
14739    switch (cmd) {
14740    case CLI_INIT:
14741       e->command = "sip show users";
14742       e->usage =
14743          "Usage: sip show users [like <pattern>]\n"
14744          "       Lists all known SIP users.\n"
14745          "       Optional regular expression pattern is used to filter the user list.\n";
14746       return NULL;
14747    case CLI_GENERATE:
14748       return NULL;
14749    }
14750 
14751    switch (a->argc) {
14752    case 5:
14753       if (!strcasecmp(a->argv[3], "like")) {
14754          if (regcomp(&regexbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
14755             return CLI_SHOWUSAGE;
14756          havepattern = TRUE;
14757       } else
14758          return CLI_SHOWUSAGE;
14759    case 3:
14760       break;
14761    default:
14762       return CLI_SHOWUSAGE;
14763    }
14764 
14765    ast_cli(a->fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "NAT");
14766 
14767    user_iter = ao2_iterator_init(peers, 0);
14768    while ((user = ao2_iterator_next(&user_iter))) {
14769       ao2_lock(user);
14770       if (!(user->type & SIP_TYPE_USER)) {
14771          ao2_unlock(user);
14772          unref_peer(user, "sip show users");
14773          continue;
14774       }
14775 
14776       if (havepattern && regexec(&regexbuf, user->name, 0, NULL, 0)) {
14777          ao2_unlock(user);
14778          unref_peer(user, "sip show users");
14779          continue;
14780       }
14781 
14782       ast_cli(a->fd, FORMAT, user->name, 
14783          user->secret, 
14784          user->accountcode,
14785          user->context,
14786          cli_yesno(user->ha != NULL),
14787          nat2str(ast_test_flag(&user->flags[0], SIP_NAT)));
14788       ao2_unlock(user);
14789       unref_peer(user, "sip show users");
14790    }
14791    ao2_iterator_destroy(&user_iter);
14792 
14793    if (havepattern)
14794       regfree(&regexbuf);
14795 
14796    return CLI_SUCCESS;
14797 #undef FORMAT
14798 }
14799 
14800 /*! \brief Manager Action SIPShowRegistry description */
14801 static char mandescr_show_registry[] =
14802 "Description: Lists all registration requests and status\n"
14803 "Registrations will follow as separate events. followed by a final event called\n"
14804 "RegistrationsComplete.\n"
14805 "Variables: \n"
14806 "  ActionID: <id>       Action ID for this transaction. Will be returned.\n";
14807 
14808 /*! \brief Show SIP registrations in the manager API */
14809 static int manager_show_registry(struct mansession *s, const struct message *m)
14810 {
14811    const char *id = astman_get_header(m, "ActionID");
14812    char idtext[256] = "";
14813    int total = 0;
14814 
14815    if (!ast_strlen_zero(id))
14816       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
14817 
14818    astman_send_listack(s, m, "Registrations will follow", "start");
14819 
14820    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
14821       ASTOBJ_RDLOCK(iterator);
14822       astman_append(s,
14823          "Event: RegistryEntry\r\n"
14824          "%s"
14825          "Host: %s\r\n"
14826          "Port: %d\r\n"
14827          "Username: %s\r\n"
14828          "Refresh: %d\r\n"
14829          "State: %s\r\n"
14830          "RegistrationTime: %ld\r\n"
14831          "\r\n", idtext, iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT,
14832                  iterator->username, iterator->refresh, regstate2str(iterator->regstate), (long) iterator->regtime.tv_sec);
14833       ASTOBJ_UNLOCK(iterator);
14834       total++;
14835    } while(0));
14836 
14837    astman_append(s,
14838       "Event: RegistrationsComplete\r\n"
14839       "EventList: Complete\r\n"
14840       "ListItems: %d\r\n"
14841       "%s"
14842       "\r\n", total, idtext);
14843    
14844    return 0;
14845 }
14846 
14847 static char mandescr_show_peers[] = 
14848 "Description: Lists SIP peers in text format with details on current status.\n"
14849 "Peerlist will follow as separate events, followed by a final event called\n"
14850 "PeerlistComplete.\n"
14851 "Variables: \n"
14852 "  ActionID: <id> Action ID for this transaction. Will be returned.\n";
14853 
14854 /*! \brief  Show SIP peers in the manager API */
14855 /*    Inspired from chan_iax2 */
14856 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
14857 {
14858    const char *id = astman_get_header(m, "ActionID");
14859    const char *a[] = {"sip", "show", "peers"};
14860    char idtext[256] = "";
14861    int total = 0;
14862 
14863    if (!ast_strlen_zero(id))
14864       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
14865 
14866    astman_send_listack(s, m, "Peer status list will follow", "start");
14867    /* List the peers in separate manager events */
14868    _sip_show_peers(-1, &total, s, m, 3, a);
14869    /* Send final confirmation */
14870    astman_append(s,
14871    "Event: PeerlistComplete\r\n"
14872    "EventList: Complete\r\n"
14873    "ListItems: %d\r\n"
14874    "%s"
14875    "\r\n", total, idtext);
14876    return 0;
14877 }
14878 
14879 /*! \brief  CLI Show Peers command */
14880 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14881 {
14882    switch (cmd) {
14883    case CLI_INIT:
14884       e->command = "sip show peers";
14885       e->usage =
14886          "Usage: sip show peers [like <pattern>]\n"
14887          "       Lists all known SIP peers.\n"
14888          "       Optional regular expression pattern is used to filter the peer list.\n";
14889       return NULL;
14890    case CLI_GENERATE:
14891       return NULL;
14892    }
14893 
14894    return _sip_show_peers(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
14895 }
14896 
14897 int peercomparefunc(const void *a, const void *b);
14898 
14899 int peercomparefunc(const void *a, const void *b)
14900 {
14901    struct sip_peer **ap = (struct sip_peer **)a;
14902    struct sip_peer **bp = (struct sip_peer **)b;
14903    return strcmp((*ap)->name, (*bp)->name);
14904 }
14905 
14906 
14907 /*! \brief Execute sip show peers command */
14908 static char *_sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
14909 {
14910    regex_t regexbuf;
14911    int havepattern = FALSE;
14912    struct sip_peer *peer;
14913    struct ao2_iterator i;
14914    
14915 /* the last argument is left-aligned, so we don't need a size anyways */
14916 #define FORMAT2 "%-25.25s  %-15.15s %-3.3s %-3.3s %-3.3s %-8s %-10s %s\n"
14917 #define FORMAT  "%-25.25s  %-15.15s %-3.3s %-3.3s %-3.3s %-8d %-10s %s\n"
14918 
14919    char name[256];
14920    int total_peers = 0;
14921    int peers_mon_online = 0;
14922    int peers_mon_offline = 0;
14923    int peers_unmon_offline = 0;
14924    int peers_unmon_online = 0;
14925    const char *id;
14926    char idtext[256] = "";
14927    int realtimepeers;
14928    int objcount = ao2_container_count(peers);
14929    struct sip_peer **peerarray;
14930    int k;
14931    
14932    
14933    realtimepeers = ast_check_realtime("sippeers");
14934    peerarray = ast_calloc(sizeof(struct sip_peer *), objcount);
14935 
14936    if (s) { /* Manager - get ActionID */
14937       id = astman_get_header(m, "ActionID");
14938       if (!ast_strlen_zero(id))
14939          snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
14940    }
14941 
14942    switch (argc) {
14943    case 5:
14944       if (!strcasecmp(argv[3], "like")) {
14945          if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
14946             return CLI_SHOWUSAGE;
14947          havepattern = TRUE;
14948       } else
14949          return CLI_SHOWUSAGE;
14950    case 3:
14951       break;
14952    default:
14953       return CLI_SHOWUSAGE;
14954    }
14955 
14956    if (!s) /* Normal list */
14957       ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Nat", "ACL", "Port", "Status", (realtimepeers ? "Realtime" : ""));
14958    
14959 
14960    i = ao2_iterator_init(peers, 0);
14961    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {  
14962       ao2_lock(peer);
14963 
14964       if (!(peer->type & SIP_TYPE_PEER)) {
14965          ao2_unlock(peer);
14966          unref_peer(peer, "unref peer because it's actually a user");
14967          continue;
14968       }
14969 
14970       if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0)) {
14971          objcount--;
14972          ao2_unlock(peer);
14973          unref_peer(peer, "toss iterator peer ptr before continue");
14974          continue;
14975       }
14976 
14977       peerarray[total_peers++] = peer;
14978       ao2_unlock(peer);
14979    }
14980    ao2_iterator_destroy(&i);
14981    
14982    qsort(peerarray, total_peers, sizeof(struct sip_peer *), peercomparefunc);
14983 
14984    for(k=0; k < total_peers; k++) {
14985       char status[20] = "";
14986       char srch[2000];
14987       char pstatus;
14988       peer = peerarray[k];
14989       
14990       ao2_lock(peer);
14991       if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0)) {
14992          ao2_unlock(peer);
14993          unref_peer(peer, "toss iterator peer ptr before continue");
14994          continue;
14995       }
14996 
14997       if (!ast_strlen_zero(peer->username) && !s)
14998          snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
14999       else
15000          ast_copy_string(name, peer->name, sizeof(name));
15001       
15002       pstatus = peer_status(peer, status, sizeof(status));
15003       if (pstatus == 1)
15004          peers_mon_online++;
15005       else if (pstatus == 0)
15006          peers_mon_offline++;
15007       else {
15008          if (peer->addr.sin_port == 0)
15009             peers_unmon_offline++;
15010          else
15011             peers_unmon_online++;
15012       }
15013 
15014       snprintf(srch, sizeof(srch), FORMAT, name,
15015          peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
15016          peer->host_dynamic ? " D " : "   ",    /* Dynamic or not? */
15017          ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? " N " : "   ", /* NAT=yes? */
15018          peer->ha ? " A " : "   ",  /* permit/deny */
15019          ntohs(peer->addr.sin_port), status,
15020          realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
15021 
15022       if (!s)  {/* Normal CLI list */
15023          ast_cli(fd, FORMAT, name, 
15024          peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
15025          peer->host_dynamic ? " D " : "   ",    /* Dynamic or not? */
15026          ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? " N " : "   ", /* NAT=yes? */
15027          peer->ha ? " A " : "   ",       /* permit/deny */
15028          
15029          ntohs(peer->addr.sin_port), status,
15030          realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
15031       } else { /* Manager format */
15032          /* The names here need to be the same as other channels */
15033          astman_append(s, 
15034          "Event: PeerEntry\r\n%s"
15035          "Channeltype: SIP\r\n"
15036          "ObjectName: %s\r\n"
15037          "ChanObjectType: peer\r\n" /* "peer" or "user" */
15038          "IPaddress: %s\r\n"
15039          "IPport: %d\r\n"
15040          "Dynamic: %s\r\n"
15041          "Natsupport: %s\r\n"
15042          "VideoSupport: %s\r\n"
15043          "TextSupport: %s\r\n"
15044          "ACL: %s\r\n"
15045          "Status: %s\r\n"
15046          "RealtimeDevice: %s\r\n\r\n", 
15047          idtext,
15048          peer->name, 
15049          peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "-none-",
15050          ntohs(peer->addr.sin_port), 
15051          peer->host_dynamic ? "yes" : "no",  /* Dynamic or not? */
15052          ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? "yes" : "no",  /* NAT=yes? */
15053          ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no",  /* VIDEOSUPPORT=yes? */
15054          ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "yes" : "no",   /* TEXTSUPPORT=yes? */
15055          peer->ha ? "yes" : "no",       /* permit/deny */
15056          status,
15057          realtimepeers ? (peer->is_realtime ? "yes":"no") : "no");
15058       }
15059       ao2_unlock(peer);
15060       unref_peer(peer, "toss iterator peer ptr");
15061    }
15062    
15063    if (!s)
15064       ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
15065               total_peers, peers_mon_online, peers_mon_offline, peers_unmon_online, peers_unmon_offline);
15066 
15067    if (havepattern)
15068       regfree(&regexbuf);
15069 
15070    if (total)
15071       *total = total_peers;
15072    
15073    ast_free(peerarray);
15074    
15075    return CLI_SUCCESS;
15076 #undef FORMAT
15077 #undef FORMAT2
15078 }
15079 
15080 static int peer_dump_func(void *userobj, void *arg, int flags)
15081 {
15082    struct sip_peer *peer = userobj;
15083    int refc = ao2_t_ref(userobj, 0, "");
15084    int *fd = arg;
15085    
15086    ast_cli(*fd, "name: %s\ntype: peer\nobjflags: %d\nrefcount: %d\n\n", 
15087           peer->name, 0, refc);
15088    return 0;
15089 }
15090 
15091 static int dialog_dump_func(void *userobj, void *arg, int flags)
15092 {
15093    struct sip_pvt *pvt = userobj;
15094    int refc = ao2_t_ref(userobj, 0, "");
15095    int *fd = arg;
15096    
15097    ast_cli(*fd, "name: %s\ntype: dialog\nobjflags: %d\nrefcount: %d\n\n", 
15098           pvt->callid, 0, refc);
15099    return 0;
15100 }
15101 
15102 
15103 /*! \brief List all allocated SIP Objects (realtime or static) */
15104 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15105 {
15106    char tmp[256];
15107    
15108    switch (cmd) {
15109    case CLI_INIT:
15110       e->command = "sip show objects";
15111       e->usage =
15112          "Usage: sip show objects\n"
15113          "       Lists status of known SIP objects\n";
15114       return NULL;
15115    case CLI_GENERATE:
15116       return NULL;
15117    }  
15118 
15119    if (a->argc != 3)
15120       return CLI_SHOWUSAGE;
15121    ast_cli(a->fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
15122    ao2_t_callback(peers, OBJ_NODATA, peer_dump_func, &a->fd, "initiate ao2_callback to dump peers");
15123    ast_cli(a->fd, "-= Registry objects: %d =-\n\n", regobjs);
15124    ASTOBJ_CONTAINER_DUMP(a->fd, tmp, sizeof(tmp), &regl);
15125    ast_cli(a->fd, "-= Dialog objects:\n\n");
15126    ao2_t_callback(dialogs, OBJ_NODATA, dialog_dump_func, &a->fd, "initiate ao2_callback to dump dialogs");
15127    return CLI_SUCCESS;
15128 }
15129 /*! \brief Print call group and pickup group */
15130 static void  print_group(int fd, ast_group_t group, int crlf)
15131 {
15132    char buf[256];
15133    ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
15134 }
15135 
15136 /*! \brief mapping between dtmf flags and strings */
15137 static struct _map_x_s dtmfstr[] = {
15138    { SIP_DTMF_RFC2833,     "rfc2833" },
15139    { SIP_DTMF_INFO,        "info" },
15140    { SIP_DTMF_SHORTINFO,   "shortinfo" },
15141    { SIP_DTMF_INBAND,      "inband" },
15142    { SIP_DTMF_AUTO,        "auto" },
15143    { -1,                   NULL }, /* terminator */
15144 };
15145 
15146 /*! \brief Convert DTMF mode to printable string */
15147 static const char *dtmfmode2str(int mode)
15148 {
15149    return map_x_s(dtmfstr, mode, "<error>");
15150 }
15151 
15152 /*! \brief maps a string to dtmfmode, returns -1 on error */
15153 static int str2dtmfmode(const char *str)
15154 {
15155    return map_s_x(dtmfstr, str, -1);
15156 }
15157 
15158 static struct _map_x_s insecurestr[] = {
15159    { SIP_INSECURE_PORT,    "port" },
15160    { SIP_INSECURE_INVITE,  "invite" },
15161    { SIP_INSECURE_PORT | SIP_INSECURE_INVITE, "port,invite" },
15162    { 0,                    "no" },
15163    { -1,                   NULL }, /* terminator */
15164 };
15165 
15166 /*! \brief Convert Insecure setting to printable string */
15167 static const char *insecure2str(int mode)
15168 {
15169    return map_x_s(insecurestr, mode, "<error>");
15170 }
15171 
15172 /*! \brief Destroy disused contexts between reloads
15173    Only used in reload_config so the code for regcontext doesn't get ugly
15174 */
15175 static void cleanup_stale_contexts(char *new, char *old)
15176 {
15177    char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
15178 
15179    while ((oldcontext = strsep(&old, "&"))) {
15180       stalecontext = '\0';
15181       ast_copy_string(newlist, new, sizeof(newlist));
15182       stringp = newlist;
15183       while ((newcontext = strsep(&stringp, "&"))) {
15184          if (!strcmp(newcontext, oldcontext)) {
15185             /* This is not the context you're looking for */
15186             stalecontext = '\0';
15187             break;
15188          } else if (strcmp(newcontext, oldcontext)) {
15189             stalecontext = oldcontext;
15190          }
15191          
15192       }
15193       if (stalecontext)
15194          ast_context_destroy(ast_context_find(stalecontext), "SIP");
15195    }
15196 }
15197 
15198 /*! 
15199  * \brief Match dialogs that need to be destroyed
15200  *
15201  * \details This is used with ao2_callback to unlink/delete all dialogs that
15202  * are marked needdestroy. It will return CMP_MATCH for candidates, and they
15203  * will be unlinked.
15204  *
15205  * \todo Re-work this to improve efficiency.  Currently, this function is called
15206  * on _every_ dialog after processing _every_ incoming SIP/UDP packet, or
15207  * potentially even more often when the scheduler has entries to run.
15208  */
15209 
15210 static int dialog_needdestroy(void *dialogobj, void *arg, int flags) 
15211 {
15212    struct sip_pvt *dialog = dialogobj;
15213    time_t *t = arg;
15214 
15215    if (sip_pvt_trylock(dialog)) {
15216       /* Don't block the monitor thread.  This function is called often enough
15217        * that we can wait for the next time around. */
15218       return 0;
15219    }
15220    
15221    /* Check RTP timeouts and kill calls if we have a timeout set and do not get RTP */
15222    check_rtp_timeout(dialog, *t);
15223 
15224    /* If we have sessions that needs to be destroyed, do it now */
15225    /* Check if we have outstanding requests not responsed to or an active call
15226       - if that's the case, wait with destruction */
15227    if (dialog->needdestroy && !dialog->packets && !dialog->owner) {
15228       /* We absolutely cannot destroy the rtp struct while a bridge is active or we WILL crash */
15229       if (dialog->rtp && ast_rtp_get_bridged(dialog->rtp)) {
15230          ast_debug(2, "Bridge still active.  Delaying destruction of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
15231          sip_pvt_unlock(dialog);
15232          return 0;
15233       }
15234       
15235       if (dialog->vrtp && ast_rtp_get_bridged(dialog->vrtp)) {
15236          ast_debug(2, "Bridge still active.  Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
15237          sip_pvt_unlock(dialog);
15238          return 0;
15239       }
15240 
15241       sip_pvt_unlock(dialog);
15242       /* no, the unlink should handle this: dialog_unref(dialog, "needdestroy: one more refcount decrement to allow dialog to be destroyed"); */
15243       /* the CMP_MATCH will unlink this dialog from the dialog hash table */
15244       dialog_unlink_all(dialog, TRUE, FALSE);
15245       return 0; /* the unlink_all should unlink this from the table, so.... no need to return a match */
15246    }
15247 
15248    sip_pvt_unlock(dialog);
15249 
15250    return 0;
15251 }
15252 
15253 /*! \brief Remove temporary realtime objects from memory (CLI) */
15254 /*! \todo XXXX Propably needs an overhaul after removal of the devices */
15255 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15256 {
15257    struct sip_peer *peer, *pi;
15258    int prunepeer = FALSE;
15259    int multi = FALSE;
15260    char *name = NULL;
15261    regex_t regexbuf;
15262    struct ao2_iterator i;
15263    static char *choices[] = { "all", "like", NULL };
15264    char *cmplt;
15265    
15266    if (cmd == CLI_INIT) {
15267       e->command = "sip prune realtime [peer|all]";
15268       e->usage =
15269          "Usage: sip prune realtime [peer [<name>|all|like <pattern>]|all]\n"
15270          "       Prunes object(s) from the cache.\n"
15271          "       Optional regular expression pattern is used to filter the objects.\n";
15272       return NULL;
15273    } else if (cmd == CLI_GENERATE) {
15274       if (a->pos == 4 && !strcasecmp(a->argv[3], "peer")) {
15275          cmplt = ast_cli_complete(a->word, choices, a->n);
15276          if (!cmplt)
15277             cmplt = complete_sip_peer(a->word, a->n - sizeof(choices), SIP_PAGE2_RTCACHEFRIENDS);
15278          return cmplt;
15279       }
15280       if (a->pos == 5 && !strcasecmp(a->argv[4], "like"))
15281          return complete_sip_peer(a->word, a->n, SIP_PAGE2_RTCACHEFRIENDS);
15282       return NULL;
15283    }
15284    switch (a->argc) {
15285    case 4:
15286       name = a->argv[3];
15287       /* we accept a name in position 3, but keywords are not good. */
15288       if (!strcasecmp(name, "peer") || !strcasecmp(name, "like"))
15289          return CLI_SHOWUSAGE;
15290       prunepeer = TRUE;
15291       if (!strcasecmp(name, "all")) {
15292          multi = TRUE;
15293          name = NULL;
15294       }
15295       /* else a single name, already set */
15296       break;
15297    case 5:
15298       /* sip prune realtime {peer|like} name */
15299       name = a->argv[4];
15300       if (!strcasecmp(a->argv[3], "peer"))
15301          prunepeer = TRUE;
15302       else if (!strcasecmp(a->argv[3], "like")) {
15303          prunepeer = TRUE;
15304          multi = TRUE;
15305       } else
15306          return CLI_SHOWUSAGE;
15307       if (!strcasecmp(name, "like"))
15308          return CLI_SHOWUSAGE;
15309       if (!multi && !strcasecmp(name, "all")) {
15310          multi = TRUE;
15311          name = NULL;
15312       }
15313       break;
15314    case 6:
15315       name = a->argv[5];
15316       multi = TRUE;
15317       /* sip prune realtime {peer} like name */
15318       if (strcasecmp(a->argv[4], "like"))
15319          return CLI_SHOWUSAGE;
15320       if (!strcasecmp(a->argv[3], "peer")) {
15321          prunepeer = TRUE;
15322       } else
15323          return CLI_SHOWUSAGE;
15324       break;
15325    default:
15326       return CLI_SHOWUSAGE;
15327    }
15328 
15329    if (multi && name) {
15330       if (regcomp(&regexbuf, name, REG_EXTENDED | REG_NOSUB))
15331          return CLI_SHOWUSAGE;
15332    }
15333 
15334    if (multi) {
15335       if (prunepeer) {
15336          int pruned = 0;
15337          
15338          i = ao2_iterator_init(peers, 0);
15339          while ((pi = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
15340             ao2_lock(pi);
15341             if (name && regexec(&regexbuf, pi->name, 0, NULL, 0)) {
15342                unref_peer(pi, "toss iterator peer ptr before continue");
15343                ao2_unlock(pi);
15344                continue;
15345             };
15346             if (ast_test_flag(&pi->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
15347                pi->the_mark = 1;
15348                pruned++;
15349             }
15350             ao2_unlock(pi);
15351             unref_peer(pi, "toss iterator peer ptr");
15352          }
15353          ao2_iterator_destroy(&i);
15354          if (pruned) {
15355             unlink_marked_peers_from_tables();
15356             ast_cli(a->fd, "%d peers pruned.\n", pruned);
15357          } else
15358             ast_cli(a->fd, "No peers found to prune.\n");
15359       }
15360    } else {
15361       if (prunepeer) {
15362          struct sip_peer tmp;
15363          ast_copy_string(tmp.name, name, sizeof(tmp.name));
15364          if ((peer = ao2_t_find(peers, &tmp, OBJ_POINTER | OBJ_UNLINK, "finding to unlink from peers"))) {
15365             if (peer->addr.sin_addr.s_addr) {
15366                ao2_t_unlink(peers_by_ip, peer, "unlinking peer from peers_by_ip also");
15367             }
15368             if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
15369                ast_cli(a->fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
15370                /* put it back! */
15371                ao2_t_link(peers, peer, "link peer into peer table");
15372                if (peer->addr.sin_addr.s_addr) {
15373                   ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
15374                }
15375                
15376             } else
15377                ast_cli(a->fd, "Peer '%s' pruned.\n", name);
15378             unref_peer(peer, "sip_prune_realtime: unref_peer: tossing temp peer ptr");
15379          } else
15380             ast_cli(a->fd, "Peer '%s' not found.\n", name);
15381       }
15382    }
15383 
15384    return CLI_SUCCESS;
15385 }
15386 
15387 /*! \brief Print codec list from preference to CLI/manager */
15388 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
15389 {
15390    int x, codec;
15391 
15392    for(x = 0; x < 32 ; x++) {
15393       codec = ast_codec_pref_index(pref, x);
15394       if (!codec)
15395          break;
15396       ast_cli(fd, "%s", ast_getformatname(codec));
15397       ast_cli(fd, ":%d", pref->framing[x]);
15398       if (x < 31 && ast_codec_pref_index(pref, x + 1))
15399          ast_cli(fd, ",");
15400    }
15401    if (!x)
15402       ast_cli(fd, "none");
15403 }
15404 
15405 /*! \brief Print domain mode to cli */
15406 static const char *domain_mode_to_text(const enum domain_mode mode)
15407 {
15408    switch (mode) {
15409    case SIP_DOMAIN_AUTO:
15410       return "[Automatic]";
15411    case SIP_DOMAIN_CONFIG:
15412       return "[Configured]";
15413    }
15414 
15415    return "";
15416 }
15417 
15418 /*! \brief CLI command to list local domains */
15419 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15420 {
15421    struct domain *d;
15422 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
15423 
15424    switch (cmd) {
15425    case CLI_INIT:
15426       e->command = "sip show domains";
15427       e->usage =
15428          "Usage: sip show domains\n"
15429          "       Lists all configured SIP local domains.\n"
15430          "       Asterisk only responds to SIP messages to local domains.\n";
15431       return NULL;
15432    case CLI_GENERATE:
15433       return NULL;
15434    }
15435 
15436    if (AST_LIST_EMPTY(&domain_list)) {
15437       ast_cli(a->fd, "SIP Domain support not enabled.\n\n");
15438       return CLI_SUCCESS;
15439    } else {
15440       ast_cli(a->fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
15441       AST_LIST_LOCK(&domain_list);
15442       AST_LIST_TRAVERSE(&domain_list, d, list)
15443          ast_cli(a->fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
15444             domain_mode_to_text(d->mode));
15445       AST_LIST_UNLOCK(&domain_list);
15446       ast_cli(a->fd, "\n");
15447       return CLI_SUCCESS;
15448    }
15449 }
15450 #undef FORMAT
15451 
15452 static char mandescr_show_peer[] = 
15453 "Description: Show one SIP peer with details on current status.\n"
15454 "Variables: \n"
15455 "  Peer: <name>           The peer name you want to check.\n"
15456 "  ActionID: <id>   Optional action ID for this AMI transaction.\n";
15457 
15458 /*! \brief Show SIP peers in the manager API  */
15459 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
15460 {
15461    const char *a[4];
15462    const char *peer;
15463 
15464    peer = astman_get_header(m, "Peer");
15465    if (ast_strlen_zero(peer)) {
15466       astman_send_error(s, m, "Peer: <name> missing.");
15467       return 0;
15468    }
15469    a[0] = "sip";
15470    a[1] = "show";
15471    a[2] = "peer";
15472    a[3] = peer;
15473 
15474    _sip_show_peer(1, -1, s, m, 4, a);
15475    astman_append(s, "\r\n\r\n" );
15476    return 0;
15477 }
15478 
15479 /*! \brief Show one peer in detail */
15480 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15481 {
15482    switch (cmd) {
15483    case CLI_INIT:
15484       e->command = "sip show peer";
15485       e->usage =
15486          "Usage: sip show peer <name> [load]\n"
15487          "       Shows all details on one SIP peer and the current status.\n"
15488          "       Option \"load\" forces lookup of peer in realtime storage.\n";
15489       return NULL;
15490    case CLI_GENERATE:
15491       return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
15492    }
15493    return _sip_show_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
15494 }
15495 
15496 /*! \brief Send qualify message to peer from cli or manager. Mostly for debugging. */
15497 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
15498 {
15499    struct sip_peer *peer;
15500    int load_realtime;
15501 
15502    if (argc < 4)
15503       return CLI_SHOWUSAGE;
15504 
15505    load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
15506    if ((peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0))) {
15507       sip_poke_peer(peer, 1);
15508       unref_peer(peer, "qualify: done with peer");
15509    } else if (type == 0) {
15510       ast_cli(fd, "Peer '%s' not found\n", argv[3]);
15511    } else {
15512       astman_send_error(s, m, "Peer not found");
15513    }
15514    return CLI_SUCCESS;
15515 }
15516 
15517 /*! \brief Qualify SIP peers in the manager API  */
15518 static int manager_sip_qualify_peer(struct mansession *s, const struct message *m)
15519 {
15520    const char *a[4];
15521    const char *peer;
15522 
15523    peer = astman_get_header(m, "Peer");
15524    if (ast_strlen_zero(peer)) {
15525       astman_send_error(s, m, "Peer: <name> missing.");
15526       return 0;
15527    }
15528    a[0] = "sip";
15529    a[1] = "qualify";
15530    a[2] = "peer";
15531    a[3] = peer;
15532 
15533    _sip_qualify_peer(1, -1, s, m, 4, a);
15534    astman_append(s, "\r\n\r\n" );
15535    return 0;
15536 }
15537 
15538 /*! \brief Send an OPTIONS packet to a SIP peer */
15539 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15540 {
15541    switch (cmd) {
15542    case CLI_INIT:
15543       e->command = "sip qualify peer";
15544       e->usage =
15545          "Usage: sip qualify peer <name> [load]\n"
15546          "       Requests a response from one SIP peer and the current status.\n"
15547          "       Option \"load\" forces lookup of peer in realtime storage.\n";
15548       return NULL;
15549    case CLI_GENERATE:
15550       return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
15551    }
15552    return _sip_qualify_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
15553 }
15554 
15555 /*! \brief list peer mailboxes to CLI */
15556 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer)
15557 {
15558    struct sip_mailbox *mailbox;
15559 
15560    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
15561       ast_str_append(mailbox_str, 0, "%s%s%s%s",
15562          mailbox->mailbox,
15563          ast_strlen_zero(mailbox->context) ? "" : "@",
15564          S_OR(mailbox->context, ""),
15565          AST_LIST_NEXT(mailbox, entry) ? "," : "");
15566    }
15567 }
15568 
15569 static struct _map_x_s faxecmodes[] = {
15570    { SIP_PAGE2_T38SUPPORT_UDPTL,       "None"},
15571    { SIP_PAGE2_T38SUPPORT_UDPTL_FEC,      "FEC"},
15572    { SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY,  "Redundancy"},
15573    { -1,                NULL},
15574 };
15575 
15576 static const char *faxec2str(int faxec)
15577 {
15578    return map_x_s(faxecmodes, faxec, "Unknown");
15579 }
15580 
15581 /*! \brief Show one peer in detail (main function) */
15582 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
15583 {
15584    char status[30] = "";
15585    char cbuf[256];
15586    struct sip_peer *peer;
15587    char codec_buf[512];
15588    struct ast_codec_pref *pref;
15589    struct ast_variable *v;
15590    struct sip_auth *auth;
15591    int x = 0, codec = 0, load_realtime;
15592    int realtimepeers;
15593 
15594    realtimepeers = ast_check_realtime("sippeers");
15595 
15596    if (argc < 4)
15597       return CLI_SHOWUSAGE;
15598 
15599    load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
15600    peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0);
15601 
15602    if (s) {    /* Manager */
15603       if (peer) {
15604          const char *id = astman_get_header(m, "ActionID");
15605 
15606          astman_append(s, "Response: Success\r\n");
15607          if (!ast_strlen_zero(id))
15608             astman_append(s, "ActionID: %s\r\n", id);
15609       } else {
15610          snprintf (cbuf, sizeof(cbuf), "Peer %s not found.", argv[3]);
15611          astman_send_error(s, m, cbuf);
15612          return CLI_SUCCESS;
15613       }
15614    }
15615    if (peer && type==0 ) { /* Normal listing */
15616       struct ast_str *mailbox_str = ast_str_alloca(512);
15617       ast_cli(fd, "\n\n");
15618       ast_cli(fd, "  * Name       : %s\n", peer->name);
15619       if (realtimepeers) { /* Realtime is enabled */
15620          ast_cli(fd, "  Realtime peer: %s\n", peer->is_realtime ? "Yes, cached" : "No");
15621       }
15622       ast_cli(fd, "  Secret       : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
15623       ast_cli(fd, "  MD5Secret    : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
15624       ast_cli(fd, "  Remote Secret: %s\n", ast_strlen_zero(peer->remotesecret)?"<Not set>":"<Set>");
15625       for (auth = peer->auth; auth; auth = auth->next) {
15626          ast_cli(fd, "  Realm-auth   : Realm %-15.15s User %-10.20s ", auth->realm, auth->username);
15627          ast_cli(fd, "%s\n", !ast_strlen_zero(auth->secret)?"<Secret set>":(!ast_strlen_zero(auth->md5secret)?"<MD5secret set>" : "<Not set>"));
15628       }
15629       ast_cli(fd, "  Context      : %s\n", peer->context);
15630       ast_cli(fd, "  Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
15631       ast_cli(fd, "  Language     : %s\n", peer->language);
15632       if (!ast_strlen_zero(peer->accountcode))
15633          ast_cli(fd, "  Accountcode  : %s\n", peer->accountcode);
15634       ast_cli(fd, "  AMA flags    : %s\n", ast_cdr_flags2str(peer->amaflags));
15635       ast_cli(fd, "  Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
15636       ast_cli(fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(peer->callingpres));
15637       if (!ast_strlen_zero(peer->fromuser))
15638          ast_cli(fd, "  FromUser     : %s\n", peer->fromuser);
15639       if (!ast_strlen_zero(peer->fromdomain))
15640          ast_cli(fd, "  FromDomain   : %s\n", peer->fromdomain);
15641       ast_cli(fd, "  Callgroup    : ");
15642       print_group(fd, peer->callgroup, 0);
15643       ast_cli(fd, "  Pickupgroup  : ");
15644       print_group(fd, peer->pickupgroup, 0);
15645       peer_mailboxes_to_str(&mailbox_str, peer);
15646       ast_cli(fd, "  Mailbox      : %s\n", mailbox_str->str);
15647       ast_cli(fd, "  VM Extension : %s\n", peer->vmexten);
15648       ast_cli(fd, "  LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
15649       ast_cli(fd, "  Call limit   : %d\n", peer->call_limit);
15650       if (peer->busy_level)
15651          ast_cli(fd, "  Busy level   : %d\n", peer->busy_level);
15652       ast_cli(fd, "  Dynamic      : %s\n", cli_yesno(peer->host_dynamic));
15653       ast_cli(fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
15654       ast_cli(fd, "  MaxCallBR    : %d kbps\n", peer->maxcallbitrate);
15655       ast_cli(fd, "  Expire       : %ld\n", ast_sched_when(sched, peer->expire));
15656       ast_cli(fd, "  Insecure     : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
15657       ast_cli(fd, "  Nat          : %s\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
15658       ast_cli(fd, "  ACL          : %s\n", cli_yesno(peer->ha != NULL));
15659       ast_cli(fd, "  T.38 support : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
15660       ast_cli(fd, "  T.38 EC mode : %s\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
15661       ast_cli(fd, "  T.38 MaxDtgrm: %d\n", peer->t38_maxdatagram);
15662       ast_cli(fd, "  DirectMedia  : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)));
15663       ast_cli(fd, "  PromiscRedir : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)));
15664       ast_cli(fd, "  User=Phone   : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)));
15665       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)));
15666       ast_cli(fd, "  Text Support : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)));
15667       ast_cli(fd, "  Ign SDP ver  : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_IGNORESDPVERSION)));
15668       ast_cli(fd, "  Trust RPID   : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_TRUSTRPID)));
15669       ast_cli(fd, "  Send RPID    : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_SENDRPID)));
15670       ast_cli(fd, "  Subscriptions: %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
15671       ast_cli(fd, "  Overlap dial : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP)));
15672       ast_cli(fd, "  Forward Loop : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_FORWARD_LOOP_DETECTED)));
15673       if (peer->outboundproxy)
15674          ast_cli(fd, "  Outb. proxy  : %s %s\n", ast_strlen_zero(peer->outboundproxy->name) ? "<not set>" : peer->outboundproxy->name,
15675                      peer->outboundproxy->force ? "(forced)" : "");
15676 
15677       /* - is enumerated */
15678       ast_cli(fd, "  DTMFmode     : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
15679       ast_cli(fd, "  Timer T1     : %d\n", peer->timer_t1);
15680       ast_cli(fd, "  Timer B      : %d\n", peer->timer_b);
15681       ast_cli(fd, "  ToHost       : %s\n", peer->tohost);
15682       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));
15683       ast_cli(fd, "  Defaddr->IP  : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
15684       ast_cli(fd, "  Prim.Transp. : %s\n", get_transport(peer->socket.type));
15685       ast_cli(fd, "  Allowed.Trsp : %s\n", get_transport_list(peer->transports)); 
15686       if (!ast_strlen_zero(global_regcontext))
15687          ast_cli(fd, "  Reg. exten   : %s\n", peer->regexten);
15688       ast_cli(fd, "  Def. Username: %s\n", peer->username);
15689       ast_cli(fd, "  SIP Options  : ");
15690       if (peer->sipoptions) {
15691          int lastoption = -1;
15692          for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
15693             if (sip_options[x].id != lastoption) {
15694                if (peer->sipoptions & sip_options[x].id)
15695                   ast_cli(fd, "%s ", sip_options[x].text);
15696                lastoption = x;
15697             }
15698          }
15699       } else
15700          ast_cli(fd, "(none)");
15701 
15702       ast_cli(fd, "\n");
15703       ast_cli(fd, "  Codecs       : ");
15704       ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
15705       ast_cli(fd, "%s\n", codec_buf);
15706       ast_cli(fd, "  Codec Order  : (");
15707       print_codec_to_cli(fd, &peer->prefs);
15708       ast_cli(fd, ")\n");
15709 
15710       ast_cli(fd, "  Auto-Framing :  %s \n", cli_yesno(peer->autoframing));
15711       ast_cli(fd, "  100 on REG   : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_REGISTERTRYING) ? "Yes" : "No");
15712       ast_cli(fd, "  Status       : ");
15713       peer_status(peer, status, sizeof(status));
15714       ast_cli(fd, "%s\n", status);
15715       ast_cli(fd, "  Useragent    : %s\n", peer->useragent);
15716       ast_cli(fd, "  Reg. Contact : %s\n", peer->fullcontact);
15717       ast_cli(fd, "  Qualify Freq : %d ms\n", peer->qualifyfreq);
15718       if (peer->chanvars) {
15719          ast_cli(fd, "  Variables    :\n");
15720          for (v = peer->chanvars ; v ; v = v->next)
15721             ast_cli(fd, "                 %s = %s\n", v->name, v->value);
15722       }
15723 
15724       ast_cli(fd, "  Sess-Timers  : %s\n", stmode2str(peer->stimer.st_mode_oper));
15725       ast_cli(fd, "  Sess-Refresh : %s\n", strefresher2str(peer->stimer.st_ref));
15726       ast_cli(fd, "  Sess-Expires : %d secs\n", peer->stimer.st_max_se);
15727       ast_cli(fd, "  Min-Sess     : %d secs\n", peer->stimer.st_min_se);
15728       ast_cli(fd, "  Parkinglot   : %s\n", peer->parkinglot);
15729       ast_cli(fd, "\n");
15730       peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer ptr");
15731    } else  if (peer && type == 1) { /* manager listing */
15732       char buffer[256];
15733       struct ast_str *mailbox_str = ast_str_alloca(512);
15734       astman_append(s, "Channeltype: SIP\r\n");
15735       astman_append(s, "ObjectName: %s\r\n", peer->name);
15736       astman_append(s, "ChanObjectType: peer\r\n");
15737       astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
15738       astman_append(s, "RemoteSecretExist: %s\r\n", ast_strlen_zero(peer->remotesecret)?"N":"Y");
15739       astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
15740       astman_append(s, "Context: %s\r\n", peer->context);
15741       astman_append(s, "Language: %s\r\n", peer->language);
15742       if (!ast_strlen_zero(peer->accountcode))
15743          astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
15744       astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
15745       astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
15746       if (!ast_strlen_zero(peer->fromuser))
15747          astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
15748       if (!ast_strlen_zero(peer->fromdomain))
15749          astman_append(s, "SIP-FromDomain: %s\r\n", peer->fromdomain);
15750       astman_append(s, "Callgroup: ");
15751       astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->callgroup));
15752       astman_append(s, "Pickupgroup: ");
15753       astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->pickupgroup));
15754       peer_mailboxes_to_str(&mailbox_str, peer);
15755       astman_append(s, "VoiceMailbox: %s\r\n", mailbox_str->str);
15756       astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
15757       astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
15758       astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
15759       astman_append(s, "Busy-level: %d\r\n", peer->busy_level);
15760       astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
15761       astman_append(s, "Dynamic: %s\r\n", peer->host_dynamic?"Y":"N");
15762       astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
15763       astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched, peer->expire));
15764       astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
15765       astman_append(s, "SIP-NatSupport: %s\r\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
15766       astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
15767       astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
15768       astman_append(s, "SIP-DirectMedia: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
15769       astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
15770       astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
15771       astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
15772       astman_append(s, "SIP-TextSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)?"Y":"N"));
15773       astman_append(s, "SIP-T.38Support: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)?"Y":"N"));
15774       astman_append(s, "SIP-T.38EC: %s\r\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
15775       astman_append(s, "SIP-T.38MaxDtgrm: %d\r\n", peer->t38_maxdatagram);
15776       astman_append(s, "SIP-Sess-Timers: %s\r\n", stmode2str(peer->stimer.st_mode_oper));
15777       astman_append(s, "SIP-Sess-Refresh: %s\r\n", strefresher2str(peer->stimer.st_ref));
15778       astman_append(s, "SIP-Sess-Expires: %d\r\n", peer->stimer.st_max_se);
15779       astman_append(s, "SIP-Sess-Min: %d\r\n", peer->stimer.st_min_se);
15780 
15781       /* - is enumerated */
15782       astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
15783       astman_append(s, "ToHost: %s\r\n", peer->tohost);
15784       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));
15785       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));
15786       astman_append(s, "Default-Username: %s\r\n", peer->username);
15787       if (!ast_strlen_zero(global_regcontext))
15788          astman_append(s, "RegExtension: %s\r\n", peer->regexten);
15789       astman_append(s, "Codecs: ");
15790       ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
15791       astman_append(s, "%s\r\n", codec_buf);
15792       astman_append(s, "CodecOrder: ");
15793       pref = &peer->prefs;
15794       for(x = 0; x < 32 ; x++) {
15795          codec = ast_codec_pref_index(pref, x);
15796          if (!codec)
15797             break;
15798          astman_append(s, "%s", ast_getformatname(codec));
15799          if (x < 31 && ast_codec_pref_index(pref, x+1))
15800             astman_append(s, ",");
15801       }
15802 
15803       astman_append(s, "\r\n");
15804       astman_append(s, "Status: ");
15805       peer_status(peer, status, sizeof(status));
15806       astman_append(s, "%s\r\n", status);
15807       astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
15808       astman_append(s, "Reg-Contact: %s\r\n", peer->fullcontact);
15809       astman_append(s, "QualifyFreq: %d ms\r\n", peer->qualifyfreq);
15810       astman_append(s, "Parkinglot: %s\r\n", peer->parkinglot);
15811       if (peer->chanvars) {
15812          for (v = peer->chanvars ; v ; v = v->next) {
15813             astman_append(s, "ChanVariable: %s=%s\r\n", v->name, v->value);
15814          }
15815       }
15816 
15817       peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer");
15818 
15819    } else {
15820       ast_cli(fd, "Peer %s not found.\n", argv[3]);
15821       ast_cli(fd, "\n");
15822    }
15823 
15824    return CLI_SUCCESS;
15825 }
15826 
15827 /*! \brief Do completion on user name */
15828 static char *complete_sip_user(const char *word, int state)
15829 {
15830    char *result = NULL;
15831    int wordlen = strlen(word);
15832    int which = 0;
15833    struct ao2_iterator user_iter;
15834    struct sip_peer *user;
15835 
15836    user_iter = ao2_iterator_init(peers, 0);
15837    while ((user = ao2_iterator_next(&user_iter))) {
15838       ao2_lock(user);
15839       if (!(user->type & SIP_TYPE_USER)) {
15840          ao2_unlock(user);
15841          unref_peer(user, "complete sip user");
15842          continue;
15843       }
15844       /* locking of the object is not required because only the name and flags are being compared */
15845       if (!strncasecmp(word, user->name, wordlen) && ++which > state) {
15846          result = ast_strdup(user->name);
15847       }
15848       ao2_unlock(user);
15849       unref_peer(user, "complete sip user");
15850    }
15851    ao2_iterator_destroy(&user_iter);
15852    return result;
15853 }
15854 /*! \brief Support routine for 'sip show user' CLI */
15855 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
15856 {
15857    if (pos == 3)
15858       return complete_sip_user(word, state);
15859 
15860    return NULL;
15861 }
15862 
15863 /*! \brief Show one user in detail */
15864 static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15865 {
15866    char cbuf[256];
15867    struct sip_peer *user;
15868    struct ast_variable *v;
15869    int load_realtime;
15870 
15871    switch (cmd) {
15872    case CLI_INIT:
15873       e->command = "sip show user";
15874       e->usage =
15875          "Usage: sip show user <name> [load]\n"
15876          "       Shows all details on one SIP user and the current status.\n"
15877          "       Option \"load\" forces lookup of peer in realtime storage.\n";
15878       return NULL;
15879    case CLI_GENERATE:
15880       return complete_sip_show_user(a->line, a->word, a->pos, a->n);
15881    }
15882 
15883    if (a->argc < 4)
15884       return CLI_SHOWUSAGE;
15885 
15886    /* Load from realtime storage? */
15887    load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? TRUE : FALSE;
15888 
15889    if ((user = find_peer(a->argv[3], NULL, load_realtime, FINDUSERS, FALSE, 0))) {
15890       ao2_lock(user);
15891       ast_cli(a->fd, "\n\n");
15892       ast_cli(a->fd, "  * Name       : %s\n", user->name);
15893       ast_cli(a->fd, "  Secret       : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
15894       ast_cli(a->fd, "  MD5Secret    : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
15895       ast_cli(a->fd, "  Context      : %s\n", user->context);
15896       ast_cli(a->fd, "  Language     : %s\n", user->language);
15897       if (!ast_strlen_zero(user->accountcode))
15898          ast_cli(a->fd, "  Accountcode  : %s\n", user->accountcode);
15899       ast_cli(a->fd, "  AMA flags    : %s\n", ast_cdr_flags2str(user->amaflags));
15900       ast_cli(a->fd, "  Transfer mode: %s\n", transfermode2str(user->allowtransfer));
15901       ast_cli(a->fd, "  MaxCallBR    : %d kbps\n", user->maxcallbitrate);
15902       ast_cli(a->fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(user->callingpres));
15903       ast_cli(a->fd, "  Call limit   : %d\n", user->call_limit);
15904       ast_cli(a->fd, "  Callgroup    : ");
15905       print_group(a->fd, user->callgroup, 0);
15906       ast_cli(a->fd, "  Pickupgroup  : ");
15907       print_group(a->fd, user->pickupgroup, 0);
15908       ast_cli(a->fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
15909       ast_cli(a->fd, "  ACL          : %s\n", cli_yesno(user->ha != NULL));
15910       ast_cli(a->fd, "  Sess-Timers  : %s\n", stmode2str(user->stimer.st_mode_oper));
15911       ast_cli(a->fd, "  Sess-Refresh : %s\n", strefresher2str(user->stimer.st_ref));
15912       ast_cli(a->fd, "  Sess-Expires : %d secs\n", user->stimer.st_max_se);
15913       ast_cli(a->fd, "  Sess-Min-SE  : %d secs\n", user->stimer.st_min_se);
15914 
15915       ast_cli(a->fd, "  Codec Order  : (");
15916       print_codec_to_cli(a->fd, &user->prefs);
15917       ast_cli(a->fd, ")\n");
15918 
15919       ast_cli(a->fd, "  Auto-Framing:  %s \n", cli_yesno(user->autoframing));
15920       if (user->chanvars) {
15921          ast_cli(a->fd, "  Variables    :\n");
15922          for (v = user->chanvars ; v ; v = v->next)
15923             ast_cli(a->fd, "                 %s = %s\n", v->name, v->value);
15924       }
15925 
15926       ast_cli(a->fd, "\n");
15927 
15928       ao2_unlock(user);
15929       unref_peer(user, "sip show user");
15930    } else {
15931       ast_cli(a->fd, "User %s not found.\n", a->argv[3]);
15932       ast_cli(a->fd, "\n");
15933    }
15934 
15935    return CLI_SUCCESS;
15936 }
15937 
15938 
15939 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15940 {
15941    struct ast_str *cbuf;
15942    struct ast_cb_names cbnames = {9, { "retrans_pkt",
15943                                         "__sip_autodestruct",
15944                                         "expire_register",
15945                                         "auto_congest",
15946                                         "sip_reg_timeout",
15947                                         "sip_poke_peer_s",
15948                                         "sip_poke_noanswer",
15949                                         "sip_reregister",
15950                                         "sip_reinvite_retry"},
15951                            { retrans_pkt,
15952                                      __sip_autodestruct,
15953                                      expire_register,
15954                                      auto_congest,
15955                                      sip_reg_timeout,
15956                                      sip_poke_peer_s,
15957                                      sip_poke_noanswer,
15958                                      sip_reregister,
15959                                      sip_reinvite_retry}};
15960    
15961    switch (cmd) {
15962    case CLI_INIT:
15963       e->command = "sip show sched";
15964       e->usage =
15965          "Usage: sip show sched\n"
15966          "       Shows stats on what's in the sched queue at the moment\n";
15967       return NULL;
15968    case CLI_GENERATE:
15969       return NULL;
15970    }
15971 
15972    cbuf = ast_str_alloca(2048);
15973 
15974    ast_cli(a->fd, "\n");
15975    ast_sched_report(sched, &cbuf, &cbnames);
15976    ast_cli(a->fd, "%s", cbuf->str);
15977 
15978    return CLI_SUCCESS;
15979 }
15980 
15981 /*! \brief  Show SIP Registry (registrations with other SIP proxies */
15982 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15983 {
15984 #define FORMAT2 "%-30.30s %-6.6s %-12.12s  %8.8s %-20.20s %-25.25s\n"
15985 #define FORMAT  "%-30.30s %-6.6s %-12.12s  %8d %-20.20s %-25.25s\n"
15986    char host[80];
15987    char tmpdat[256];
15988    struct ast_tm tm;
15989    int counter = 0;
15990 
15991    switch (cmd) {
15992    case CLI_INIT:
15993       e->command = "sip show registry";
15994       e->usage =
15995          "Usage: sip show registry\n"
15996          "       Lists all registration requests and status.\n";
15997       return NULL;
15998    case CLI_GENERATE:
15999       return NULL;
16000    }
16001 
16002    if (a->argc != 3)
16003       return CLI_SHOWUSAGE;
16004    ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Refresh", "State", "Reg.Time");
16005    
16006    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
16007       ASTOBJ_RDLOCK(iterator);
16008       snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
16009       if (iterator->regtime.tv_sec) {
16010          ast_localtime(&iterator->regtime, &tm, NULL);
16011          ast_strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
16012       } else 
16013          tmpdat[0] = '\0';
16014       ast_cli(a->fd, FORMAT, host, (iterator->dnsmgr) ? "Y" : "N", iterator->username, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
16015       ASTOBJ_UNLOCK(iterator);
16016       counter++;
16017    } while(0));
16018    ast_cli(a->fd, "%d SIP registrations.\n", counter);
16019    return CLI_SUCCESS;
16020 #undef FORMAT
16021 #undef FORMAT2
16022 }
16023 
16024 /*! \brief Unregister (force expiration) a SIP peer in the registry via CLI 
16025    \note This function does not tell the SIP device what's going on,
16026    so use it with great care.
16027 */
16028 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16029 {
16030    struct sip_peer *peer;
16031    int load_realtime = 0;
16032 
16033    switch (cmd) {
16034    case CLI_INIT:
16035       e->command = "sip unregister";
16036       e->usage =
16037          "Usage: sip unregister <peer>\n"
16038          "       Unregister (force expiration) a SIP peer from the registry\n";
16039       return NULL;
16040    case CLI_GENERATE:
16041       return complete_sip_unregister(a->line, a->word, a->pos, a->n);
16042    }
16043    
16044    if (a->argc != 3)
16045       return CLI_SHOWUSAGE;
16046    
16047    if ((peer = find_peer(a->argv[2], NULL, load_realtime, FINDPEERS, TRUE, 0))) {
16048       if (peer->expire > 0) {
16049          AST_SCHED_DEL_UNREF(sched, peer->expire,
16050             unref_peer(peer, "remove register expire ref"));
16051          expire_register(ref_peer(peer, "ref for expire_register"));
16052          ast_cli(a->fd, "Unregistered peer \'%s\'\n\n", a->argv[2]);
16053       } else {
16054          ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
16055       }
16056       unref_peer(peer, "sip_unregister: unref_peer via sip_unregister: done with peer from find_peer call");
16057    } else {
16058       ast_cli(a->fd, "Peer unknown: \'%s\'. Not unregistered.\n", a->argv[2]);
16059    }
16060    
16061    return CLI_SUCCESS;
16062 }
16063 
16064 /*! \brief Callback for show_chanstats */
16065 static int show_chanstats_cb(void *__cur, void *__arg, int flags)
16066 {
16067 #define FORMAT2 "%-15.15s  %-11.11s  %-8.8s %-10.10s  %-10.10s (     %%) %-6.6s %-10.10s  %-10.10s (     %%) %-6.6s\n"
16068 #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"
16069    struct sip_pvt *cur = __cur;
16070    unsigned int rxcount, txcount, rxploss, txploss;
16071    char durbuf[10];
16072         int duration;
16073         int durh, durm, durs;
16074    struct ast_channel *c = cur->owner;
16075    struct __show_chan_arg *arg = __arg;
16076    int fd = arg->fd;
16077 
16078 
16079    if (cur->subscribed != NONE) /* Subscriptions */
16080       return 0;   /* don't care, we scan all channels */
16081 
16082    if (!cur->rtp) {
16083       if (sipdebug)
16084          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");
16085       return 0;   /* don't care, we scan all channels */
16086    }
16087    rxcount = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXCOUNT);
16088    txcount = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXCOUNT);
16089    rxploss = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXPLOSS);
16090    txploss = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXPLOSS);
16091 
16092    /* Find the duration of this channel */
16093    if (c && c->cdr && !ast_tvzero(c->cdr->start)) {
16094       duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
16095       durh = duration / 3600;
16096       durm = (duration % 3600) / 60;
16097       durs = duration % 60;
16098       snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
16099    } else {
16100       durbuf[0] = '\0';
16101    }
16102    /* Print stats for every call with RTP */
16103    ast_cli(fd, FORMAT, 
16104       ast_inet_ntoa(cur->sa.sin_addr), 
16105       cur->callid, 
16106       durbuf,
16107       rxcount > (unsigned int) 100000 ? (unsigned int) (rxcount)/(unsigned int) 1000 : rxcount,
16108       rxcount > (unsigned int) 100000 ? "K":" ",
16109       rxploss,
16110       (rxcount + rxploss) > 0 ? (double) rxploss / (rxcount + rxploss) * 100 : 0,
16111       ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXJITTER),
16112       txcount > (unsigned int) 100000 ? (unsigned int) (txcount)/(unsigned int) 1000 : txcount,
16113       txcount > (unsigned int) 100000 ? "K":" ",
16114       txploss,
16115       txcount > 0 ? (double) txploss / txcount * 100 : 0,
16116       ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXJITTER)
16117    );
16118    arg->numchans++;
16119 
16120    return 0;   /* don't care, we scan all channels */
16121 }
16122 
16123 /*! \brief SIP show channelstats CLI (main function) */
16124 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16125 {
16126    struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
16127 
16128    switch (cmd) {
16129    case CLI_INIT:
16130       e->command = "sip show channelstats";
16131       e->usage =
16132          "Usage: sip show channelstats\n"
16133          "       Lists all currently active SIP channel's RTCP statistics.\n"
16134          "       Note that calls in the much optimized RTP P2P bridge mode will not show any packets here.";
16135       return NULL;
16136    case CLI_GENERATE:
16137       return NULL;
16138    }
16139 
16140    if (a->argc != 3)
16141       return CLI_SHOWUSAGE;
16142 
16143    ast_cli(a->fd, FORMAT2, "Peer", "Call ID", "Duration", "Recv: Pack", "Lost", "Jitter", "Send: Pack", "Lost", "Jitter");
16144    /* iterate on the container and invoke the callback on each item */
16145    ao2_t_callback(dialogs, OBJ_NODATA, show_chanstats_cb, &arg, "callback to sip show chanstats");
16146    ast_cli(a->fd, "%d active SIP channel%s\n", arg.numchans, (arg.numchans != 1) ? "s" : ""); 
16147    return CLI_SUCCESS;
16148 }
16149 #undef FORMAT
16150 #undef FORMAT2
16151 
16152 /*! \brief List global settings for the SIP channel */
16153 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16154 {
16155    int realtimepeers;
16156    int realtimeregs;
16157    char codec_buf[SIPBUFSIZE];
16158    const char *msg;  /* temporary msg pointer */
16159 
16160    switch (cmd) {
16161    case CLI_INIT:
16162       e->command = "sip show settings";
16163       e->usage =
16164          "Usage: sip show settings\n"
16165          "       Provides detailed list of the configuration of the SIP channel.\n";
16166       return NULL;
16167    case CLI_GENERATE:
16168       return NULL;
16169    }
16170 
16171 
16172    realtimepeers = ast_check_realtime("sippeers");
16173    realtimeregs = ast_check_realtime("sipregs");
16174 
16175    if (a->argc != 3)
16176       return CLI_SHOWUSAGE;
16177    ast_cli(a->fd, "\n\nGlobal Settings:\n");
16178    ast_cli(a->fd, "----------------\n");
16179    ast_cli(a->fd, "  UDP SIP Port:           %d\n", ntohs(bindaddr.sin_port));
16180    ast_cli(a->fd, "  UDP Bindaddress:        %s\n", ast_inet_ntoa(bindaddr.sin_addr));
16181    ast_cli(a->fd, "  TCP SIP Port:           ");
16182    if (sip_tcp_desc.local_address.sin_family == AF_INET) {
16183       ast_cli(a->fd, "%d\n", ntohs(sip_tcp_desc.local_address.sin_port));
16184       ast_cli(a->fd, "  TCP Bindaddress:        %s\n", ast_inet_ntoa(sip_tcp_desc.local_address.sin_addr));
16185    } else {
16186       ast_cli(a->fd, "Disabled\n");
16187    }
16188    ast_cli(a->fd, "  TLS SIP Port:           ");
16189    if (default_tls_cfg.enabled != FALSE) {
16190       ast_cli(a->fd, "%d\n", ntohs(sip_tls_desc.local_address.sin_port));
16191       ast_cli(a->fd, "  TLS Bindaddress:        %s\n", ast_inet_ntoa(sip_tls_desc.local_address.sin_addr));
16192    } else {
16193       ast_cli(a->fd, "Disabled\n");
16194    }
16195    ast_cli(a->fd, "  Videosupport:           %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT)));
16196    ast_cli(a->fd, "  Textsupport:            %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT)));
16197    ast_cli(a->fd, "  Ignore SDP sess. ver.:  %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION)));
16198    ast_cli(a->fd, "  AutoCreate Peer:        %s\n", cli_yesno(sip_cfg.autocreatepeer));
16199    ast_cli(a->fd, "  Match Auth Username:    %s\n", cli_yesno(global_match_auth_username));
16200    ast_cli(a->fd, "  Allow unknown access:   %s\n", cli_yesno(sip_cfg.allowguest));
16201    ast_cli(a->fd, "  Allow subscriptions:    %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
16202    ast_cli(a->fd, "  Allow overlap dialing:  %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)));
16203    ast_cli(a->fd, "  Allow promsic. redir:   %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_PROMISCREDIR)));
16204    ast_cli(a->fd, "  Enable call counters:   %s\n", cli_yesno(global_callcounter));
16205    ast_cli(a->fd, "  SIP domain support:     %s\n", cli_yesno(!AST_LIST_EMPTY(&domain_list)));
16206    ast_cli(a->fd, "  Realm. auth:            %s\n", cli_yesno(authl != NULL));
16207    ast_cli(a->fd, "  Our auth realm          %s\n", sip_cfg.realm);
16208    ast_cli(a->fd, "  Call to non-local dom.: %s\n", cli_yesno(sip_cfg.allow_external_domains));
16209    ast_cli(a->fd, "  URI user is phone no:   %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_USEREQPHONE)));
16210    ast_cli(a->fd, "  Always auth rejects:    %s\n", cli_yesno(sip_cfg.alwaysauthreject));
16211    ast_cli(a->fd, "  Direct RTP setup:       %s\n", cli_yesno(sip_cfg.directrtpsetup));
16212    ast_cli(a->fd, "  User Agent:             %s\n", global_useragent);
16213    ast_cli(a->fd, "  SDP Session Name:       %s\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
16214    ast_cli(a->fd, "  SDP Owner Name:         %s\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner);
16215    ast_cli(a->fd, "  Reg. context:           %s\n", S_OR(global_regcontext, "(not set)"));
16216    ast_cli(a->fd, "  Regexten on Qualify:    %s\n", cli_yesno(sip_cfg.regextenonqualify));
16217    ast_cli(a->fd, "  Caller ID:              %s\n", default_callerid);
16218    ast_cli(a->fd, "  From: Domain:           %s\n", default_fromdomain);
16219    ast_cli(a->fd, "  Record SIP history:     %s\n", recordhistory ? "On" : "Off");
16220    ast_cli(a->fd, "  Call Events:            %s\n", sip_cfg.callevents ? "On" : "Off");
16221    ast_cli(a->fd, "  Auth. Failure Events:   %s\n", global_authfailureevents ? "On" : "Off");
16222 
16223    ast_cli(a->fd, "  T.38 support:           %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
16224    ast_cli(a->fd, "  T.38 EC mode:           %s\n", faxec2str(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
16225    ast_cli(a->fd, "  T.38 MaxDtgrm:          %d\n", global_t38_maxdatagram);
16226 
16227    if (!realtimepeers && !realtimeregs)
16228       ast_cli(a->fd, "  SIP realtime:           Disabled\n" );
16229    else
16230       ast_cli(a->fd, "  SIP realtime:           Enabled\n" );
16231    ast_cli(a->fd, "  Qualify Freq :          %d ms\n", global_qualifyfreq);
16232    ast_cli(a->fd, "\nNetwork QoS Settings:\n");
16233    ast_cli(a->fd, "---------------------------\n");
16234    ast_cli(a->fd, "  IP ToS SIP:             %s\n", ast_tos2str(global_tos_sip));
16235    ast_cli(a->fd, "  IP ToS RTP audio:       %s\n", ast_tos2str(global_tos_audio));
16236    ast_cli(a->fd, "  IP ToS RTP video:       %s\n", ast_tos2str(global_tos_video));
16237    ast_cli(a->fd, "  IP ToS RTP text:        %s\n", ast_tos2str(global_tos_text));
16238    ast_cli(a->fd, "  802.1p CoS SIP:         %d\n", global_cos_sip);
16239    ast_cli(a->fd, "  802.1p CoS RTP audio:   %d\n", global_cos_audio);
16240    ast_cli(a->fd, "  802.1p CoS RTP video:   %d\n", global_cos_video);
16241    ast_cli(a->fd, "  802.1p CoS RTP text:    %d\n", global_cos_text);
16242    ast_cli(a->fd, "  Jitterbuffer enabled:   %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_ENABLED)));
16243    ast_cli(a->fd, "  Jitterbuffer forced:    %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_FORCED)));
16244    ast_cli(a->fd, "  Jitterbuffer max size:  %ld\n", global_jbconf.max_size);
16245    ast_cli(a->fd, "  Jitterbuffer resync:    %ld\n", global_jbconf.resync_threshold);
16246    ast_cli(a->fd, "  Jitterbuffer impl:      %s\n", global_jbconf.impl);
16247    ast_cli(a->fd, "  Jitterbuffer log:       %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_LOG)));
16248 
16249    ast_cli(a->fd, "\nNetwork Settings:\n");
16250    ast_cli(a->fd, "---------------------------\n");
16251    /* determine if/how SIP address can be remapped */
16252    if (localaddr == NULL)
16253       msg = "Disabled, no localnet list";
16254    else if (externip.sin_addr.s_addr == 0)
16255       msg = "Disabled, externip is 0.0.0.0";
16256    else if (stunaddr.sin_addr.s_addr != 0)
16257       msg = "Enabled using STUN";
16258    else if (!ast_strlen_zero(externhost))
16259       msg = "Enabled using externhost";
16260    else
16261       msg = "Enabled using externip";
16262    ast_cli(a->fd, "  SIP address remapping:  %s\n", msg);
16263    ast_cli(a->fd, "  Externhost:             %s\n", S_OR(externhost, "<none>"));
16264    ast_cli(a->fd, "  Externip:               %s:%d\n", ast_inet_ntoa(externip.sin_addr), ntohs(externip.sin_port));
16265    ast_cli(a->fd, "  Externrefresh:          %d\n", externrefresh);
16266    {
16267       struct ast_ha *d;
16268       const char *prefix = "Localnet:";
16269       char buf[INET_ADDRSTRLEN]; /* need to print two addresses */
16270 
16271       for (d = localaddr; d ; prefix = "", d = d->next) {
16272          ast_cli(a->fd, "  %-24s%s/%s\n",
16273              prefix, ast_inet_ntoa(d->netaddr),
16274              inet_ntop(AF_INET, &d->netmask, buf, sizeof(buf)) );
16275       }
16276    }
16277    ast_cli(a->fd, "  STUN server:            %s:%d\n", ast_inet_ntoa(stunaddr.sin_addr), ntohs(stunaddr.sin_port));
16278  
16279    ast_cli(a->fd, "\nGlobal Signalling Settings:\n");
16280    ast_cli(a->fd, "---------------------------\n");
16281    ast_cli(a->fd, "  Codecs:                 ");
16282    ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, global_capability);
16283    ast_cli(a->fd, "%s\n", codec_buf);
16284    ast_cli(a->fd, "  Codec Order:            ");
16285    print_codec_to_cli(a->fd, &default_prefs);
16286    ast_cli(a->fd, "\n");
16287    ast_cli(a->fd, "  Relax DTMF:             %s\n", cli_yesno(global_relaxdtmf));
16288    ast_cli(a->fd, "  RFC2833 Compensation:   %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE)));
16289    ast_cli(a->fd, "  Compact SIP headers:    %s\n", cli_yesno(sip_cfg.compactheaders));
16290    ast_cli(a->fd, "  RTP Keepalive:          %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
16291    ast_cli(a->fd, "  RTP Timeout:            %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
16292    ast_cli(a->fd, "  RTP Hold Timeout:       %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
16293    ast_cli(a->fd, "  MWI NOTIFY mime type:   %s\n", default_notifymime);
16294    ast_cli(a->fd, "  DNS SRV lookup:         %s\n", cli_yesno(sip_cfg.srvlookup));
16295    ast_cli(a->fd, "  Pedantic SIP support:   %s\n", cli_yesno(sip_cfg.pedanticsipchecking));
16296    ast_cli(a->fd, "  Reg. min duration       %d secs\n", min_expiry);
16297    ast_cli(a->fd, "  Reg. max duration:      %d secs\n", max_expiry);
16298    ast_cli(a->fd, "  Reg. default duration:  %d secs\n", default_expiry);
16299    ast_cli(a->fd, "  Outbound reg. timeout:  %d secs\n", global_reg_timeout);
16300    ast_cli(a->fd, "  Outbound reg. attempts: %d\n", global_regattempts_max);
16301    ast_cli(a->fd, "  Notify ringing state:   %s\n", cli_yesno(sip_cfg.notifyringing));
16302    if (sip_cfg.notifyringing) {
16303       ast_cli(a->fd, "    Include CID:          %s%s\n",
16304             cli_yesno(sip_cfg.notifycid),
16305             sip_cfg.notifycid == IGNORE_CONTEXT ? " (Ignoring context)" : "");
16306    }
16307    ast_cli(a->fd, "  Notify hold state:      %s\n", cli_yesno(sip_cfg.notifyhold));
16308    ast_cli(a->fd, "  SIP Transfer mode:      %s\n", transfermode2str(sip_cfg.allowtransfer));
16309    ast_cli(a->fd, "  Max Call Bitrate:       %d kbps\n", default_maxcallbitrate);
16310    ast_cli(a->fd, "  Auto-Framing:           %s\n", cli_yesno(global_autoframing));
16311    ast_cli(a->fd, "  Outb. proxy:            %s %s\n", ast_strlen_zero(sip_cfg.outboundproxy.name) ? "<not set>" : sip_cfg.outboundproxy.name,
16312                      sip_cfg.outboundproxy.force ? "(forced)" : "");
16313    ast_cli(a->fd, "  Session Timers:         %s\n", stmode2str(global_st_mode));
16314    ast_cli(a->fd, "  Session Refresher:      %s\n", strefresher2str (global_st_refresher));
16315    ast_cli(a->fd, "  Session Expires:        %d secs\n", global_max_se);
16316    ast_cli(a->fd, "  Session Min-SE:         %d secs\n", global_min_se);
16317    ast_cli(a->fd, "  Timer T1:               %d\n", global_t1);
16318    ast_cli(a->fd, "  Timer T1 minimum:       %d\n", global_t1min);
16319    ast_cli(a->fd, "  Timer B:                %d\n", global_timer_b);
16320    ast_cli(a->fd, "  No premature media:     %s\n", global_prematuremediafilter ? "Yes" : "No");
16321 
16322    ast_cli(a->fd, "\nDefault Settings:\n");
16323    ast_cli(a->fd, "-----------------\n");
16324    ast_cli(a->fd, "  Allowed transports:     %s\n", get_transport_list(default_transports)); 
16325    ast_cli(a->fd, "  Outbound transport:    %s\n", get_transport(default_primary_transport));
16326    ast_cli(a->fd, "  Context:                %s\n", sip_cfg.default_context);
16327    ast_cli(a->fd, "  Nat:                    %s\n", nat2str(ast_test_flag(&global_flags[0], SIP_NAT)));
16328    ast_cli(a->fd, "  DTMF:                   %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
16329    ast_cli(a->fd, "  Qualify:                %d\n", default_qualify);
16330    ast_cli(a->fd, "  Use ClientCode:         %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_USECLIENTCODE)));
16331    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" );
16332    ast_cli(a->fd, "  Language:               %s\n", default_language);
16333    ast_cli(a->fd, "  MOH Interpret:          %s\n", default_mohinterpret);
16334    ast_cli(a->fd, "  MOH Suggest:            %s\n", default_mohsuggest);
16335    ast_cli(a->fd, "  Voice Mail Extension:   %s\n", default_vmexten);
16336    ast_cli(a->fd, "  Forward Detected Loops: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_FORWARD_LOOP_DETECTED)));
16337    
16338    if (realtimepeers || realtimeregs) {
16339       ast_cli(a->fd, "\nRealtime SIP Settings:\n");
16340       ast_cli(a->fd, "----------------------\n");
16341       ast_cli(a->fd, "  Realtime Peers:         %s\n", cli_yesno(realtimepeers));
16342       ast_cli(a->fd, "  Realtime Regs:          %s\n", cli_yesno(realtimeregs));
16343       ast_cli(a->fd, "  Cache Friends:          %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)));
16344       ast_cli(a->fd, "  Update:                 %s\n", cli_yesno(sip_cfg.peer_rtupdate));
16345       ast_cli(a->fd, "  Ignore Reg. Expire:     %s\n", cli_yesno(sip_cfg.ignore_regexpire));
16346       ast_cli(a->fd, "  Save sys. name:         %s\n", cli_yesno(sip_cfg.rtsave_sysname));
16347       ast_cli(a->fd, "  Auto Clear:             %d (%s)\n", sip_cfg.rtautoclear, ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR) ? "Enabled" : "Disabled");
16348    }
16349    ast_cli(a->fd, "\n----\n");
16350    return CLI_SUCCESS;
16351 }
16352 
16353 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16354 {
16355 #define FORMAT  "%-30.30s  %-12.12s  %-10.10s  %-10.10s\n"
16356    char host[80];
16357    
16358    switch (cmd) {
16359    case CLI_INIT:
16360       e->command = "sip show mwi";
16361       e->usage =
16362          "Usage: sip show mwi\n"
16363          "       Provides a list of MWI subscriptions and status.\n";
16364       return NULL;
16365    case CLI_GENERATE:
16366       return NULL;
16367    }
16368    
16369    ast_cli(a->fd, FORMAT, "Host", "Username", "Mailbox", "Subscribed");
16370    
16371    ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
16372       ASTOBJ_RDLOCK(iterator);
16373       snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
16374       ast_cli(a->fd, FORMAT, host, iterator->username, iterator->mailbox, iterator->subscribed ? "Yes" : "No");
16375       ASTOBJ_UNLOCK(iterator);
16376    } while(0));
16377 
16378    return CLI_SUCCESS;
16379 #undef FORMAT
16380 }
16381 
16382 
16383 /*! \brief Show subscription type in string format */
16384 static const char *subscription_type2str(enum subscriptiontype subtype)
16385 {
16386    int i;
16387 
16388    for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
16389       if (subscription_types[i].type == subtype) {
16390          return subscription_types[i].text;
16391       }
16392    }
16393    return subscription_types[0].text;
16394 }
16395 
16396 /*! \brief Find subscription type in array */
16397 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
16398 {
16399    int i;
16400 
16401    for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
16402       if (subscription_types[i].type == subtype) {
16403          return &subscription_types[i];
16404       }
16405    }
16406    return &subscription_types[0];
16407 }
16408 
16409 /*
16410  * We try to structure all functions that loop on data structures as
16411  * a handler for individual entries, and a mainloop that iterates
16412  * on the main data structure. This way, moving the code to containers
16413  * that support iteration through callbacks will be a lot easier.
16414  */
16415 
16416 #define FORMAT4 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-13.13s  %-15.15s %-10.10s %-6.6d\n"
16417 #define FORMAT3 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-13.13s  %-15.15s %-10.10s %-6.6s\n"
16418 #define FORMAT2 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-7.7s  %-15.15s %-6.6s\n"
16419 #define FORMAT  "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-3.3s %-3.3s  %-15.15s %-10.10s\n"
16420 
16421 /*! \brief callback for show channel|subscription */
16422 static int show_channels_cb(void *__cur, void *__arg, int flags)
16423 {
16424    struct sip_pvt *cur = __cur;
16425    struct __show_chan_arg *arg = __arg;
16426    const struct sockaddr_in *dst = sip_real_dst(cur);
16427    
16428    /* XXX indentation preserved to reduce diff. Will be fixed later */
16429    if (cur->subscribed == NONE && !arg->subscriptions) {
16430       /* set if SIP transfer in progress */
16431       const char *referstatus = cur->refer ? referstatus2str(cur->refer->status) : "";
16432       char formatbuf[SIPBUFSIZE/2];
16433       
16434       ast_cli(arg->fd, FORMAT, ast_inet_ntoa(dst->sin_addr), 
16435             S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
16436             cur->callid, 
16437             ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0),
16438             cli_yesno(ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD)),
16439             cur->needdestroy ? "(d)" : "",
16440             cur->lastmsg ,
16441             referstatus
16442          );
16443       arg->numchans++;
16444    }
16445    if (cur->subscribed != NONE && arg->subscriptions) {
16446       struct ast_str *mailbox_str = ast_str_alloca(512);
16447       if (cur->subscribed == MWI_NOTIFICATION && cur->relatedpeer)
16448          peer_mailboxes_to_str(&mailbox_str, cur->relatedpeer);
16449       ast_cli(arg->fd, FORMAT4, ast_inet_ntoa(dst->sin_addr),
16450             S_OR(cur->username, S_OR(cur->cid_num, "(None)")), 
16451                cur->callid,
16452             /* the 'complete' exten/context is hidden in the refer_to field for subscriptions */
16453             cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
16454             cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate), 
16455             subscription_type2str(cur->subscribed),
16456             cur->subscribed == MWI_NOTIFICATION ? S_OR(mailbox_str->str, "<none>") : "<none>",
16457             cur->expiry
16458          );
16459       arg->numchans++;
16460    }
16461    return 0;   /* don't care, we scan all channels */
16462 }
16463 
16464 /*! \brief CLI for show channels or subscriptions.
16465  * This is a new-style CLI handler so a single function contains
16466  * the prototype for the function, the 'generator' to produce multiple
16467  * entries in case it is required, and the actual handler for the command.
16468  */
16469 static char *sip_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16470 {
16471    struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
16472 
16473 
16474    if (cmd == CLI_INIT) {
16475       e->command = "sip show {channels|subscriptions}";
16476       e->usage =
16477          "Usage: sip show channels\n"
16478          "       Lists all currently active SIP calls (dialogs).\n"
16479          "Usage: sip show subscriptions\n"
16480          "       Lists active SIP subscriptions.\n";
16481       return NULL;
16482    } else if (cmd == CLI_GENERATE)
16483       return NULL;
16484 
16485    if (a->argc != e->args)
16486       return CLI_SHOWUSAGE;
16487    arg.subscriptions = !strcasecmp(a->argv[e->args - 1], "subscriptions");
16488    if (!arg.subscriptions)
16489       ast_cli(arg.fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Format", "Hold", "Last Message", "Expiry");
16490    else
16491       ast_cli(arg.fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox", "Expiry");
16492 
16493    /* iterate on the container and invoke the callback on each item */
16494    ao2_t_callback(dialogs, OBJ_NODATA, show_channels_cb, &arg, "callback to show channels");
16495    
16496    /* print summary information */
16497    ast_cli(arg.fd, "%d active SIP %s%s\n", arg.numchans,
16498       (arg.subscriptions ? "subscription" : "dialog"),
16499       ESS(arg.numchans));  /* ESS(n) returns an "s" if n>1 */
16500    return CLI_SUCCESS;
16501 #undef FORMAT
16502 #undef FORMAT2
16503 #undef FORMAT3
16504 }
16505 
16506 /*! \brief Support routine for 'sip show channel' and 'sip show history' CLI
16507  * This is in charge of generating all strings that match a prefix in the
16508  * given position. As many functions of this kind, each invokation has
16509  * O(state) time complexity so be careful in using it.
16510  */
16511 static char *complete_sipch(const char *line, const char *word, int pos, int state)
16512 {
16513    int which=0;
16514    struct sip_pvt *cur;
16515    char *c = NULL;
16516    int wordlen = strlen(word);
16517    struct ao2_iterator i;
16518 
16519    if (pos != 3) {
16520       return NULL;
16521    }
16522 
16523    i = ao2_iterator_init(dialogs, 0);
16524    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
16525       sip_pvt_lock(cur);
16526       if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
16527          c = ast_strdup(cur->callid);
16528          sip_pvt_unlock(cur);
16529          dialog_unref(cur, "drop ref in iterator loop break");
16530          break;
16531       }
16532       sip_pvt_unlock(cur);
16533       dialog_unref(cur, "drop ref in iterator loop");
16534    }
16535    ao2_iterator_destroy(&i);
16536    return c;
16537 }
16538 
16539 
16540 /*! \brief Do completion on peer name */
16541 static char *complete_sip_peer(const char *word, int state, int flags2)
16542 {
16543    char *result = NULL;
16544    int wordlen = strlen(word);
16545    int which = 0;
16546    struct ao2_iterator i = ao2_iterator_init(peers, 0);
16547    struct sip_peer *peer;
16548 
16549    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
16550       /* locking of the object is not required because only the name and flags are being compared */
16551       if (!strncasecmp(word, peer->name, wordlen) &&
16552             (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
16553             ++which > state)
16554          result = ast_strdup(peer->name);
16555       unref_peer(peer, "toss iterator peer ptr before break");
16556       if (result) {
16557          break;
16558       }
16559    }
16560    ao2_iterator_destroy(&i);
16561    return result;
16562 }
16563 
16564 /*! \brief Do completion on registered peer name */
16565 static char *complete_sip_registered_peer(const char *word, int state, int flags2)
16566 {
16567        char *result = NULL;
16568        int wordlen = strlen(word);
16569        int which = 0;
16570        struct ao2_iterator i;
16571        struct sip_peer *peer;
16572        
16573        i = ao2_iterator_init(peers, 0);
16574        while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
16575           if (!strncasecmp(word, peer->name, wordlen) &&
16576          (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
16577          ++which > state && peer->expire > 0)
16578              result = ast_strdup(peer->name);
16579           if (result) {
16580              unref_peer(peer, "toss iterator peer ptr before break");
16581              break;
16582           }
16583           unref_peer(peer, "toss iterator peer ptr");
16584        }
16585        ao2_iterator_destroy(&i);
16586        return result;
16587 }
16588 
16589 /*! \brief Support routine for 'sip show history' CLI */
16590 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state)
16591 {
16592    if (pos == 3)
16593       return complete_sipch(line, word, pos, state);
16594 
16595    return NULL;
16596 }
16597 
16598 /*! \brief Support routine for 'sip show peer' CLI */
16599 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
16600 {
16601    if (pos == 3) {
16602       return complete_sip_peer(word, state, 0);
16603    }
16604 
16605    return NULL;
16606 }
16607 
16608 /*! \brief Support routine for 'sip unregister' CLI */
16609 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state)
16610 {
16611        if (pos == 2)
16612                return complete_sip_registered_peer(word, state, 0);
16613 
16614        return NULL;
16615 }
16616 
16617 /*! \brief Support routine for 'sip notify' CLI */
16618 static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
16619 {
16620    char *c = NULL;
16621 
16622    if (pos == 2) {
16623       int which = 0;
16624       char *cat = NULL;
16625       int wordlen = strlen(word);
16626 
16627       /* do completion for notify type */
16628 
16629       if (!notify_types)
16630          return NULL;
16631       
16632       while ( (cat = ast_category_browse(notify_types, cat)) ) {
16633          if (!strncasecmp(word, cat, wordlen) && ++which > state) {
16634             c = ast_strdup(cat);
16635             break;
16636          }
16637       }
16638       return c;
16639    }
16640 
16641    if (pos > 2)
16642       return complete_sip_peer(word, state, 0);
16643 
16644    return NULL;
16645 }
16646 
16647 /*! \brief Show details of one active dialog */
16648 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16649 {
16650    struct sip_pvt *cur;
16651    size_t len;
16652    int found = 0;
16653    struct ao2_iterator i;
16654 
16655    switch (cmd) {
16656    case CLI_INIT:
16657       e->command = "sip show channel";
16658       e->usage =
16659          "Usage: sip show channel <call-id>\n"
16660          "       Provides detailed status on a given SIP dialog (identified by SIP call-id).\n";
16661       return NULL;
16662    case CLI_GENERATE:
16663       return complete_sipch(a->line, a->word, a->pos, a->n);
16664    }
16665 
16666    if (a->argc != 4)
16667       return CLI_SHOWUSAGE;
16668    len = strlen(a->argv[3]);
16669    
16670    i = ao2_iterator_init(dialogs, 0);
16671    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
16672       sip_pvt_lock(cur);
16673 
16674       if (!strncasecmp(cur->callid, a->argv[3], len)) {
16675          char formatbuf[SIPBUFSIZE/2];
16676          ast_cli(a->fd, "\n");
16677          if (cur->subscribed != NONE)
16678             ast_cli(a->fd, "  * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
16679          else
16680             ast_cli(a->fd, "  * SIP Call\n");
16681          ast_cli(a->fd, "  Curr. trans. direction:  %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
16682          ast_cli(a->fd, "  Call-ID:                %s\n", cur->callid);
16683          ast_cli(a->fd, "  Owner channel ID:       %s\n", cur->owner ? cur->owner->name : "<none>");
16684          ast_cli(a->fd, "  Our Codec Capability:   %d\n", cur->capability);
16685          ast_cli(a->fd, "  Non-Codec Capability (DTMF):   %d\n", cur->noncodeccapability);
16686          ast_cli(a->fd, "  Their Codec Capability:   %d\n", cur->peercapability);
16687          ast_cli(a->fd, "  Joint Codec Capability:   %d\n", cur->jointcapability);
16688          ast_cli(a->fd, "  Format:                 %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
16689          ast_cli(a->fd, "  T.38 support            %s\n", cli_yesno(cur->udptl != NULL));
16690          ast_cli(a->fd, "  Video support           %s\n", cli_yesno(cur->vrtp != NULL));
16691          ast_cli(a->fd, "  MaxCallBR:              %d kbps\n", cur->maxcallbitrate);
16692          ast_cli(a->fd, "  Theoretical Address:    %s:%d\n", ast_inet_ntoa(cur->sa.sin_addr), ntohs(cur->sa.sin_port));
16693          ast_cli(a->fd, "  Received Address:       %s:%d\n", ast_inet_ntoa(cur->recv.sin_addr), ntohs(cur->recv.sin_port));
16694          ast_cli(a->fd, "  SIP Transfer mode:      %s\n", transfermode2str(cur->allowtransfer));
16695          ast_cli(a->fd, "  NAT Support:            %s\n", nat2str(ast_test_flag(&cur->flags[0], SIP_NAT)));
16696          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)" );
16697          ast_cli(a->fd, "  Our Tag:                %s\n", cur->tag);
16698          ast_cli(a->fd, "  Their Tag:              %s\n", cur->theirtag);
16699          ast_cli(a->fd, "  SIP User agent:         %s\n", cur->useragent);
16700          if (!ast_strlen_zero(cur->username))
16701             ast_cli(a->fd, "  Username:               %s\n", cur->username);
16702          if (!ast_strlen_zero(cur->peername))
16703             ast_cli(a->fd, "  Peername:               %s\n", cur->peername);
16704          if (!ast_strlen_zero(cur->uri))
16705             ast_cli(a->fd, "  Original uri:           %s\n", cur->uri);
16706          if (!ast_strlen_zero(cur->cid_num))
16707             ast_cli(a->fd, "  Caller-ID:              %s\n", cur->cid_num);
16708          ast_cli(a->fd, "  Need Destroy:           %s\n", cli_yesno(cur->needdestroy));
16709          ast_cli(a->fd, "  Last Message:           %s\n", cur->lastmsg);
16710          ast_cli(a->fd, "  Promiscuous Redir:      %s\n", cli_yesno(ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR)));
16711          ast_cli(a->fd, "  Route:                  %s\n", cur->route ? cur->route->hop : "N/A");
16712          ast_cli(a->fd, "  DTMF Mode:              %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
16713          ast_cli(a->fd, "  SIP Options:            ");
16714          if (cur->sipoptions) {
16715             int x;
16716             for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
16717                if (cur->sipoptions & sip_options[x].id)
16718                   ast_cli(a->fd, "%s ", sip_options[x].text);
16719             }
16720             ast_cli(a->fd, "\n");
16721          } else
16722             ast_cli(a->fd, "(none)\n");
16723 
16724          if (!cur->stimer)
16725             ast_cli(a->fd, "  Session-Timer:          Uninitiallized\n");
16726          else {
16727             ast_cli(a->fd, "  Session-Timer:          %s\n", cur->stimer->st_active ? "Active" : "Inactive");
16728             if (cur->stimer->st_active == TRUE) {
16729                ast_cli(a->fd, "  S-Timer Interval:       %d\n", cur->stimer->st_interval);
16730                ast_cli(a->fd, "  S-Timer Refresher:      %s\n", strefresher2str(cur->stimer->st_ref));
16731                ast_cli(a->fd, "  S-Timer Expirys:        %d\n", cur->stimer->st_expirys);
16732                ast_cli(a->fd, "  S-Timer Sched Id:       %d\n", cur->stimer->st_schedid);
16733                ast_cli(a->fd, "  S-Timer Peer Sts:       %s\n", cur->stimer->st_active_peer_ua ? "Active" : "Inactive");
16734                ast_cli(a->fd, "  S-Timer Cached Min-SE:  %d\n", cur->stimer->st_cached_min_se);
16735                ast_cli(a->fd, "  S-Timer Cached SE:      %d\n", cur->stimer->st_cached_max_se);
16736                ast_cli(a->fd, "  S-Timer Cached Ref:     %s\n", strefresher2str(cur->stimer->st_cached_ref));
16737                ast_cli(a->fd, "  S-Timer Cached Mode:    %s\n", stmode2str(cur->stimer->st_cached_mode));
16738             }
16739          }
16740 
16741          ast_cli(a->fd, "\n\n");
16742 
16743          found++;
16744       }
16745 
16746       sip_pvt_unlock(cur);
16747 
16748       ao2_t_ref(cur, -1, "toss dialog ptr set by iterator_next");
16749    }
16750    ao2_iterator_destroy(&i);
16751 
16752    if (!found) 
16753       ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
16754 
16755    return CLI_SUCCESS;
16756 }
16757 
16758 /*! \brief Show history details of one dialog */
16759 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16760 {
16761    struct sip_pvt *cur;
16762    size_t len;
16763    int found = 0;
16764    struct ao2_iterator i;
16765 
16766    switch (cmd) {
16767    case CLI_INIT:
16768       e->command = "sip show history";
16769       e->usage =
16770          "Usage: sip show history <call-id>\n"
16771          "       Provides detailed dialog history on a given SIP call (specified by call-id).\n";
16772       return NULL;
16773    case CLI_GENERATE:
16774       return complete_sip_show_history(a->line, a->word, a->pos, a->n);
16775    }
16776 
16777    if (a->argc != 4)
16778       return CLI_SHOWUSAGE;
16779 
16780    if (!recordhistory)
16781       ast_cli(a->fd, "\n***Note: History recording is currently DISABLED.  Use 'sip set history on' to ENABLE.\n");
16782 
16783    len = strlen(a->argv[3]);
16784 
16785    i = ao2_iterator_init(dialogs, 0);
16786    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
16787       sip_pvt_lock(cur);
16788       if (!strncasecmp(cur->callid, a->argv[3], len)) {
16789          struct sip_history *hist;
16790          int x = 0;
16791 
16792          ast_cli(a->fd, "\n");
16793          if (cur->subscribed != NONE)
16794             ast_cli(a->fd, "  * Subscription\n");
16795          else
16796             ast_cli(a->fd, "  * SIP Call\n");
16797          if (cur->history)
16798             AST_LIST_TRAVERSE(cur->history, hist, list)
16799                ast_cli(a->fd, "%d. %s\n", ++x, hist->event);
16800          if (x == 0)
16801             ast_cli(a->fd, "Call '%s' has no history\n", cur->callid);
16802          found++;
16803       }
16804       sip_pvt_unlock(cur);
16805       ao2_t_ref(cur, -1, "toss dialog ptr from iterator_next");
16806    }
16807    ao2_iterator_destroy(&i);
16808 
16809    if (!found) 
16810       ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
16811 
16812    return CLI_SUCCESS;
16813 }
16814 
16815 /*! \brief Dump SIP history to debug log file at end of lifespan for SIP dialog */
16816 static void sip_dump_history(struct sip_pvt *dialog)
16817 {
16818    int x = 0;
16819    struct sip_history *hist;
16820    static int errmsg = 0;
16821 
16822    if (!dialog)
16823       return;
16824 
16825    if (!option_debug && !sipdebug) {
16826       if (!errmsg) {
16827          ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
16828          errmsg = 1;
16829       }
16830       return;
16831    }
16832 
16833    ast_debug(1, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
16834    if (dialog->subscribed)
16835       ast_debug(1, "  * Subscription\n");
16836    else
16837       ast_debug(1, "  * SIP Call\n");
16838    if (dialog->history)
16839       AST_LIST_TRAVERSE(dialog->history, hist, list)
16840          ast_debug(1, "  %-3.3d. %s\n", ++x, hist->event);
16841    if (!x)
16842       ast_debug(1, "Call '%s' has no history\n", dialog->callid);
16843    ast_debug(1, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
16844 }
16845 
16846 
16847 /*! \brief  Receive SIP INFO Message */
16848 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
16849 {
16850    char buf[1024];
16851    unsigned int event;
16852    const char *c = get_header(req, "Content-Type");
16853 
16854    /* Need to check the media/type */
16855    if (!strcasecmp(c, "application/dtmf-relay") ||
16856        !strcasecmp(c, "application/vnd.nortelnetworks.digits")) {
16857       unsigned int duration = 0;
16858 
16859       if (!p->owner) {  /* not a PBX call */
16860          transmit_response(p, "481 Call leg/transaction does not exist", req);
16861          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16862          return;
16863       }
16864 
16865       /* Try getting the "signal=" part */
16866       if (ast_strlen_zero(c = get_body(req, "Signal", '=')) && ast_strlen_zero(c = get_body(req, "d", '='))) {
16867          ast_log(LOG_WARNING, "Unable to retrieve DTMF signal from INFO message from %s\n", p->callid);
16868          transmit_response(p, "200 OK", req); /* Should return error */
16869          return;
16870       } else {
16871          ast_copy_string(buf, c, sizeof(buf));
16872       }
16873 
16874       if (!ast_strlen_zero((c = get_body(req, "Duration", '='))))
16875          duration = atoi(c);
16876       if (!duration)
16877          duration = 100; /* 100 ms */
16878 
16879 
16880       if (ast_strlen_zero(buf)) {
16881          transmit_response(p, "200 OK", req);
16882          return;
16883       }
16884 
16885       if (buf[0] == '*')
16886          event = 10;
16887       else if (buf[0] == '#')
16888          event = 11;
16889       else if ((buf[0] >= 'A') && (buf[0] <= 'D'))
16890          event = 12 + buf[0] - 'A';
16891       else if (buf[0] == '!')
16892          event = 16;
16893       else
16894          event = atoi(buf);
16895       if (event == 16) {
16896          /* send a FLASH event */
16897          struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
16898          ast_queue_frame(p->owner, &f);
16899          if (sipdebug)
16900             ast_verbose("* DTMF-relay event received: FLASH\n");
16901       } else {
16902          /* send a DTMF event */
16903          struct ast_frame f = { AST_FRAME_DTMF, };
16904          if (event < 10) {
16905             f.subclass = '0' + event;
16906          } else if (event < 11) {
16907             f.subclass = '*';
16908          } else if (event < 12) {
16909             f.subclass = '#';
16910          } else if (event < 16) {
16911             f.subclass = 'A' + (event - 12);
16912          }
16913          f.len = duration;
16914          ast_queue_frame(p->owner, &f);
16915          if (sipdebug)
16916             ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
16917       }
16918       transmit_response(p, "200 OK", req);
16919       return;
16920    } else if (!strcasecmp(c, "application/dtmf")) {
16921       /*! \todo Note: Doesn't read the duration of the DTMF. Should be fixed. */
16922       unsigned int duration = 0;
16923 
16924       if (!p->owner) {  /* not a PBX call */
16925          transmit_response(p, "481 Call leg/transaction does not exist", req);
16926          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16927          return;
16928       }
16929 
16930       get_msg_text(buf, sizeof(buf), req, TRUE);
16931       duration = 100; /* 100 ms */
16932 
16933       if (ast_strlen_zero(buf)) {
16934          transmit_response(p, "200 OK", req);
16935          return;
16936       }
16937       event = atoi(buf);
16938       if (event == 16) {
16939          /* send a FLASH event */
16940          struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
16941          ast_queue_frame(p->owner, &f);
16942          if (sipdebug)
16943             ast_verbose("* DTMF-relay event received: FLASH\n");
16944       } else {
16945          /* send a DTMF event */
16946          struct ast_frame f = { AST_FRAME_DTMF, };
16947          if (event < 10) {
16948             f.subclass = '0' + event;
16949          } else if (event < 11) {
16950             f.subclass = '*';
16951          } else if (event < 12) {
16952             f.subclass = '#';
16953          } else if (event < 16) {
16954             f.subclass = 'A' + (event - 12);
16955          }
16956          f.len = duration;
16957          ast_queue_frame(p->owner, &f);
16958          if (sipdebug)
16959             ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
16960       }
16961       transmit_response(p, "200 OK", req);
16962       return;
16963 
16964    } else if (!strcasecmp(c, "application/media_control+xml")) {
16965       /* Eh, we'll just assume it's a fast picture update for now */
16966       if (p->owner)
16967          ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
16968       transmit_response(p, "200 OK", req);
16969       return;
16970    } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
16971       /* Client code (from SNOM phone) */
16972       if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
16973          if (p->owner && p->owner->cdr)
16974             ast_cdr_setuserfield(p->owner, c);
16975          if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
16976             ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
16977          transmit_response(p, "200 OK", req);
16978       } else {
16979          transmit_response(p, "403 Forbidden", req);
16980       }
16981       return;
16982    } else if (!ast_strlen_zero(c = get_header(req, "Record"))) {
16983       /* INFO messages generated by some phones to start/stop recording
16984          on phone calls. 
16985          OEJ: I think this should be something that is enabled/disabled
16986          per device. I don't want incoming callers to record calls in my
16987          pbx.
16988       */
16989       /* first, get the feature string, if it exists */
16990       struct ast_call_feature *feat;
16991       int j;
16992       struct ast_frame f = { AST_FRAME_DTMF, };
16993 
16994       ast_rdlock_call_features();
16995       feat = ast_find_call_feature("automon");
16996       if (!feat || ast_strlen_zero(feat->exten)) {
16997          ast_log(LOG_WARNING, "Recording requested, but no One Touch Monitor registered. (See features.conf)\n");
16998          /* 403 means that we don't support this feature, so don't request it again */
16999          transmit_response(p, "403 Forbidden", req);
17000          ast_unlock_call_features();
17001          return;
17002       } 
17003       /* Send the feature code to the PBX as DTMF, just like the handset had sent it */
17004       f.len = 100;
17005       for (j=0; j < strlen(feat->exten); j++) {
17006          f.subclass = feat->exten[j];
17007          ast_queue_frame(p->owner, &f);
17008          if (sipdebug)
17009             ast_verbose("* DTMF-relay event faked: %c\n", f.subclass);
17010       }
17011       ast_unlock_call_features();
17012 
17013       ast_debug(1, "Got a Request to Record the channel, state %s\n", c);
17014       transmit_response(p, "200 OK", req);
17015       return;
17016    } else if (ast_strlen_zero(c = get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
17017       /* This is probably just a packet making sure the signalling is still up, just send back a 200 OK */
17018       transmit_response(p, "200 OK", req);
17019       return;
17020    }
17021 
17022    /* Other type of INFO message, not really understood by Asterisk */
17023    /* if (get_msg_text(buf, sizeof(buf), req)) { */
17024 
17025    ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
17026    transmit_response(p, "415 Unsupported media type", req);
17027    return;
17028 }
17029 
17030 /*! \brief Enable SIP Debugging for a single IP */
17031 static char *sip_do_debug_ip(int fd, char *arg)
17032 {
17033    struct hostent *hp;
17034    struct ast_hostent ahp;
17035    int port = 0;
17036    char *p;
17037 
17038    p = arg;
17039    strsep(&p, ":");
17040    if (p)
17041       port = atoi(p);
17042    hp = ast_gethostbyname(arg, &ahp);
17043    if (hp == NULL)
17044       return CLI_SHOWUSAGE;
17045 
17046    debugaddr.sin_family = AF_INET;
17047    memcpy(&debugaddr.sin_addr, hp->h_addr, sizeof(debugaddr.sin_addr));
17048    debugaddr.sin_port = htons(port);
17049    if (port == 0)
17050       ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_inet_ntoa(debugaddr.sin_addr));
17051    else
17052       ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), port);
17053 
17054    sipdebug |= sip_debug_console;
17055 
17056    return CLI_SUCCESS;
17057 }
17058 
17059 /*! \brief  Turn on SIP debugging for a given peer */
17060 static char *sip_do_debug_peer(int fd, char *arg)
17061 {
17062    struct sip_peer *peer = find_peer(arg, NULL, TRUE, FINDPEERS, FALSE, 0);
17063    if (!peer)
17064       ast_cli(fd, "No such peer '%s'\n", arg);
17065    else if (peer->addr.sin_addr.s_addr == 0)
17066       ast_cli(fd, "Unable to get IP address of peer '%s'\n", arg);
17067    else {
17068       debugaddr.sin_family = AF_INET;
17069       debugaddr.sin_addr = peer->addr.sin_addr;
17070       debugaddr.sin_port = peer->addr.sin_port;
17071       ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n",
17072          ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
17073       sipdebug |= sip_debug_console;
17074    }
17075    if (peer)
17076       unref_peer(peer, "sip_do_debug_peer: unref_peer, from find_peer call");
17077    return CLI_SUCCESS;
17078 }
17079 
17080 /*! \brief Turn on SIP debugging (CLI command) */
17081 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17082 {
17083    int oldsipdebug = sipdebug & sip_debug_console;
17084    char *what;
17085 
17086    if (cmd == CLI_INIT) {
17087       e->command = "sip set debug {on|off|ip|peer}";
17088       e->usage =
17089          "Usage: sip set debug {off|on|ip addr[:port]|peer peername}\n"
17090          "       Globally disables dumping of SIP packets,\n"
17091          "       or enables it either globally or for a (single)\n"
17092          "       IP address or registered peer.\n";
17093       return NULL;
17094    } else if (cmd == CLI_GENERATE) {
17095       if (a->pos == 4 && !strcasecmp(a->argv[3], "peer")) 
17096          return complete_sip_peer(a->word, a->n, 0);
17097       return NULL;
17098         }
17099 
17100    what = a->argv[e->args-1];      /* guaranteed to exist */
17101    if (a->argc == e->args) {       /* on/off */
17102       if (!strcasecmp(what, "on")) {
17103          sipdebug |= sip_debug_console;
17104          sipdebug_text = 1;   /*! \note this can be a special debug command - "sip debug text" or something */
17105          memset(&debugaddr, 0, sizeof(debugaddr));
17106          ast_cli(a->fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
17107          return CLI_SUCCESS;
17108       } else if (!strcasecmp(what, "off")) {
17109          sipdebug &= ~sip_debug_console;
17110          sipdebug_text = 0;
17111          ast_cli(a->fd, "SIP Debugging Disabled\n");
17112          return CLI_SUCCESS;
17113       }
17114    } else if (a->argc == e->args +1) {/* ip/peer */
17115       if (!strcasecmp(what, "ip"))
17116          return sip_do_debug_ip(a->fd, a->argv[e->args]);
17117       else if (!strcasecmp(what, "peer"))
17118          return sip_do_debug_peer(a->fd, a->argv[e->args]);
17119    }
17120    return CLI_SHOWUSAGE;   /* default, failure */
17121 }
17122 
17123 /*! \brief Cli command to send SIP notify to peer */
17124 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17125 {
17126    struct ast_variable *varlist;
17127    int i;
17128 
17129    switch (cmd) {
17130    case CLI_INIT:
17131       e->command = "sip notify";
17132       e->usage =
17133          "Usage: sip notify <type> <peer> [<peer>...]\n"
17134          "       Send a NOTIFY message to a SIP peer or peers\n"
17135          "       Message types are defined in sip_notify.conf\n";
17136       return NULL;
17137    case CLI_GENERATE:
17138       return complete_sipnotify(a->line, a->word, a->pos, a->n);
17139    }
17140 
17141    if (a->argc < 4)
17142       return CLI_SHOWUSAGE;
17143 
17144    if (!notify_types) {
17145       ast_cli(a->fd, "No %s file found, or no types listed there\n", notify_config);
17146       return CLI_FAILURE;
17147    }
17148 
17149    varlist = ast_variable_browse(notify_types, a->argv[2]);
17150 
17151    if (!varlist) {
17152       ast_cli(a->fd, "Unable to find notify type '%s'\n", a->argv[2]);
17153       return CLI_FAILURE;
17154    }
17155 
17156    for (i = 3; i < a->argc; i++) {
17157       struct sip_pvt *p;
17158 
17159       if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
17160          ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
17161          return CLI_FAILURE;
17162       }
17163 
17164       if (create_addr(p, a->argv[i], NULL, 1)) {
17165          /* Maybe they're not registered, etc. */
17166          dialog_unlink_all(p, TRUE, TRUE);
17167          dialog_unref(p, "unref dialog inside for loop" );
17168          /* sip_destroy(p); */
17169          ast_cli(a->fd, "Could not create address for '%s'\n", a->argv[i]);
17170          continue;
17171       }
17172 
17173       /* Notify is outgoing call */
17174       ast_set_flag(&p->flags[0], SIP_OUTGOING);
17175 
17176       /* Recalculate our side, and recalculate Call ID */
17177       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
17178       build_via(p);
17179       ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
17180       build_callid_pvt(p);
17181       ao2_t_link(dialogs, p, "Linking in new name");
17182       ast_cli(a->fd, "Sending NOTIFY of type '%s' to '%s'\n", a->argv[2], a->argv[i]);
17183       dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
17184       sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
17185       transmit_notify_custom(p, varlist);
17186    }
17187 
17188    return CLI_SUCCESS;
17189 }
17190 
17191 /*! \brief Enable/Disable SIP History logging (CLI) */
17192 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17193 {
17194    switch (cmd) {
17195    case CLI_INIT:
17196       e->command = "sip set history {on|off}";
17197       e->usage =
17198          "Usage: sip set history {on|off}\n"
17199          "       Enables/Disables recording of SIP dialog history for debugging purposes.\n"
17200          "       Use 'sip show history' to view the history of a call number.\n";
17201       return NULL;
17202    case CLI_GENERATE:
17203       return NULL;
17204    }
17205 
17206    if (a->argc != e->args)
17207       return CLI_SHOWUSAGE;
17208 
17209    if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
17210       recordhistory = TRUE;
17211       ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
17212    } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
17213       recordhistory = FALSE;
17214       ast_cli(a->fd, "SIP History Recording Disabled\n");
17215    } else {
17216       return CLI_SHOWUSAGE;
17217    }
17218    return CLI_SUCCESS;
17219 }
17220 
17221 /*! \brief Authenticate for outbound registration */
17222 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code)
17223 {
17224    char *header, *respheader;
17225    char digest[1024];
17226 
17227    p->authtries++;
17228    auth_headers(code, &header, &respheader);
17229    memset(digest, 0, sizeof(digest));
17230    if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
17231       /* There's nothing to use for authentication */
17232       /* No digest challenge in request */
17233       if (sip_debug_test_pvt(p) && p->registry)
17234          ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
17235          /* No old challenge */
17236       return -1;
17237    }
17238    if (p->do_history)
17239       append_history(p, "RegistryAuth", "Try: %d", p->authtries);
17240    if (sip_debug_test_pvt(p) && p->registry)
17241       ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
17242    return transmit_register(p->registry, SIP_REGISTER, digest, respheader); 
17243 }
17244 
17245 /*! \brief Add authentication on outbound SIP packet */
17246 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code, int sipmethod, int init)
17247 {
17248    char *header, *respheader;
17249    char digest[1024];
17250 
17251    if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
17252       return -2;
17253 
17254    p->authtries++;
17255    auth_headers(code, &header, &respheader);
17256    ast_debug(2, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
17257    memset(digest, 0, sizeof(digest));
17258    if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
17259       /* No way to authenticate */
17260       return -1;
17261    }
17262    /* Now we have a reply digest */
17263    p->options->auth = digest;
17264    p->options->authheader = respheader;
17265    return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init); 
17266 }
17267 
17268 /*! \brief  reply to authentication for outbound registrations
17269 \return  Returns -1 if we have no auth 
17270 \note This is used for register= servers in sip.conf, SIP proxies we register
17271    with  for receiving calls from.  */
17272 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod,  char *digest, int digest_len)
17273 {
17274    char tmp[512];
17275    char *c;
17276    char oldnonce[256];
17277 
17278    /* table of recognised keywords, and places where they should be copied */
17279    const struct x {
17280       const char *key;
17281       const ast_string_field *field;
17282    } *i, keys[] = {
17283       { "realm=", &p->realm },
17284       { "nonce=", &p->nonce },
17285       { "opaque=", &p->opaque },
17286       { "qop=", &p->qop },
17287       { "domain=", &p->domain },
17288       { NULL, 0 },
17289    };
17290 
17291    ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
17292    if (ast_strlen_zero(tmp)) 
17293       return -1;
17294    if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
17295       ast_log(LOG_WARNING, "missing Digest.\n");
17296       return -1;
17297    }
17298    c = tmp + strlen("Digest ");
17299    ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
17300    while (c && *(c = ast_skip_blanks(c))) {  /* lookup for keys */
17301       for (i = keys; i->key != NULL; i++) {
17302          char *src, *separator;
17303          if (strncasecmp(c, i->key, strlen(i->key)) != 0)
17304             continue;
17305          /* Found. Skip keyword, take text in quotes or up to the separator. */
17306          c += strlen(i->key);
17307          if (*c == '"') {
17308             src = ++c;
17309             separator = "\"";
17310          } else {
17311             src = c;
17312             separator = ",";
17313          }
17314          strsep(&c, separator); /* clear separator and move ptr */
17315          ast_string_field_ptr_set(p, i->field, src);
17316          break;
17317       }
17318       if (i->key == NULL) /* not found, try ',' */
17319          strsep(&c, ",");
17320    }
17321    /* Reset nonce count */
17322    if (strcmp(p->nonce, oldnonce)) 
17323       p->noncecount = 0;
17324 
17325    /* Save auth data for following registrations */
17326    if (p->registry) {
17327       struct sip_registry *r = p->registry;
17328 
17329       if (strcmp(r->nonce, p->nonce)) {
17330          ast_string_field_set(r, realm, p->realm);
17331          ast_string_field_set(r, nonce, p->nonce);
17332          ast_string_field_set(r, domain, p->domain);
17333          ast_string_field_set(r, opaque, p->opaque);
17334          ast_string_field_set(r, qop, p->qop);
17335          r->noncecount = 0;
17336       }
17337    }
17338    return build_reply_digest(p, sipmethod, digest, digest_len); 
17339 }
17340 
17341 /*! \brief  Build reply digest 
17342 \return  Returns -1 if we have no auth 
17343 \note Build digest challenge for authentication of registrations and calls
17344    Also used for authentication of BYE 
17345 */
17346 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
17347 {
17348    char a1[256];
17349    char a2[256];
17350    char a1_hash[256];
17351    char a2_hash[256];
17352    char resp[256];
17353    char resp_hash[256];
17354    char uri[256];
17355    char opaque[256] = "";
17356    char cnonce[80];
17357    const char *username;
17358    const char *secret;
17359    const char *md5secret;
17360    struct sip_auth *auth = NULL; /* Realm authentication */
17361 
17362    if (!ast_strlen_zero(p->domain))
17363       ast_copy_string(uri, p->domain, sizeof(uri));
17364    else if (!ast_strlen_zero(p->uri))
17365       ast_copy_string(uri, p->uri, sizeof(uri));
17366    else
17367       snprintf(uri, sizeof(uri), "sip:%s@%s", p->username, ast_inet_ntoa(p->sa.sin_addr));
17368 
17369    snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
17370 
17371    /* Check if we have separate auth credentials */
17372    if(!(auth = find_realm_authentication(p->peerauth, p->realm))) /* Start with peer list */
17373       auth = find_realm_authentication(authl, p->realm); /* If not, global list */
17374 
17375    if (auth) {
17376       ast_debug(3, "use realm [%s] from peer [%s][%s]\n", auth->username, p->peername, p->username);
17377       username = auth->username;
17378       secret = auth->secret;
17379       md5secret = auth->md5secret;
17380       if (sipdebug)
17381          ast_debug(1, "Using realm %s authentication for call %s\n", p->realm, p->callid);
17382    } else {
17383       /* No authentication, use peer or register= config */
17384       username = p->authname;
17385       secret =  p->peersecret;
17386       md5secret = p->peermd5secret;
17387    }
17388    if (ast_strlen_zero(username))   /* We have no authentication */
17389       return -1;
17390 
17391    /* Calculate SIP digest response */
17392    snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
17393    snprintf(a2, sizeof(a2), "%s:%s", sip_methods[method].text, uri);
17394    if (!ast_strlen_zero(md5secret))
17395       ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
17396    else
17397       ast_md5_hash(a1_hash, a1);
17398    ast_md5_hash(a2_hash, a2);
17399 
17400    p->noncecount++;
17401    if (!ast_strlen_zero(p->qop))
17402       snprintf(resp, sizeof(resp), "%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
17403    else
17404       snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, p->nonce, a2_hash);
17405    ast_md5_hash(resp_hash, resp);
17406 
17407    /* only include the opaque string if it's set */
17408    if (!ast_strlen_zero(p->opaque)) {
17409      snprintf(opaque, sizeof(opaque), ", opaque=\"%s\"", p->opaque);
17410    }
17411 
17412    /* XXX We hard code our qop to "auth" for now.  XXX */
17413    if (!ast_strlen_zero(p->qop))
17414       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);
17415    else
17416       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);
17417 
17418    append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
17419 
17420    return 0;
17421 }
17422    
17423 /*! \brief Read SIP header (dialplan function) */
17424 static int func_header_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len) 
17425 {
17426    struct sip_pvt *p;
17427    const char *content = NULL;
17428    AST_DECLARE_APP_ARGS(args,
17429       AST_APP_ARG(header);
17430       AST_APP_ARG(number);
17431    );
17432    int i, number, start = 0;
17433 
17434    if (ast_strlen_zero(data)) {
17435       ast_log(LOG_WARNING, "This function requires a header name.\n");
17436       return -1;
17437    }
17438 
17439    ast_channel_lock(chan);
17440    if (!IS_SIP_TECH(chan->tech)) {
17441       ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
17442       ast_channel_unlock(chan);
17443       return -1;
17444    }
17445 
17446    AST_STANDARD_APP_ARGS(args, data);
17447    if (!args.number) {
17448       number = 1;
17449    } else {
17450       sscanf(args.number, "%30d", &number);
17451       if (number < 1)
17452          number = 1;
17453    }
17454 
17455    p = chan->tech_pvt;
17456 
17457    /* If there is no private structure, this channel is no longer alive */
17458    if (!p) {
17459       ast_channel_unlock(chan);
17460       return -1;
17461    }
17462 
17463    for (i = 0; i < number; i++)
17464       content = __get_header(&p->initreq, args.header, &start);
17465 
17466    if (ast_strlen_zero(content)) {
17467       ast_channel_unlock(chan);
17468       return -1;
17469    }
17470 
17471    ast_copy_string(buf, content, len);
17472    ast_channel_unlock(chan);
17473 
17474    return 0;
17475 }
17476 
17477 static struct ast_custom_function sip_header_function = {
17478    .name = "SIP_HEADER",
17479    .read = func_header_read,
17480 };
17481 
17482 /*! \brief  Dial plan function to check if domain is local */
17483 static int func_check_sipdomain(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
17484 {
17485    if (ast_strlen_zero(data)) {
17486       ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
17487       return -1;
17488    }
17489    if (check_sip_domain(data, NULL, 0))
17490       ast_copy_string(buf, data, len);
17491    else
17492       buf[0] = '\0';
17493    return 0;
17494 }
17495 
17496 static struct ast_custom_function checksipdomain_function = {
17497    .name = "CHECKSIPDOMAIN",
17498    .read = func_check_sipdomain,
17499 };
17500 
17501 /*! \brief  ${SIPPEER()} Dialplan function - reads peer data */
17502 static int function_sippeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
17503 {
17504    struct sip_peer *peer;
17505    char *colname;
17506 
17507    if ((colname = strchr(data, ':'))) {   /*! \todo Will be deprecated after 1.4 */
17508       static int deprecation_warning = 0;
17509       *colname++ = '\0';
17510       if (deprecation_warning++ % 10 == 0)
17511          ast_log(LOG_WARNING, "SIPPEER(): usage of ':' to separate arguments is deprecated.  Please use ',' instead.\n");
17512    } else if ((colname = strchr(data, ',')))
17513       *colname++ = '\0';
17514    else
17515       colname = "ip";
17516 
17517    if (!(peer = find_peer(data, NULL, TRUE, FINDPEERS, FALSE, 0)))
17518       return -1;
17519 
17520    if (!strcasecmp(colname, "ip")) {
17521       ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len);
17522    } else  if (!strcasecmp(colname, "port")) {
17523       snprintf(buf, len, "%d", ntohs(peer->addr.sin_port));
17524    } else  if (!strcasecmp(colname, "status")) {
17525       peer_status(peer, buf, len);
17526    } else  if (!strcasecmp(colname, "language")) {
17527       ast_copy_string(buf, peer->language, len);
17528    } else  if (!strcasecmp(colname, "regexten")) {
17529       ast_copy_string(buf, peer->regexten, len);
17530    } else  if (!strcasecmp(colname, "limit")) {
17531       snprintf(buf, len, "%d", peer->call_limit);
17532    } else  if (!strcasecmp(colname, "busylevel")) {
17533       snprintf(buf, len, "%d", peer->busy_level);
17534    } else  if (!strcasecmp(colname, "curcalls")) {
17535       snprintf(buf, len, "%d", peer->inUse);
17536    } else  if (!strcasecmp(colname, "accountcode")) {
17537       ast_copy_string(buf, peer->accountcode, len);
17538    } else  if (!strcasecmp(colname, "callgroup")) {
17539       ast_print_group(buf, len, peer->callgroup);
17540    } else  if (!strcasecmp(colname, "pickupgroup")) {
17541       ast_print_group(buf, len, peer->pickupgroup);
17542    } else  if (!strcasecmp(colname, "useragent")) {
17543       ast_copy_string(buf, peer->useragent, len);
17544    } else  if (!strcasecmp(colname, "mailbox")) {
17545       struct ast_str *mailbox_str = ast_str_alloca(512);
17546       peer_mailboxes_to_str(&mailbox_str, peer);
17547       ast_copy_string(buf, mailbox_str->str, len);
17548    } else  if (!strcasecmp(colname, "context")) {
17549       ast_copy_string(buf, peer->context, len);
17550    } else  if (!strcasecmp(colname, "expire")) {
17551       snprintf(buf, len, "%d", peer->expire);
17552    } else  if (!strcasecmp(colname, "dynamic")) {
17553       ast_copy_string(buf, peer->host_dynamic ? "yes" : "no", len);
17554    } else  if (!strcasecmp(colname, "callerid_name")) {
17555       ast_copy_string(buf, peer->cid_name, len);
17556    } else  if (!strcasecmp(colname, "callerid_num")) {
17557       ast_copy_string(buf, peer->cid_num, len);
17558    } else  if (!strcasecmp(colname, "codecs")) {
17559       ast_getformatname_multiple(buf, len -1, peer->capability);
17560    } else  if (!strncasecmp(colname, "chanvar[", 8)) {
17561       char *chanvar=colname + 8;
17562       struct ast_variable *v;
17563    
17564       chanvar = strsep(&chanvar, "]");
17565       for (v = peer->chanvars ; v ; v = v->next) {
17566          if (!strcasecmp(v->name, chanvar)) {
17567             ast_copy_string(buf, v->value, len);
17568          }
17569       }
17570    } else  if (!strncasecmp(colname, "codec[", 6)) {
17571       char *codecnum;
17572       int codec = 0;
17573       
17574       codecnum = colname + 6; /* move past the '[' */
17575       codecnum = strsep(&codecnum, "]"); /* trim trailing ']' if any */
17576       if((codec = ast_codec_pref_index(&peer->prefs, atoi(codecnum)))) {
17577          ast_copy_string(buf, ast_getformatname(codec), len);
17578       } else {
17579          buf[0] = '\0';
17580       }
17581    } else {
17582       buf[0] = '\0';
17583    }
17584 
17585    unref_peer(peer, "unref_peer from function_sippeer, just before return");
17586 
17587    return 0;
17588 }
17589 
17590 /*! \brief Structure to declare a dialplan function: SIPPEER */
17591 static struct ast_custom_function sippeer_function = {
17592    .name = "SIPPEER",
17593    .read = function_sippeer,
17594 };
17595 
17596 /*! \brief ${SIPCHANINFO()} Dialplan function - reads sip channel data */
17597 static int function_sipchaninfo_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
17598 {
17599    struct sip_pvt *p;
17600    static int deprecated = 0;
17601 
17602    *buf = 0;
17603    
17604    if (!data) {
17605       ast_log(LOG_WARNING, "This function requires a parameter name.\n");
17606       return -1;
17607    }
17608 
17609    ast_channel_lock(chan);
17610    if (!IS_SIP_TECH(chan->tech)) {
17611       ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
17612       ast_channel_unlock(chan);
17613       return -1;
17614    }
17615 
17616    if (deprecated++ % 20 == 0) {
17617       /* Deprecated in 1.6.1 */
17618       ast_log(LOG_WARNING, "SIPCHANINFO() is deprecated.  Please transition to using CHANNEL().\n");
17619    }
17620 
17621    p = chan->tech_pvt;
17622 
17623    /* If there is no private structure, this channel is no longer alive */
17624    if (!p) {
17625       ast_channel_unlock(chan);
17626       return -1;
17627    }
17628 
17629    if (!strcasecmp(data, "peerip")) {
17630       ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", len);
17631    } else  if (!strcasecmp(data, "recvip")) {
17632       ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", len);
17633    } else  if (!strcasecmp(data, "from")) {
17634       ast_copy_string(buf, p->from, len);
17635    } else  if (!strcasecmp(data, "uri")) {
17636       ast_copy_string(buf, p->uri, len);
17637    } else  if (!strcasecmp(data, "useragent")) {
17638       ast_copy_string(buf, p->useragent, len);
17639    } else  if (!strcasecmp(data, "peername")) {
17640       ast_copy_string(buf, p->peername, len);
17641    } else if (!strcasecmp(data, "t38passthrough")) {
17642       if (p->t38.state == T38_DISABLED) {
17643          ast_copy_string(buf, "0", len);
17644       } else { /* T38 is offered or enabled in this call */
17645          ast_copy_string(buf, "1", len);
17646       }
17647    } else {
17648       ast_channel_unlock(chan);
17649       return -1;
17650    }
17651    ast_channel_unlock(chan);
17652 
17653    return 0;
17654 }
17655 
17656 /*! \brief Structure to declare a dialplan function: SIPCHANINFO */
17657 static struct ast_custom_function sipchaninfo_function = {
17658    .name = "SIPCHANINFO",
17659    .read = function_sipchaninfo_read,
17660 };
17661 
17662 /*! \brief Parse 302 Moved temporalily response 
17663    \todo XXX Doesn't redirect over TLS on sips: uri's.
17664       If we get a redirect to a SIPS: uri, this needs to be going back to the
17665       dialplan (this is a request for a secure signalling path).
17666       Note that transport=tls is deprecated, but we need to support it on incoming requests.
17667 */
17668 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req)
17669 {
17670    char tmp[SIPBUFSIZE];
17671    char *s, *e, *t, *trans;
17672    char *domain;
17673    enum sip_transport transport = SIP_TRANSPORT_UDP;
17674 
17675    ast_copy_string(tmp, get_header(req, "Contact"), sizeof(tmp));
17676    if ((t = strchr(tmp, ',')))
17677       *t = '\0';
17678 
17679    s = get_in_brackets(tmp);
17680    if ((trans = strcasestr(s, ";transport="))) do {
17681       trans += 11;
17682 
17683       if ((e = strchr(trans, ';')))
17684          *e = '\0';
17685 
17686       if (!strncasecmp(trans, "tcp", 3))
17687          transport = SIP_TRANSPORT_TCP;
17688       else if (!strncasecmp(trans, "tls", 3))
17689          transport = SIP_TRANSPORT_TLS;
17690       else {
17691          if (strncasecmp(trans, "udp", 3))
17692             ast_debug(1, "received contact with an invalid transport, '%s'\n", s);
17693          /* This will assume UDP for all unknown transports */
17694          transport = SIP_TRANSPORT_UDP;
17695       }
17696    } while(0);
17697    s = remove_uri_parameters(s);
17698 
17699    if (p->socket.tcptls_session) {
17700       ao2_ref(p->socket.tcptls_session, -1);
17701       p->socket.tcptls_session = NULL;
17702    }
17703 
17704    set_socket_transport(&p->socket, transport);
17705 
17706    if (ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
17707       char *host = NULL;
17708       if (!strncasecmp(s, "sip:", 4))
17709          s += 4;
17710       else if (!strncasecmp(s, "sips:", 5))
17711          s += 5;
17712       e = strchr(s, '/');
17713       if (e)
17714          *e = '\0';
17715       if ((host = strchr(s, '@'))) {
17716          *host++ = '\0';
17717          ast_debug(2, "Found promiscuous redirection to 'SIP/%s::::%s@%s'\n", s, get_transport(transport), host);
17718          if (p->owner)
17719             ast_string_field_build(p->owner, call_forward, "SIP/%s::::%s@%s", s, get_transport(transport), host);
17720       } else {
17721          ast_debug(2, "Found promiscuous redirection to 'SIP/::::%s@%s'\n", get_transport(transport), s);
17722          if (p->owner)
17723             ast_string_field_build(p->owner, call_forward, "SIP/::::%s@%s", get_transport(transport), s);
17724       }
17725    } else {
17726       e = strchr(tmp, '@');
17727       if (e) {
17728          *e++ = '\0';
17729          domain = e;
17730       } else {
17731          /* No username part */
17732          domain = tmp;
17733       }
17734       e = strchr(tmp, '/');   /* WHEN do we hae a forward slash in the URI? */
17735       if (e)
17736          *e = '\0';
17737 
17738       if (!strncasecmp(s, "sip:", 4))
17739          s += 4;
17740       else if (!strncasecmp(s, "sips:", 5))
17741          s += 5;
17742       e = strchr(s, ';');  /* And username ; parameters? */
17743       if (e)
17744          *e = '\0';  
17745       ast_uri_decode(s);
17746       ast_debug(2, "Received 302 Redirect to extension '%s' (domain %s)\n", s, domain);
17747       if (p->owner) {
17748          pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
17749          ast_string_field_set(p->owner, call_forward, s);
17750       }
17751    }
17752 }
17753 
17754 /*! \brief Check pending actions on SIP call 
17755  *
17756  * \note both sip_pvt and sip_pvt's owner channel (if present)
17757  *  must be locked for this function.
17758  */
17759 static void check_pendings(struct sip_pvt *p)
17760 {
17761    if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
17762       /* if we can't BYE, then this is really a pending CANCEL */
17763       if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA) {
17764          p->invitestate = INV_CANCELLED;
17765          transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
17766          /* Actually don't destroy us yet, wait for the 487 on our original 
17767             INVITE, but do set an autodestruct just in case we never get it. */
17768       } else {
17769          /* We have a pending outbound invite, don't send something
17770             new in-transaction */
17771          if (p->pendinginvite)
17772             return;
17773 
17774          if (p->owner) {
17775             ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
17776          }
17777          /* Perhaps there is an SD change INVITE outstanding */
17778          transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
17779       }
17780       ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);   
17781       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17782    } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
17783       /* if we can't REINVITE, hold it for later */
17784       if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
17785          ast_debug(2, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
17786       } else {
17787          ast_debug(2, "Sending pending reinvite on '%s'\n", p->callid);
17788          /* Didn't get to reinvite yet, so do it now */
17789          transmit_reinvite_with_sdp(p, (p->t38.state == T38_LOCAL_REINVITE ? TRUE : FALSE), FALSE);
17790          ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE); 
17791       }
17792    }
17793 }
17794 
17795 /*! \brief Reset the NEEDREINVITE flag after waiting when we get 491 on a Re-invite
17796    to avoid race conditions between asterisk servers.
17797    Called from the scheduler.
17798 */
17799 static int sip_reinvite_retry(const void *data)
17800 {
17801    struct sip_pvt *p = (struct sip_pvt *) data;
17802    struct ast_channel *owner;
17803 
17804    sip_pvt_lock(p); /* called from schedule thread which requires a lock */
17805    while ((owner = p->owner) && ast_channel_trylock(owner)) {
17806       sip_pvt_unlock(p);
17807       usleep(1);
17808       sip_pvt_lock(p);
17809    }
17810    ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
17811    p->waitid = -1;
17812    check_pendings(p);
17813    sip_pvt_unlock(p);
17814    if (owner) {
17815       ast_channel_unlock(owner);
17816    }
17817    dialog_unref(p, "unref the dialog ptr from sip_reinvite_retry, because it held a dialog ptr");
17818    return 0;
17819 }
17820 
17821 
17822 /*! \brief Handle SIP response to INVITE dialogue */
17823 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
17824 {
17825    int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
17826    int res = 0;
17827    int xmitres = 0;
17828    int reinvite = (p->owner && p->owner->_state == AST_STATE_UP);
17829    char *p_hdrval;
17830    int rtn;
17831 
17832    if (reinvite)
17833       ast_debug(4, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
17834    else
17835       ast_debug(4, "SIP response %d to standard invite\n", resp);
17836 
17837    if (p->alreadygone) { /* This call is already gone */
17838       ast_debug(1, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
17839       return;
17840    }
17841 
17842    /* Acknowledge sequence number - This only happens on INVITE from SIP-call */
17843    /* Don't auto congest anymore since we've gotten something useful back */
17844    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"));
17845 
17846    /* RFC3261 says we must treat every 1xx response (but not 100)
17847       that we don't recognize as if it was 183.
17848    */
17849    if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 182 && resp != 183)
17850       resp = 183;
17851 
17852    /* Any response between 100 and 199 is PROCEEDING */
17853    if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING)
17854       p->invitestate = INV_PROCEEDING;
17855  
17856    /* Final response, not 200 ? */
17857    if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA ))
17858       p->invitestate = INV_COMPLETED;
17859    
17860    /* Final response, clear out pending invite */
17861    if ((resp == 200 || resp >= 300) && p->pendinginvite && seqno == p->pendinginvite)
17862       p->pendinginvite = 0;
17863 
17864    switch (resp) {
17865    case 100:   /* Trying */
17866    case 101:   /* Dialog establishment */
17867       if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
17868          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
17869       check_pendings(p);
17870       break;
17871 
17872    case 180:   /* 180 Ringing */
17873    case 182:       /* 182 Queued */
17874       if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
17875          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
17876       if (!req->ignore && p->owner) {
17877          ast_queue_control(p->owner, AST_CONTROL_RINGING);
17878          if (p->owner->_state != AST_STATE_UP) {
17879             ast_setstate(p->owner, AST_STATE_RINGING);
17880          }
17881       }
17882       if (find_sdp(req)) {
17883          if (p->invitestate != INV_CANCELLED)
17884             p->invitestate = INV_EARLY_MEDIA;
17885          res = process_sdp(p, req, SDP_T38_NONE);
17886          if (!req->ignore && p->owner) {
17887             /* Queue a progress frame only if we have SDP in 180 or 182 */
17888             ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
17889          }
17890       }
17891       check_pendings(p);
17892       break;
17893 
17894    case 183:   /* Session progress */
17895       if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
17896          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
17897       if (find_sdp(req)) {
17898          if (p->invitestate != INV_CANCELLED)
17899             p->invitestate = INV_EARLY_MEDIA;
17900          res = process_sdp(p, req, SDP_T38_NONE);
17901          if (!req->ignore && p->owner) {
17902             /* Queue a progress frame */
17903             ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
17904          }
17905       } else {
17906          /* Alcatel PBXs are known to send 183s with no SDP after sending
17907           * a 100 Trying response. We're just going to treat this sort of thing
17908           * the same as we would treat a 180 Ringing
17909           */
17910          if (!req->ignore && p->owner) {
17911             ast_queue_control(p->owner, AST_CONTROL_RINGING);
17912          }
17913       }
17914       check_pendings(p);
17915       break;
17916 
17917    case 200:   /* 200 OK on invite - someone's answering our call */
17918       if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
17919          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
17920       p->authtries = 0;
17921       if (find_sdp(req)) {
17922          if ((res = process_sdp(p, req, SDP_T38_ACCEPT)) && !req->ignore)
17923             if (!reinvite)
17924                /* This 200 OK's SDP is not acceptable, so we need to ack, then hangup */
17925                /* For re-invites, we try to recover */
17926                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
17927       }
17928 
17929       /* Parse contact header for continued conversation */
17930       /* When we get 200 OK, we know which device (and IP) to contact for this call */
17931       /* This is important when we have a SIP proxy between us and the phone */
17932       if (outgoing) {
17933          update_call_counter(p, DEC_CALL_RINGING);
17934          parse_ok_contact(p, req);
17935          /* Save Record-Route for any later requests we make on this dialogue */
17936          if (!reinvite)
17937             build_route(p, req, 1);
17938 
17939          if(set_address_from_contact(p)) {
17940             /* Bad contact - we don't know how to reach this device */
17941             /* We need to ACK, but then send a bye */
17942             if (!p->route && !req->ignore)
17943                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
17944          } 
17945 
17946       }
17947 
17948       if (!req->ignore && p->owner) {
17949          if (!reinvite) {
17950             ast_queue_control(p->owner, AST_CONTROL_ANSWER);
17951             if (sip_cfg.callevents)
17952                manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
17953                   "Channel: %s\r\nChanneltype: %s\r\nUniqueid: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
17954                   p->owner->name, "SIP", p->owner->uniqueid, p->callid, p->fullcontact, p->peername);
17955          } else { /* RE-invite */
17956             ast_queue_frame(p->owner, &ast_null_frame);
17957          }
17958       } else {
17959           /* It's possible we're getting an 200 OK after we've tried to disconnect
17960               by sending CANCEL */
17961          /* First send ACK, then send bye */
17962          if (!req->ignore)
17963             ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
17964       }
17965 
17966       /* Check for Session-Timers related headers */
17967       if (st_get_mode(p) != SESSION_TIMER_MODE_REFUSE && p->outgoing_call == TRUE && !reinvite) {
17968          p_hdrval = (char*)get_header(req, "Session-Expires");
17969          if (!ast_strlen_zero(p_hdrval)) {
17970             /* UAS supports Session-Timers */
17971             enum st_refresher tmp_st_ref = SESSION_TIMER_REFRESHER_AUTO;
17972             int tmp_st_interval = 0;
17973             rtn = parse_session_expires(p_hdrval, &tmp_st_interval, &tmp_st_ref);
17974             if (rtn != 0) {
17975                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
17976             }
17977             if (tmp_st_ref == SESSION_TIMER_REFRESHER_UAC || 
17978                tmp_st_ref == SESSION_TIMER_REFRESHER_UAS) {
17979                p->stimer->st_ref = tmp_st_ref;
17980             } 
17981             if (tmp_st_interval) {
17982                p->stimer->st_interval = tmp_st_interval;
17983             }
17984             p->stimer->st_active = TRUE;
17985             p->stimer->st_active_peer_ua = TRUE;
17986             start_session_timer(p);
17987          } else {
17988             /* UAS doesn't support Session-Timers */
17989             if (st_get_mode(p) == SESSION_TIMER_MODE_ORIGINATE) {
17990                p->stimer->st_ref = SESSION_TIMER_REFRESHER_UAC;
17991                p->stimer->st_active_peer_ua = FALSE;
17992                start_session_timer(p);
17993             }
17994          }
17995       }
17996 
17997 
17998       /* If I understand this right, the branch is different for a non-200 ACK only */
17999       p->invitestate = INV_TERMINATED;
18000       ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
18001       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
18002       check_pendings(p);
18003       break;
18004 
18005    case 407: /* Proxy authentication */
18006    case 401: /* Www auth */
18007       /* First we ACK */
18008       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18009       if (p->options)
18010          p->options->auth_type = resp;
18011 
18012       /* Then we AUTH */
18013       ast_string_field_set(p, theirtag, NULL);  /* forget their old tag, so we don't match tags when getting response */
18014       if (!req->ignore) {
18015          if (p->authtries < MAX_AUTHTRIES)
18016             p->invitestate = INV_CALLING;
18017          if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, SIP_INVITE, 1)) {
18018             ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
18019             pvt_set_needdestroy(p, "failed to authenticate on INVITE");
18020             sip_alreadygone(p);
18021             if (p->owner)
18022                ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18023          }
18024       }
18025       break;
18026 
18027    case 403: /* Forbidden */
18028       /* First we ACK */
18029       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18030       ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
18031       if (!req->ignore && p->owner)
18032          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18033       pvt_set_needdestroy(p, "received 403 response");
18034       sip_alreadygone(p);
18035       break;
18036 
18037    case 404: /* Not found */
18038       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18039       if (p->owner && !req->ignore)
18040          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18041       sip_alreadygone(p);
18042       break;
18043 
18044    case 408: /* Request timeout */
18045    case 481: /* Call leg does not exist */
18046       /* Could be REFER caused INVITE with replaces */
18047       ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
18048       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18049       if (p->owner)
18050          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18051       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18052       break;
18053 
18054    case 422: /* Session-Timers: Session interval too small */
18055       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18056       ast_string_field_set(p, theirtag, NULL);
18057       proc_422_rsp(p, req);
18058       break;
18059 
18060    case 428: /* Use identity header - rfc 4474 - not supported by Asterisk yet */
18061       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18062       append_history(p, "Identity", "SIP identity is required. Not supported by Asterisk.");
18063       ast_log(LOG_WARNING, "SIP identity required by proxy. SIP dialog '%s'. Giving up.\n", p->callid);
18064       if (p->owner)
18065          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18066       break;
18067 
18068       
18069 
18070    case 487: /* Cancelled transaction */
18071       /* We have sent CANCEL on an outbound INVITE 
18072          This transaction is already scheduled to be killed by sip_hangup().
18073       */
18074       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18075       if (p->owner && !req->ignore) {
18076          ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_CLEARING);
18077          append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
18078       } else if (!req->ignore) {
18079          update_call_counter(p, DEC_CALL_LIMIT);
18080          append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
18081          pvt_set_needdestroy(p, "received 487 response");
18082          sip_alreadygone(p);
18083       }
18084       break;
18085    case 415: /* Unsupported media type */
18086    case 488: /* Not acceptable here */
18087    case 606: /* Not Acceptable */
18088       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18089       if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
18090          change_t38_state(p, T38_DISABLED);
18091          /* Try to reset RTP timers */
18092          ast_rtp_set_rtptimers_onhold(p->rtp);
18093 
18094          /* Trigger a reinvite back to audio */
18095          transmit_reinvite_with_sdp(p, FALSE, FALSE);
18096       } else {
18097          /* We can't set up this call, so give up */
18098          if (p->owner && !req->ignore)
18099             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18100          pvt_set_needdestroy(p, "received 488 response");
18101          /* If there's no dialog to end, then mark p as already gone */
18102          if (!reinvite)
18103             sip_alreadygone(p);
18104       }
18105       break;
18106    case 491: /* Pending */
18107       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18108       if (p->owner && !req->ignore) {
18109          if (p->owner->_state != AST_STATE_UP) {
18110             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18111             pvt_set_needdestroy(p, "received 491 response");
18112          } else {
18113             /* This is a re-invite that failed. */
18114             /* Reset the flag after a while 
18115              */
18116             int wait;
18117             /* RFC 3261, if owner of call, wait between 2.1 to 4 seconds,
18118              * if not owner of call, wait 0 to 2 seconds */
18119             if (p->outgoing_call) {
18120                wait = 2100 + ast_random() % 2000;
18121             } else {
18122                wait = ast_random() % 2000;
18123             }
18124             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."));
18125             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);
18126             ast_debug(2, "Reinvite race. Waiting %d secs before retry\n", wait);
18127          }
18128       }
18129       break;
18130 
18131    case 501: /* Not implemented */
18132       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18133       if (p->owner)
18134          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18135       break;
18136    }
18137    if (xmitres == XMIT_ERROR)
18138       ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
18139 }
18140 
18141 /* \brief Handle SIP response in NOTIFY transaction
18142        We've sent a NOTIFY, now handle responses to it
18143   */
18144 static void handle_response_notify(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18145 {
18146    switch (resp) {
18147    case 200:   /* Notify accepted */
18148       /* They got the notify, this is the end */
18149       if (p->owner) {
18150          if (!p->refer) {
18151             ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
18152             ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_UNSPECIFIED);
18153          } else {
18154             ast_debug(4, "Got OK on REFER Notify message\n");
18155          }
18156       } else {
18157          if (p->subscribed == NONE) {
18158             ast_debug(4, "Got 200 accepted on NOTIFY\n");
18159             pvt_set_needdestroy(p, "received 200 response");
18160          }
18161          if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
18162             /* Ready to send the next state we have on queue */
18163             ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
18164             cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
18165          }
18166       }
18167       break;
18168    case 401:   /* Not www-authorized on SIP method */
18169    case 407:   /* Proxy auth */
18170       if (!p->notify_headers) {
18171          break; /* Only device notify can use NOTIFY auth */
18172       }
18173       ast_string_field_set(p, theirtag, NULL);
18174       if (ast_strlen_zero(p->authname)) {
18175          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));
18176          pvt_set_needdestroy(p, "unable to authenticate NOTIFY");
18177       }
18178       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_NOTIFY, 0)) {
18179          ast_log(LOG_NOTICE, "Failed to authenticate on NOTIFY to '%s'\n", get_header(&p->initreq, "From"));
18180          pvt_set_needdestroy(p, "failed to authenticate NOTIFY");
18181       }
18182       break;
18183    }
18184 }
18185 
18186 /* \brief Handle SIP response in SUBSCRIBE transaction */
18187 static void handle_response_subscribe(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18188 {
18189    if (!p->mwi) {
18190       return;
18191    }
18192 
18193    switch (resp) {
18194    case 200: /* Subscription accepted */
18195       ast_debug(3, "Got 200 OK on subscription for MWI\n");
18196       if (p->options) {
18197          ast_free(p->options);
18198          p->options = NULL;
18199       }
18200       p->mwi->subscribed = 1;
18201       if ((p->mwi->resub = ast_sched_add(sched, mwi_expiry * 1000, sip_subscribe_mwi_do, ASTOBJ_REF(p->mwi))) < 0) {
18202          ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18203       }
18204       break;
18205    case 401:
18206    case 407:
18207       ast_string_field_set(p, theirtag, NULL);
18208       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_SUBSCRIBE, 0)) {
18209          ast_log(LOG_NOTICE, "Failed to authenticate on SUBSCRIBE to '%s'\n", get_header(&p->initreq, "From"));
18210          p->mwi->call = NULL;
18211          ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18212          pvt_set_needdestroy(p, "failed to authenticate SUBSCRIBE");
18213       }
18214       break;
18215    case 403:
18216       transmit_response_with_date(p, "200 OK", req);
18217       ast_log(LOG_WARNING, "Authentication failed while trying to subscribe for MWI.\n");
18218       p->mwi->call = NULL;
18219       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18220       pvt_set_needdestroy(p, "received 403 response");
18221       sip_alreadygone(p);
18222       break;
18223    case 404:
18224       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that a mailbox may not have been configured.\n");
18225       p->mwi->call = NULL;
18226       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18227       pvt_set_needdestroy(p, "received 404 response");
18228       break;
18229    case 481:
18230       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that our dialog did not exist.\n");
18231       p->mwi->call = NULL;
18232       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18233       pvt_set_needdestroy(p, "received 481 response");
18234       break;
18235    case 500:
18236    case 501:
18237       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side may have suffered a heart attack.\n");
18238       p->mwi->call = NULL;
18239       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18240       pvt_set_needdestroy(p, "received 500/501 response");
18241       break;
18242    }
18243 }
18244 
18245 /* \brief Handle SIP response in REFER transaction
18246    We've sent a REFER, now handle responses to it 
18247   */
18248 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18249 {
18250    /* If no refer structure exists, then do nothing */
18251    if (!p->refer)
18252       return;
18253 
18254    switch (resp) {
18255    case 202:   /* Transfer accepted */
18256       /* We need  to do something here */
18257       /* The transferee is now sending INVITE to target */
18258       p->refer->status = REFER_ACCEPTED;
18259       /* Now wait for next message */
18260       ast_debug(3, "Got 202 accepted on transfer\n");
18261       /* We should hang along, waiting for NOTIFY's here */
18262       break;
18263 
18264    case 401:   /* Not www-authorized on SIP method */
18265    case 407:   /* Proxy auth */
18266       if (ast_strlen_zero(p->authname)) {
18267          ast_log(LOG_WARNING, "Asked to authenticate REFER to %s:%d but we have no matching peer or realm auth!\n",
18268             ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
18269          pvt_set_needdestroy(p, "unable to authenticate REFER");
18270       }
18271       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_REFER, 0)) {
18272          ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
18273          p->refer->status = REFER_NOAUTH;
18274          pvt_set_needdestroy(p, "failed to authenticat REFER");
18275       }
18276       break;
18277    case 481: /* Call leg does not exist */
18278 
18279       /* A transfer with Replaces did not work */
18280       /* OEJ: We should Set flag, cancel the REFER, go back
18281       to original call - but right now we can't */
18282       ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
18283       if (p->owner)
18284          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18285       pvt_set_needdestroy(p, "received 481 response");
18286       break;
18287 
18288    case 500:   /* Server error */
18289    case 501:   /* Method not implemented */
18290       /* Return to the current call onhold */
18291       /* Status flag needed to be reset */
18292       ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
18293       pvt_set_needdestroy(p, "received 500/501 response");
18294       p->refer->status = REFER_FAILED;
18295       break;
18296    case 603:   /* Transfer declined */
18297       ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
18298       p->refer->status = REFER_FAILED;
18299       pvt_set_needdestroy(p, "received 603 response");
18300       break;
18301    }
18302 }
18303 
18304 /*! \brief Handle responses on REGISTER to services */
18305 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18306 {
18307    int expires, expires_ms;
18308    struct sip_registry *r;
18309    r=p->registry;
18310    
18311    switch (resp) {
18312    case 401:   /* Unauthorized */
18313       if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
18314          ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
18315          pvt_set_needdestroy(p, "failed to authenticate REGISTER");
18316       }
18317       break;
18318    case 403:   /* Forbidden */
18319       ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
18320       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 403"));
18321       r->regstate = REG_STATE_NOAUTH;
18322       pvt_set_needdestroy(p, "received 403 response");
18323       break;
18324    case 404:   /* Not found */
18325       ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username, p->registry->hostname);
18326       pvt_set_needdestroy(p, "received 404 response");
18327       if (r->call)
18328          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 404");
18329       r->regstate = REG_STATE_REJECTED;
18330       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 404"));
18331       break;
18332    case 407:   /* Proxy auth */
18333       if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
18334          ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
18335          pvt_set_needdestroy(p, "failed to authenticate REGISTER");
18336       }
18337       break;
18338    case 408:   /* Request timeout */
18339       /* Got a timeout response, so reset the counter of failed responses */
18340       if (r) {
18341          r->regattempts = 0;
18342       } else {
18343          ast_log(LOG_WARNING, "Got a 408 response to our REGISTER on call %s after we had destroyed the registry object\n", p->callid);
18344       }
18345       break;
18346    case 423:   /* Interval too brief */
18347       r->expiry = atoi(get_header(req, "Min-Expires"));
18348       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);
18349       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 423"));
18350       if (r->call) {
18351          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 423");
18352          pvt_set_needdestroy(p, "received 423 response");
18353       }
18354       if (r->expiry > max_expiry) {
18355          ast_log(LOG_WARNING, "Required expiration time from %s@%s is too high, giving up\n", p->registry->username, p->registry->hostname);
18356          r->expiry = r->configured_expiry;
18357          r->regstate = REG_STATE_REJECTED;
18358       } else {
18359          r->regstate = REG_STATE_UNREGISTERED;
18360          transmit_register(r, SIP_REGISTER, NULL, NULL);
18361       }
18362       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));
18363       break;
18364    case 479:   /* SER: Not able to process the URI - address is wrong in register*/
18365       ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username, p->registry->hostname);
18366       pvt_set_needdestroy(p, "received 479 response");
18367       if (r->call)
18368          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 479");
18369       r->regstate = REG_STATE_REJECTED;
18370       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 479"));
18371       break;
18372    case 200:   /* 200 OK */
18373       if (!r) {
18374          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));
18375          pvt_set_needdestroy(p, "received erroneous 200 response");
18376          return 0;
18377       }
18378       
18379       r->regstate = REG_STATE_REGISTERED;
18380       r->regtime = ast_tvnow();     /* Reset time of last succesful registration */
18381       manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
18382       r->regattempts = 0;
18383       ast_debug(1, "Registration successful\n");
18384       if (r->timeout > -1) {
18385          ast_debug(1, "Cancelling timeout %d\n", r->timeout);
18386       }
18387       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 200"));
18388       if (r->call)
18389          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 200");
18390       p->registry = registry_unref(p->registry, "unref registry entry p->registry");
18391       /* Let this one hang around until we have all the responses */
18392       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18393       /* p->needdestroy = 1; */
18394       
18395       /* set us up for re-registering
18396        * figure out how long we got registered for
18397        * according to section 6.13 of RFC, contact headers override
18398        * expires headers, so check those first */
18399       expires = 0;
18400 
18401       /* XXX todo: try to save the extra call */
18402       if (!ast_strlen_zero(get_header(req, "Contact"))) {
18403          const char *contact = NULL;
18404          const char *tmptmp = NULL;
18405          int start = 0;
18406          for(;;) {
18407             contact = __get_header(req, "Contact", &start);
18408             /* this loop ensures we get a contact header about our register request */
18409             if(!ast_strlen_zero(contact)) {
18410                if( (tmptmp=strstr(contact, p->our_contact))) {
18411                   contact=tmptmp;
18412                   break;
18413                }
18414             } else
18415                break;
18416          }
18417          tmptmp = strcasestr(contact, "expires=");
18418          if (tmptmp) {
18419             if (sscanf(tmptmp + 8, "%30d;", &expires) != 1)
18420                expires = 0;
18421          }
18422          
18423       }
18424       if (!expires) 
18425          expires=atoi(get_header(req, "expires"));
18426       if (!expires)
18427          expires=default_expiry;
18428       
18429       expires_ms = expires * 1000;
18430       if (expires <= EXPIRY_GUARD_LIMIT)
18431          expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT), EXPIRY_GUARD_MIN);
18432       else
18433          expires_ms -= EXPIRY_GUARD_SECS * 1000;
18434       if (sipdebug)
18435          ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000); 
18436       
18437       r->refresh= (int) expires_ms / 1000;
18438       
18439       /* Schedule re-registration before we expire */
18440       AST_SCHED_REPLACE_UNREF(r->expire, sched, expires_ms, sip_reregister, r, 
18441                         registry_unref(_data,"unref in REPLACE del fail"), 
18442                         registry_unref(r,"unref in REPLACE add fail"), 
18443                         registry_addref(r,"The Addition side of REPLACE")); 
18444    }
18445    return 1;
18446 }
18447 
18448 /*! \brief Handle qualification responses (OPTIONS) */
18449 static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
18450 {
18451    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! */
18452    int statechanged, is_reachable, was_reachable;
18453    int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
18454 
18455    /*
18456     * Compute the response time to a ping (goes in peer->lastms.)
18457     * -1 means did not respond, 0 means unknown,
18458     * 1..maxms is a valid response, >maxms means late response.
18459     */
18460    if (pingtime < 1) /* zero = unknown, so round up to 1 */
18461       pingtime = 1;
18462 
18463    /* Now determine new state and whether it has changed.
18464     * Use some helper variables to simplify the writing
18465     * of the expressions.
18466     */
18467    was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
18468    is_reachable = pingtime <= peer->maxms;
18469    statechanged = peer->lastms == 0 /* yes, unknown before */
18470       || was_reachable != is_reachable;
18471 
18472    peer->lastms = pingtime;
18473    peer->call = dialog_unref(peer->call, "unref dialog peer->call");
18474    if (statechanged) {
18475       const char *s = is_reachable ? "Reachable" : "Lagged";
18476       char str_lastms[20];
18477       snprintf(str_lastms, sizeof(str_lastms), "%d", pingtime);
18478 
18479       ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
18480          peer->name, s, pingtime, peer->maxms);
18481       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
18482       if (sip_cfg.peer_rtupdate) {
18483          ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", str_lastms, SENTINEL);
18484       }
18485       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
18486          "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
18487          peer->name, s, pingtime);
18488       if (is_reachable && sip_cfg.regextenonqualify)
18489          register_peer_exten(peer, TRUE);
18490    }
18491 
18492    pvt_set_needdestroy(p, "got OPTIONS response");
18493 
18494    /* Try again eventually */
18495    AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
18496          is_reachable ? peer->qualifyfreq : DEFAULT_FREQ_NOTOK,
18497          sip_poke_peer_s, peer,
18498          unref_peer(_data, "removing poke peer ref"),
18499          unref_peer(peer, "removing poke peer ref"),
18500          ref_peer(peer, "adding poke peer ref"));
18501 }
18502 
18503 /*! \brief Immediately stop RTP, VRTP and UDPTL as applicable */
18504 static void stop_media_flows(struct sip_pvt *p)
18505 {
18506    /* Immediately stop RTP, VRTP and UDPTL as applicable */
18507    if (p->rtp)
18508       ast_rtp_stop(p->rtp);
18509    if (p->vrtp)
18510       ast_rtp_stop(p->vrtp);
18511    if (p->trtp)
18512       ast_rtp_stop(p->trtp);
18513    if (p->udptl)
18514       ast_udptl_stop(p->udptl);
18515 }
18516 
18517 /*! \brief Handle SIP response in dialogue
18518    \note only called by handle_incoming */
18519 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18520 {
18521    struct ast_channel *owner;
18522    int sipmethod;
18523    int res = 1;
18524    const char *c = get_header(req, "Cseq");
18525    /* 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 */
18526    char *c_copy = ast_strdupa(c);
18527    /* Skip the Cseq and its subsequent spaces */
18528    const char *msg = ast_skip_blanks(ast_skip_nonblanks(c_copy));
18529 
18530    if (!msg)
18531       msg = "";
18532 
18533    sipmethod = find_sip_method(msg);
18534 
18535    owner = p->owner;
18536    if (owner) 
18537       owner->hangupcause = hangup_sip2cause(resp);
18538 
18539    if (p->socket.type == SIP_TRANSPORT_UDP) {
18540       int ack_res;
18541 
18542       /* Acknowledge whatever it is destined for */
18543       if ((resp >= 100) && (resp <= 199)) {
18544          ack_res = __sip_semi_ack(p, seqno, 0, sipmethod);
18545       } else {
18546          ack_res = __sip_ack(p, seqno, 0, sipmethod);
18547       }
18548 
18549       if (ack_res == FALSE) {
18550          append_history(p, "Ignore", "Ignoring this retransmit\n");
18551          return;
18552       }
18553    }
18554 
18555    /* If this is a NOTIFY for a subscription clear the flag that indicates that we have a NOTIFY pending */
18556    if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite) 
18557       p->pendinginvite = 0;
18558 
18559    /* Get their tag if we haven't already */
18560    if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
18561       char tag[128];
18562 
18563       gettag(req, "To", tag, sizeof(tag));
18564       ast_string_field_set(p, theirtag, tag);
18565    }
18566    /* This needs to be configurable on a channel/peer level,
18567       not mandatory for all communication. Sadly enough, NAT implementations
18568       are not so stable so we can always rely on these headers. 
18569       Temporarily disabled, while waiting for fix.
18570       Fix assigned to Rizzo :-)
18571    */
18572    /* check_via_response(p, req); */
18573 
18574    /* RFC 3261 Section 15 specifies that if we receive a 408 or 481
18575     * in response to a BYE, then we should end the current dialog
18576     * and session.  It is known that at least one phone manufacturer
18577     * potentially will send a 404 in response to a BYE, so we'll be
18578     * liberal in what we accept and end the dialog and session if we
18579     * receive any of those responses to a BYE.
18580     */
18581    if ((resp == 404 || resp == 408 || resp == 481) && sipmethod == SIP_BYE) {
18582       pvt_set_needdestroy(p, "received 4XX response to a BYE");
18583       return;
18584    }
18585 
18586    if (p->relatedpeer && p->method == SIP_OPTIONS) {
18587       /* We don't really care what the response is, just that it replied back. 
18588          Well, as long as it's not a 100 response...  since we might
18589          need to hang around for something more "definitive" */
18590       if (resp != 100)
18591          handle_response_peerpoke(p, resp, req);
18592    } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
18593       switch(resp) {
18594       case 100:   /* 100 Trying */
18595       case 101:   /* 101 Dialog establishment */
18596       case 183:   /* 183 Session Progress */
18597       case 180:   /* 180 Ringing */
18598       case 182:   /* 182 Queued */
18599          if (sipmethod == SIP_INVITE)
18600             handle_response_invite(p, resp, rest, req, seqno);
18601          break;
18602       case 200:   /* 200 OK */
18603          p->authtries = 0; /* Reset authentication counter */
18604          if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
18605             /* We successfully transmitted a message 
18606                or a video update request in INFO */
18607             /* Nothing happens here - the message is inside a dialog */
18608          } else if (sipmethod == SIP_INVITE) {
18609             handle_response_invite(p, resp, rest, req, seqno);
18610          } else if (sipmethod == SIP_NOTIFY) {
18611             handle_response_notify(p, resp, rest, req, seqno);
18612          } else if (sipmethod == SIP_REGISTER) {
18613             res = handle_response_register(p, resp, rest, req, seqno);
18614          } else if (sipmethod == SIP_SUBSCRIBE) {
18615             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
18616             handle_response_subscribe(p, resp, rest, req, seqno);
18617          } else if (sipmethod == SIP_BYE) {     /* Ok, we're ready to go */
18618             pvt_set_needdestroy(p, "received 200 response");
18619             ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
18620          }
18621          break;
18622       case 202:   /* Transfer accepted */
18623          if (sipmethod == SIP_REFER) 
18624             handle_response_refer(p, resp, rest, req, seqno);
18625          break;
18626       case 401: /* Not www-authorized on SIP method */
18627       case 407: /* Proxy auth required */
18628          if (sipmethod == SIP_INVITE)
18629             handle_response_invite(p, resp, rest, req, seqno);
18630          else if (sipmethod == SIP_NOTIFY)
18631             handle_response_notify(p, resp, rest, req, seqno);
18632          else if (sipmethod == SIP_REFER)
18633             handle_response_refer(p, resp, rest, req, seqno);
18634          else if (sipmethod == SIP_SUBSCRIBE)
18635             handle_response_subscribe(p, resp, rest, req, seqno);
18636          else if (p->registry && sipmethod == SIP_REGISTER)
18637             res = handle_response_register(p, resp, rest, req, seqno);
18638          else if (sipmethod == SIP_BYE) {
18639             if (p->options)
18640                p->options->auth_type = resp;
18641             if (ast_strlen_zero(p->authname)) {
18642                ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
18643                      msg, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
18644                pvt_set_needdestroy(p, "unable to authenticate BYE");
18645             } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp,  sipmethod, 0)) {
18646                ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
18647                pvt_set_needdestroy(p, "failed to authenticate BYE");
18648             }
18649          } else {
18650             ast_log(LOG_WARNING, "Got authentication request (%d) on %s to '%s'\n", resp, sip_methods[sipmethod].text, get_header(req, "To"));
18651             pvt_set_needdestroy(p, "received 407 response");
18652          }
18653          break;
18654       case 403: /* Forbidden - we failed authentication */
18655          if (sipmethod == SIP_INVITE)
18656             handle_response_invite(p, resp, rest, req, seqno);
18657          else if (sipmethod == SIP_SUBSCRIBE)
18658             handle_response_subscribe(p, resp, rest, req, seqno);
18659          else if (p->registry && sipmethod == SIP_REGISTER) 
18660             res = handle_response_register(p, resp, rest, req, seqno);
18661          else {
18662             ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
18663             pvt_set_needdestroy(p, "received 403 response");
18664          }
18665          break;
18666       case 404: /* Not found */
18667          if (p->registry && sipmethod == SIP_REGISTER)
18668             res = handle_response_register(p, resp, rest, req, seqno);
18669          else if (sipmethod == SIP_INVITE)
18670             handle_response_invite(p, resp, rest, req, seqno);
18671          else if (sipmethod == SIP_SUBSCRIBE)
18672             handle_response_subscribe(p, resp, rest, req, seqno);
18673          else if (owner)
18674             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18675          break;
18676       case 423: /* Interval too brief */
18677          if (sipmethod == SIP_REGISTER)
18678             res = handle_response_register(p, resp, rest, req, seqno);
18679          break;
18680       case 408: /* Request timeout - terminate dialog */
18681          if (sipmethod == SIP_INVITE)
18682             handle_response_invite(p, resp, rest, req, seqno);
18683          else if (sipmethod == SIP_REGISTER) 
18684             res = handle_response_register(p, resp, rest, req, seqno);
18685          else if (sipmethod == SIP_BYE) {
18686             pvt_set_needdestroy(p, "received 408 response");
18687             ast_debug(4, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
18688          } else {
18689             if (owner)
18690                ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18691             pvt_set_needdestroy(p, "received 408 response");
18692          }
18693          break;
18694 
18695       case 422: /* Session-Timers: Session Interval Too Small */
18696          if (sipmethod == SIP_INVITE) {
18697             handle_response_invite(p, resp, rest, req, seqno);
18698          }
18699          break;
18700 
18701       case 481: /* Call leg does not exist */
18702          if (sipmethod == SIP_INVITE) {
18703             handle_response_invite(p, resp, rest, req, seqno);
18704          } else if (sipmethod == SIP_REFER) {
18705             handle_response_refer(p, resp, rest, req, seqno);
18706          } else if (sipmethod == SIP_SUBSCRIBE) {
18707             handle_response_subscribe(p, resp, rest, req, seqno);
18708          } else if (sipmethod == SIP_NOTIFY) {
18709             pvt_set_needdestroy(p, "received 481 response");
18710          } else if (sipmethod == SIP_BYE) {
18711             /* The other side has no transaction to bye,
18712             just assume it's all right then */
18713             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
18714          } else if (sipmethod == SIP_CANCEL) {
18715             /* The other side has no transaction to cancel,
18716             just assume it's all right then */
18717             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
18718          } else {
18719             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
18720             /* Guessing that this is not an important request */
18721          }
18722          break;
18723       case 487:
18724          if (sipmethod == SIP_INVITE)
18725             handle_response_invite(p, resp, rest, req, seqno);
18726          break;
18727       case 415: /* Unsupported media type */
18728       case 488: /* Not acceptable here - codec error */
18729       case 606: /* Not Acceptable */
18730          if (sipmethod == SIP_INVITE)
18731             handle_response_invite(p, resp, rest, req, seqno);
18732          break;
18733       case 491: /* Pending */
18734          if (sipmethod == SIP_INVITE)
18735             handle_response_invite(p, resp, rest, req, seqno);
18736          else {
18737             ast_debug(1, "Got 491 on %s, unsupported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
18738             pvt_set_needdestroy(p, "received 491 response");
18739          }
18740          break;
18741       case 501: /* Not Implemented */
18742          if (sipmethod == SIP_INVITE)
18743             handle_response_invite(p, resp, rest, req, seqno);
18744          else if (sipmethod == SIP_REFER)
18745             handle_response_refer(p, resp, rest, req, seqno);
18746          else
18747             ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_inet_ntoa(p->sa.sin_addr), msg);
18748          break;
18749       case 603:   /* Declined transfer */
18750          if (sipmethod == SIP_REFER) {
18751             handle_response_refer(p, resp, rest, req, seqno);
18752             break;
18753          }
18754          /* Fallthrough */
18755       default:
18756          if ((resp >= 300) && (resp < 700)) {
18757             /* Fatal response */
18758             if ((resp != 487))
18759                ast_verb(3, "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
18760    
18761             if (sipmethod == SIP_INVITE)
18762                stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
18763 
18764             /* XXX Locking issues?? XXX */
18765             switch(resp) {
18766             case 300: /* Multiple Choices */
18767             case 301: /* Moved permanently */
18768             case 302: /* Moved temporarily */
18769             case 305: /* Use Proxy */
18770                parse_moved_contact(p, req);
18771                /* Fall through */
18772             case 486: /* Busy here */
18773             case 600: /* Busy everywhere */
18774             case 603: /* Decline */
18775                if (p->owner)
18776                   ast_queue_control(p->owner, AST_CONTROL_BUSY);
18777                break;
18778             case 482: /* Loop Detected */
18779                /*
18780                   \note Asterisk has historically tried to do a call forward when it
18781                   gets a 482, but that behavior isn't necessarily the best course of
18782                   action. Go ahead and do it anyway by default, but allow the option
18783                   to immediately pass to the next line in the dialplan. */
18784                if (p->owner && ast_test_flag(&p->flags[1], SIP_PAGE2_FORWARD_LOOP_DETECTED)) {
18785                      ast_debug(1, "Hairpin detected, setting up call forward for what it's worth\n");
18786                      ast_string_field_build(p->owner, call_forward,
18787                            "Local/%s@%s", p->username, p->context);
18788                }
18789                /* Fall through */
18790             case 480: /* Temporarily Unavailable */
18791             case 404: /* Not Found */
18792             case 410: /* Gone */
18793             case 400: /* Bad Request */
18794             case 500: /* Server error */
18795                if (sipmethod == SIP_REFER) {
18796                   handle_response_refer(p, resp, rest, req, seqno);
18797                   break;
18798                } else if (sipmethod == SIP_SUBSCRIBE) {
18799                   handle_response_subscribe(p, resp, rest, req, seqno);
18800                   break;
18801                }
18802                /* Fall through */
18803             case 502: /* Bad gateway */
18804             case 503: /* Service Unavailable */
18805             case 504: /* Server Timeout */
18806                if (owner)
18807                   ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18808                break;
18809             default:
18810                /* Send hangup */ 
18811                if (owner && sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO && sipmethod != SIP_BYE)
18812                   ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
18813                break;
18814             }
18815             /* ACK on invite */
18816             if (sipmethod == SIP_INVITE) 
18817                transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18818             if (sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO) 
18819                sip_alreadygone(p);
18820             if (!p->owner) {
18821                pvt_set_needdestroy(p, "transaction completed");
18822             }
18823          } else if ((resp >= 100) && (resp < 200)) {
18824             if (sipmethod == SIP_INVITE) {
18825                if (!req->ignore && sip_cancel_destroy(p))
18826                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
18827                if (find_sdp(req))
18828                   process_sdp(p, req, SDP_T38_NONE);
18829                if (p->owner) {
18830                   /* Queue a progress frame */
18831                   ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
18832                }
18833             }
18834          } else
18835             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));
18836       }
18837    } else { 
18838       /* Responses to OUTGOING SIP requests on INCOMING calls 
18839          get handled here. As well as out-of-call message responses */
18840       if (req->debug)
18841          ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
18842 
18843       if (sipmethod == SIP_INVITE && resp == 200) {
18844          /* Tags in early session is replaced by the tag in 200 OK, which is 
18845          the final reply to our INVITE */
18846          char tag[128];
18847 
18848          gettag(req, "To", tag, sizeof(tag));
18849          ast_string_field_set(p, theirtag, tag);
18850       }
18851 
18852       switch(resp) {
18853       case 200:
18854          if (sipmethod == SIP_INVITE) {
18855             handle_response_invite(p, resp, rest, req, seqno);
18856          } else if (sipmethod == SIP_CANCEL) {
18857             ast_debug(1, "Got 200 OK on CANCEL\n");
18858 
18859             /* Wait for 487, then destroy */
18860          } else if (sipmethod == SIP_NOTIFY) {
18861             /* They got the notify, this is the end */
18862             if (p->owner) {
18863                if (p->refer) {
18864                   ast_debug(1, "Got 200 OK on NOTIFY for transfer\n");
18865                } else
18866                   ast_log(LOG_WARNING, "Notify answer on an owned channel?\n");
18867                /* ast_queue_hangup(p->owner); Disabled */
18868             } else {
18869                if (!p->subscribed && !p->refer) {
18870                   pvt_set_needdestroy(p, "transaction completed");
18871                }
18872                if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
18873                   /* Ready to send the next state we have on queue */
18874                   ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
18875                   cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
18876                }
18877             }
18878          } else if (sipmethod == SIP_BYE) {
18879             pvt_set_needdestroy(p, "transaction completed");
18880          } else if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
18881             /* We successfully transmitted a message or
18882                a video update request in INFO */
18883             ;
18884          }
18885          break;
18886       case 202:   /* Transfer accepted */
18887          if (sipmethod == SIP_REFER) 
18888             handle_response_refer(p, resp, rest, req, seqno);
18889          break;
18890       case 401:   /* www-auth */
18891       case 407:
18892          if (sipmethod == SIP_REFER)
18893             handle_response_refer(p, resp, rest, req, seqno);
18894          else if (sipmethod == SIP_INVITE) 
18895             handle_response_invite(p, resp, rest, req, seqno);
18896          else if (sipmethod == SIP_BYE) {
18897             if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, sipmethod, 0)) {
18898                ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
18899                pvt_set_needdestroy(p, "failed to authenticate BYE");
18900             }
18901          }
18902          break;
18903       case 481:   /* Call leg does not exist */
18904          if (sipmethod == SIP_INVITE) {
18905             /* Re-invite failed */
18906             handle_response_invite(p, resp, rest, req, seqno);
18907          } else if (sipmethod == SIP_BYE) {
18908             pvt_set_needdestroy(p, "received 481 response");
18909          } else if (sipmethod == SIP_NOTIFY) {
18910             pvt_set_needdestroy(p, "received 481 response");
18911          } else if (sipdebug) {
18912             ast_debug(1, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
18913          }
18914          break;
18915       case 501: /* Not Implemented */
18916          if (sipmethod == SIP_INVITE) 
18917             handle_response_invite(p, resp, rest, req, seqno);
18918          else if (sipmethod == SIP_REFER) 
18919             handle_response_refer(p, resp, rest, req, seqno);
18920          break;
18921       case 603:   /* Declined transfer */
18922          if (sipmethod == SIP_REFER) {
18923             handle_response_refer(p, resp, rest, req, seqno);
18924             break;
18925          }
18926          /* Fallthrough */
18927       default: /* Errors without handlers */
18928          if ((resp >= 100) && (resp < 200)) {
18929             if (sipmethod == SIP_INVITE) {   /* re-invite */
18930                if (!req->ignore && sip_cancel_destroy(p))
18931                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
18932             }
18933          }
18934          if ((resp >= 300) && (resp < 700)) {
18935             if ((resp != 487))
18936                ast_verb(3, "Incoming call: Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
18937             switch(resp) {
18938             case 415: /* Unsupported media type */
18939             case 488: /* Not acceptable here - codec error */
18940             case 603: /* Decline */
18941             case 500: /* Server error */
18942             case 502: /* Bad gateway */
18943             case 503: /* Service Unavailable */
18944             case 504: /* Server timeout */
18945 
18946                /* re-invite failed */
18947                if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
18948                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
18949                break;
18950             }
18951          }
18952          break;
18953       }
18954    }
18955 }
18956 
18957 
18958 /*! \brief Park SIP call support function 
18959    Starts in a new thread, then parks the call
18960    XXX Should we add a wait period after streaming audio and before hangup?? Sometimes the
18961       audio can't be heard before hangup
18962 */
18963 static void *sip_park_thread(void *stuff)
18964 {
18965    struct ast_channel *transferee, *transferer; /* Chan1: The transferee, Chan2: The transferer */
18966    struct sip_dual *d;
18967    struct sip_request req = {0,};
18968    int ext;
18969    int res;
18970 
18971    d = stuff;
18972    transferee = d->chan1;
18973    transferer = d->chan2;
18974    copy_request(&req, &d->req);
18975 
18976    if (!transferee || !transferer) {
18977       ast_log(LOG_ERROR, "Missing channels for parking! Transferer %s Transferee %s\n", transferer ? "<available>" : "<missing>", transferee ? "<available>" : "<missing>" );
18978       deinit_req(&d->req);
18979       ast_free(d);
18980       return NULL;
18981    }
18982    ast_debug(4, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);
18983 
18984    ast_channel_lock(transferee);
18985    if (ast_do_masquerade(transferee)) {
18986       ast_log(LOG_WARNING, "Masquerade failed.\n");
18987       transmit_response(transferer->tech_pvt, "503 Internal error", &req);
18988       ast_channel_unlock(transferee);
18989       deinit_req(&d->req);
18990       ast_free(d);
18991       return NULL;
18992    } 
18993    ast_channel_unlock(transferee);
18994 
18995    res = ast_park_call(transferee, transferer, 0, &ext);
18996    
18997 
18998 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
18999    if (!res) {
19000       transmit_message_with_text(transferer->tech_pvt, "Unable to park call.\n");
19001    } else {
19002       /* Then tell the transferer what happened */
19003       sprintf(buf, "Call parked on extension '%d'", ext);
19004       transmit_message_with_text(transferer->tech_pvt, buf);
19005    }
19006 #endif
19007 
19008    /* Any way back to the current call??? */
19009    /* Transmit response to the REFER request */
19010    if (!res)   {
19011       /* Transfer succeeded */
19012       append_history(transferer->tech_pvt, "SIPpark", "Parked call on %d", ext);
19013       transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "200 OK", TRUE);
19014       transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
19015       ast_hangup(transferer); /* This will cause a BYE */
19016       ast_debug(1, "SIP Call parked on extension '%d'\n", ext);
19017    } else {
19018       transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "503 Service Unavailable", TRUE);
19019       append_history(transferer->tech_pvt, "SIPpark", "Parking failed\n");
19020       ast_debug(1, "SIP Call parked failed \n");
19021       /* Do not hangup call */
19022    }
19023    deinit_req(&d->req);
19024    ast_free(d);
19025    return NULL;
19026 }
19027 
19028 /*! \brief Park a call using the subsystem in res_features.c 
19029    This is executed in a separate thread
19030 */
19031 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno)
19032 {
19033    struct sip_dual *d;
19034    struct ast_channel *transferee, *transferer;
19035       /* Chan2m: The transferer, chan1m: The transferee */
19036    pthread_t th;
19037 
19038    transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan1->accountcode, chan1->exten, chan1->context, chan1->amaflags, "Parking/%s", chan1->name);
19039    transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->amaflags, "SIPPeer/%s", chan2->name);
19040    if ((!transferer) || (!transferee)) {
19041       if (transferee) {
19042          transferee->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
19043          ast_hangup(transferee);
19044       }
19045       if (transferer) {
19046          transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
19047          ast_hangup(transferer);
19048       }
19049       return -1;
19050    }
19051 
19052    /* Make formats okay */
19053    transferee->readformat = chan1->readformat;
19054    transferee->writeformat = chan1->writeformat;
19055 
19056    /* Prepare for taking over the channel */
19057    ast_channel_masquerade(transferee, chan1);
19058 
19059    /* Setup the extensions and such */
19060    ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
19061    ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
19062    transferee->priority = chan1->priority;
19063       
19064    /* We make a clone of the peer channel too, so we can play
19065       back the announcement */
19066 
19067    /* Make formats okay */
19068    transferer->readformat = chan2->readformat;
19069    transferer->writeformat = chan2->writeformat;
19070    if (!ast_strlen_zero(chan2->parkinglot))
19071       ast_string_field_set(transferer, parkinglot, chan2->parkinglot);
19072 
19073    /* Prepare for taking over the channel.  Go ahead and grab this channel
19074     * lock here to avoid a deadlock with callbacks into the channel driver
19075     * that hold the channel lock and want the pvt lock.  */
19076    while (ast_channel_trylock(chan2)) {
19077       struct sip_pvt *pvt = chan2->tech_pvt;
19078       sip_pvt_unlock(pvt);
19079       usleep(1);
19080       sip_pvt_lock(pvt);
19081    }
19082    ast_channel_masquerade(transferer, chan2);
19083    ast_channel_unlock(chan2);
19084 
19085    /* Setup the extensions and such */
19086    ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
19087    ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
19088    transferer->priority = chan2->priority;
19089 
19090    ast_channel_lock(transferer);
19091    if (ast_do_masquerade(transferer)) {
19092       ast_log(LOG_WARNING, "Masquerade failed :(\n");
19093       ast_channel_unlock(transferer);
19094       transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
19095       ast_hangup(transferer);
19096       return -1;
19097    }
19098    ast_channel_unlock(transferer);
19099    if (!transferer || !transferee) {
19100       if (!transferer) { 
19101          ast_debug(1, "No transferer channel, giving up parking\n");
19102       }
19103       if (!transferee) {
19104          ast_debug(1, "No transferee channel, giving up parking\n");
19105       }
19106       return -1;
19107    }
19108    if (!(d = ast_calloc(1, sizeof(*d)))) {
19109       return -1;
19110    }
19111 
19112    /* Save original request for followup */
19113    copy_request(&d->req, req);
19114    d->chan1 = transferee;  /* Transferee */
19115    d->chan2 = transferer;  /* Transferer */
19116    d->seqno = seqno;
19117    if (ast_pthread_create_detached_background(&th, NULL, sip_park_thread, d) < 0) {
19118       /* Could not start thread */
19119       deinit_req(&d->req);
19120       ast_free(d);   /* We don't need it anymore. If thread is created, d will be free'd
19121                by sip_park_thread() */
19122       return -1;
19123    }
19124    return 0;
19125 }
19126 
19127 /*! \brief Turn off generator data 
19128    XXX Does this function belong in the SIP channel?
19129 */
19130 static void ast_quiet_chan(struct ast_channel *chan) 
19131 {
19132    if (chan && chan->_state == AST_STATE_UP) {
19133       if (ast_test_flag(chan, AST_FLAG_MOH))
19134          ast_moh_stop(chan);
19135       else if (chan->generatordata)
19136          ast_deactivate_generator(chan);
19137    }
19138 }
19139 
19140 /*! \brief Attempt transfer of SIP call 
19141    This fix for attended transfers on a local PBX */
19142 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
19143 {
19144    int res = 0;
19145    struct ast_channel *peera = NULL,   
19146       *peerb = NULL,
19147       *peerc = NULL,
19148       *peerd = NULL;
19149 
19150 
19151    /* We will try to connect the transferee with the target and hangup
19152       all channels to the transferer */   
19153    ast_debug(4, "Sip transfer:--------------------\n");
19154    if (transferer->chan1)
19155       ast_debug(4, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
19156    else
19157       ast_debug(4, "-- No transferer first channel - odd??? \n");
19158    if (target->chan1)
19159       ast_debug(4, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
19160    else
19161       ast_debug(4, "-- No target first channel ---\n");
19162    if (transferer->chan2)
19163       ast_debug(4, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
19164    else
19165       ast_debug(4, "-- No bridged call to transferee\n");
19166    if (target->chan2)
19167       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)");
19168    else
19169       ast_debug(4, "-- No target second channel ---\n");
19170    ast_debug(4, "-- END Sip transfer:--------------------\n");
19171    if (transferer->chan2) { /* We have a bridge on the transferer's channel */
19172       peera = transferer->chan1; /* Transferer - PBX -> transferee channel * the one we hangup */
19173       peerb = target->chan1;     /* Transferer - PBX -> target channel - This will get lost in masq */
19174       peerc = transferer->chan2; /* Asterisk to Transferee */
19175       peerd = target->chan2;     /* Asterisk to Target */
19176       ast_debug(3, "SIP transfer: Four channels to handle\n");
19177    } else if (target->chan2) {   /* Transferer has no bridge (IVR), but transferee */
19178       peera = target->chan1;     /* Transferer to PBX -> target channel */
19179       peerb = transferer->chan1; /* Transferer to IVR*/
19180       peerc = target->chan2;     /* Asterisk to Target */
19181       peerd = transferer->chan2; /* Nothing */
19182       ast_debug(3, "SIP transfer: Three channels to handle\n");
19183    }
19184 
19185    if (peera && peerb && peerc && (peerb != peerc)) {
19186       ast_quiet_chan(peera);     /* Stop generators */
19187       ast_quiet_chan(peerb);  
19188       ast_quiet_chan(peerc);
19189       if (peerd)
19190          ast_quiet_chan(peerd);
19191 
19192       ast_debug(4, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
19193       if (ast_channel_masquerade(peerb, peerc)) {
19194          ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
19195          res = -1;
19196       } else
19197          ast_debug(4, "SIP transfer: Succeeded to masquerade channels.\n");
19198       return res;
19199    } else {
19200       ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
19201       if (transferer->chan1)
19202          ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
19203       if (target->chan1)
19204          ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
19205       return -1;
19206    }
19207    return 0;
19208 }
19209 
19210 /*! \brief Get tag from packet 
19211  *
19212  * \return Returns the pointer to the provided tag buffer,
19213  *         or NULL if the tag was not found.
19214  */
19215 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
19216 {
19217    const char *thetag;
19218 
19219    if (!tagbuf)
19220       return NULL;
19221    tagbuf[0] = '\0';    /* reset the buffer */
19222    thetag = get_header(req, header);
19223    thetag = strcasestr(thetag, ";tag=");
19224    if (thetag) {
19225       thetag += 5;
19226       ast_copy_string(tagbuf, thetag, tagbufsize);
19227       return strsep(&tagbuf, ";");
19228    }
19229    return NULL;
19230 }
19231 
19232 /*! \brief Handle incoming notifications */
19233 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
19234 {
19235    /* This is mostly a skeleton for future improvements */
19236    /* Mostly created to return proper answers on notifications on outbound REFER's */
19237    int res = 0;
19238    const char *event = get_header(req, "Event");
19239    char *eventid = NULL;
19240    char *sep;
19241 
19242    if( (sep = strchr(event, ';')) ) {  /* XXX bug here - overwriting string ? */
19243       *sep++ = '\0';
19244       eventid = sep;
19245    }
19246    
19247    if (sipdebug)
19248       ast_debug(2, "Got NOTIFY Event: %s\n", event);
19249 
19250    if (!strcmp(event, "refer")) {
19251       /* Save nesting depth for now, since there might be other events we will
19252          support in the future */
19253 
19254       /* Handle REFER notifications */
19255 
19256       char buf[1024];
19257       char *cmd, *code;
19258       int respcode;
19259       int success = TRUE;
19260 
19261       /* EventID for each transfer... EventID is basically the REFER cseq 
19262 
19263        We are getting notifications on a call that we transfered
19264        We should hangup when we are getting a 200 OK in a sipfrag
19265        Check if we have an owner of this event */
19266       
19267       /* Check the content type */
19268       if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
19269          /* We need a sipfrag */
19270          transmit_response(p, "400 Bad request", req);
19271          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19272          return -1;
19273       }
19274 
19275       /* Get the text of the attachment */
19276       if (get_msg_text(buf, sizeof(buf), req, TRUE)) {
19277          ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
19278          transmit_response(p, "400 Bad request", req);
19279          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19280          return -1;
19281       }
19282 
19283       /*
19284       From the RFC...
19285       A minimal, but complete, implementation can respond with a single
19286       NOTIFY containing either the body:
19287          SIP/2.0 100 Trying
19288       
19289       if the subscription is pending, the body:
19290          SIP/2.0 200 OK
19291       if the reference was successful, the body:
19292          SIP/2.0 503 Service Unavailable
19293       if the reference failed, or the body:
19294          SIP/2.0 603 Declined
19295 
19296       if the REFER request was accepted before approval to follow the
19297       reference could be obtained and that approval was subsequently denied
19298       (see Section 2.4.7).
19299       
19300       If there are several REFERs in the same dialog, we need to
19301       match the ID of the event header...
19302       */
19303       ast_debug(3, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
19304       cmd = ast_skip_blanks(buf);
19305       code = cmd;
19306       /* We are at SIP/2.0 */
19307       while(*code && (*code > 32)) {   /* Search white space */
19308          code++;
19309       }
19310       *code++ = '\0';
19311       code = ast_skip_blanks(code);
19312       sep = code;
19313       sep++;
19314       while(*sep && (*sep > 32)) {  /* Search white space */
19315          sep++;
19316       }
19317       *sep++ = '\0';       /* Response string */
19318       respcode = atoi(code);
19319       switch (respcode) {
19320       case 100:   /* Trying: */
19321       case 101:   /* dialog establishment */
19322          /* Don't do anything yet */
19323          break;
19324       case 183:   /* Ringing: */
19325          /* Don't do anything yet */
19326          break;
19327       case 200:   /* OK: The new call is up, hangup this call */
19328          /* Hangup the call that we are replacing */
19329          break;
19330       case 301: /* Moved permenantly */
19331       case 302: /* Moved temporarily */
19332          /* Do we get the header in the packet in this case? */
19333          success = FALSE;
19334          break;
19335       case 503:   /* Service Unavailable: The new call failed */
19336             /* Cancel transfer, continue the call */
19337          success = FALSE;
19338          break;
19339       case 603:   /* Declined: Not accepted */
19340             /* Cancel transfer, continue the current call */
19341          success = FALSE;
19342          break;
19343       }
19344       if (!success) {
19345          ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
19346       }
19347       
19348       /* Confirm that we received this packet */
19349       transmit_response(p, "200 OK", req);
19350    } else if (p->mwi && !strcmp(event, "message-summary")) {
19351       char *c = ast_strdupa(get_body(req, "Voice-Message", ':'));
19352 
19353       if (!ast_strlen_zero(c)) {
19354          char *old = strsep(&c, " ");
19355          char *new = strsep(&old, "/");
19356          struct ast_event *event;
19357 
19358          if ((event = ast_event_new(AST_EVENT_MWI,
19359                      AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, p->mwi->mailbox,
19360                      AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, "SIP_Remote",
19361                      AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(new),
19362                      AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(old),
19363                      AST_EVENT_IE_END))) {
19364             ast_event_queue_and_cache(event);
19365          }
19366       }
19367 
19368       transmit_response(p, "200 OK", req);
19369    } else if (!strcmp(event, "keep-alive")) {
19370        /* Used by Sipura/Linksys for NAT pinhole,
19371         * just confirm that we received the packet. */
19372       transmit_response(p, "200 OK", req);
19373    } else {
19374       /* We don't understand this event. */
19375       transmit_response(p, "489 Bad event", req);
19376       res = -1;
19377    }
19378 
19379    if (!p->lastinvite)
19380       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19381 
19382    return res;
19383 }
19384 
19385 /*! \brief Handle incoming OPTIONS request 
19386    An OPTIONS request should be answered like an INVITE from the same UA, including SDP
19387 */
19388 static int handle_request_options(struct sip_pvt *p, struct sip_request *req)
19389 {
19390    int res;
19391 
19392    /*! XXX get_destination assumes we're already authenticated. This means that a request from
19393       a known device (peer) will end up in the wrong context if this is out-of-dialog.
19394       However, we want to handle OPTIONS as light as possible, so we might want to have
19395       a configuration option whether we care or not. Some devices use this for testing
19396       capabilities, which means that we need to match device to answer with proper 
19397       capabilities (including SDP).
19398       \todo Fix handle_request_options device handling with optional authentication
19399          (this needs to be fixed in 1.4 as well)
19400    */
19401 
19402    if (p->lastinvite) {
19403       /* if this is a request in an active dialog, just confirm that the dialog exists. */
19404       transmit_response_with_allow(p, "200 OK", req, 0);
19405       return 0;
19406    }
19407 
19408    res = get_destination(p, req);
19409    build_contact(p);
19410 
19411    if (ast_strlen_zero(p->context))
19412       ast_string_field_set(p, context, sip_cfg.default_context);
19413 
19414    if (ast_shutting_down())
19415       transmit_response_with_allow(p, "503 Unavailable", req, 0);
19416    else if (res < 0)
19417       transmit_response_with_allow(p, "404 Not Found", req, 0);
19418    else 
19419       transmit_response_with_allow(p, "200 OK", req, 0);
19420 
19421    /* Destroy if this OPTIONS was the opening request, but not if
19422       it's in the middle of a normal call flow. */
19423    sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19424 
19425    return res;
19426 }
19427 
19428 /*! \brief Handle the transfer part of INVITE with a replaces: header, 
19429     meaning a target pickup or an attended transfer.
19430     Used only once.
19431    XXX 'ignore' is unused.
19432 
19433    \note this function is called by handle_request_invite(). Four locks
19434    held at the beginning of this function, p, p->owner, p->refer->refer_call->owner...
19435    only p's lock should remain at the end of this function.  p's lock is held by sipsock_read()
19436  */
19437 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *nounlock)
19438 {
19439    int earlyreplace = 0;
19440    int oneleggedreplace = 0;     /* Call with no bridge, propably IVR or voice message */
19441    struct ast_channel *c = p->owner;   /* Our incoming call */
19442    struct ast_channel *replacecall = p->refer->refer_call->owner; /* The channel we're about to take over */
19443    struct ast_channel *targetcall;     /* The bridge to the take-over target */
19444 
19445    struct ast_channel *test;
19446 
19447    /* Check if we're in ring state */
19448    if (replacecall->_state == AST_STATE_RING)
19449       earlyreplace = 1;
19450 
19451    /* Check if we have a bridge */
19452    if (!(targetcall = ast_bridged_channel(replacecall))) {
19453       /* We have no bridge */
19454       if (!earlyreplace) {
19455          ast_debug(2, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
19456          oneleggedreplace = 1;
19457       }
19458    } 
19459    if (targetcall && targetcall->_state == AST_STATE_RINGING)
19460       ast_debug(4, "SIP transfer: Target channel is in ringing state\n");
19461 
19462    if (targetcall) 
19463       ast_debug(4, "SIP transfer: Invite Replace incoming channel should bridge to channel %s while hanging up channel %s\n", targetcall->name, replacecall->name); 
19464    else
19465       ast_debug(4, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name); 
19466 
19467    if (req->ignore) {
19468       ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
19469       /* We should answer something here. If we are here, the
19470          call we are replacing exists, so an accepted 
19471          can't harm */
19472       transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE);
19473       /* Do something more clever here */
19474       if (c) {
19475          *nounlock = 1;
19476          ast_channel_unlock(c);
19477       }
19478       ast_channel_unlock(replacecall);
19479       sip_pvt_unlock(p->refer->refer_call);
19480       return 1;
19481    } 
19482    if (!c) {
19483       /* What to do if no channel ??? */
19484       ast_log(LOG_ERROR, "Unable to create new channel.  Invite/replace failed.\n");
19485       transmit_response_reliable(p, "503 Service Unavailable", req);
19486       append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
19487       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19488       ast_channel_unlock(replacecall);
19489       sip_pvt_unlock(p->refer->refer_call);
19490       return 1;
19491    }
19492    append_history(p, "Xfer", "INVITE/Replace received");
19493    /* We have three channels to play with
19494       channel c: New incoming call
19495       targetcall: Call from PBX to target
19496       p->refer->refer_call: SIP pvt dialog from transferer to pbx.
19497       replacecall: The owner of the previous
19498       We need to masq C into refer_call to connect to 
19499       targetcall;
19500       If we are talking to internal audio stream, target call is null.
19501    */
19502 
19503    /* Fake call progress */
19504    transmit_response(p, "100 Trying", req);
19505    ast_setstate(c, AST_STATE_RING);
19506 
19507    /* Masquerade the new call into the referred call to connect to target call 
19508       Targetcall is not touched by the masq */
19509 
19510    /* Answer the incoming call and set channel to UP state */
19511    transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE);
19512       
19513    ast_setstate(c, AST_STATE_UP);
19514    
19515    /* Stop music on hold and other generators */
19516    ast_quiet_chan(replacecall);
19517    ast_quiet_chan(targetcall);
19518    ast_debug(4, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);
19519 
19520    /* Make sure that the masq does not free our PVT for the old call */
19521    if (! earlyreplace && ! oneleggedreplace )
19522       ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER);  /* Delay hangup */
19523 
19524    /* Prepare the masquerade - if this does not happen, we will be gone */
19525    if(ast_channel_masquerade(replacecall, c))
19526       ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
19527    else
19528       ast_debug(4, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);
19529 
19530    /* C should now be in place of replacecall */
19531    if (ast_do_masquerade(replacecall)) {
19532       ast_log(LOG_WARNING, "Failed to perform masquerade with INVITE replaces\n");
19533    }
19534 
19535    if (earlyreplace || oneleggedreplace ) {
19536       c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
19537    }
19538 
19539    ast_setstate(c, AST_STATE_DOWN);
19540    ast_debug(4, "After transfer:----------------------------\n");
19541    ast_debug(4, " -- C:        %s State %s\n", c->name, ast_state2str(c->_state));
19542    if (replacecall)
19543       ast_debug(4, " -- replacecall:        %s State %s\n", replacecall->name, ast_state2str(replacecall->_state));
19544    if (p->owner) {
19545       ast_debug(4, " -- P->owner: %s State %s\n", p->owner->name, ast_state2str(p->owner->_state));
19546       test = ast_bridged_channel(p->owner);
19547       if (test)
19548          ast_debug(4, " -- Call bridged to P->owner: %s State %s\n", test->name, ast_state2str(test->_state));
19549       else
19550          ast_debug(4, " -- No call bridged to C->owner \n");
19551    } else 
19552       ast_debug(4, " -- No channel yet \n");
19553    ast_debug(4, "End After transfer:----------------------------\n");
19554 
19555    /* unlock sip pvt and owner so hangup can do its thing */
19556    ast_channel_unlock(replacecall);
19557    ast_channel_unlock(c);
19558    sip_pvt_unlock(p->refer->refer_call);
19559    sip_pvt_unlock(p);
19560    *nounlock = 1;
19561 
19562    /* The call should be down with no ast_channel, so hang it up */
19563    c->tech_pvt = dialog_unref(c->tech_pvt, "unref dialog c->tech_pvt");
19564    ast_hangup(c);
19565    sip_pvt_lock(p); /* lock PVT structure again after hangup */
19566 
19567    return 0;
19568 }
19569 
19570 /*! \brief helper routine for sip_uri_cmp to compare URI parameters
19571  *
19572  * This takes the parameters from two SIP URIs and determines
19573  * if the URIs match. The rules for parameters *suck*. Here's a breakdown
19574  * 1. If a parameter appears in both URIs, then they must have the same value
19575  *    in order for the URIs to match
19576  * 2. If one URI has a user, maddr, ttl, or method parameter, then the other
19577  *    URI must also have that parameter and must have the same value
19578  *    in order for the URIs to match
19579  * 3. All other headers appearing in only one URI are not considered when
19580  *    determining if URIs match
19581  *
19582  * \param input1 Parameters from URI 1
19583  * \param input2 Parameters from URI 2
19584  * \retval 0 URIs' parameters match
19585  * \retval nonzero URIs' parameters do not match
19586  */
19587 static int sip_uri_params_cmp(const char *input1, const char *input2)
19588 {
19589    char *params1 = NULL;
19590    char *params2 = NULL;
19591    char *pos1;
19592    char *pos2;
19593    int zerolength1 = 0;
19594    int zerolength2 = 0;
19595    int maddrmatch = 0;
19596    int ttlmatch = 0;
19597    int usermatch = 0;
19598    int methodmatch = 0;
19599 
19600    if (ast_strlen_zero(input1)) {
19601       zerolength1 = 1;
19602    } else {
19603       params1 = ast_strdupa(input1);
19604    }
19605    if (ast_strlen_zero(input2)) {
19606       zerolength2 = 1;
19607    } else {
19608       params2 = ast_strdupa(input2);
19609    }
19610 
19611    /* Quick optimization. If both params are zero-length, then
19612     * they match
19613     */
19614    if (zerolength1 && zerolength2) {
19615       return 0;
19616    }
19617 
19618    for (pos1 = strsep(&params1, ";"); pos1; pos1 = strsep(&params1, ";")) {
19619       char *value1 = pos1;
19620       char *name1 = strsep(&value1, "=");
19621       char *params2dup = NULL;
19622       int matched = 0;
19623       if (!value1) {
19624          value1 = "";
19625       }
19626       /* Checkpoint reached. We have the name and value parsed for param1
19627        * We have to duplicate params2 each time through this loop
19628        * or else the inner loop below will not work properly.
19629        */
19630       if (!zerolength2) {
19631          params2dup = ast_strdupa(params2);
19632       }
19633       for (pos2 = strsep(&params2dup, ";"); pos2; pos2 = strsep(&params2dup, ";")) {
19634          char *name2 = pos2;
19635          char *value2 = strchr(pos2, '=');
19636          if (!value2) {
19637             value2 = "";
19638          } else {
19639             *value2++ = '\0';
19640          }
19641          if (!strcasecmp(name1, name2)) {
19642             if (strcasecmp(value1, value2)) {
19643                goto fail;
19644             } else {
19645                matched = 1;
19646                break;
19647             }
19648          }
19649       }
19650       /* Check to see if the parameter is one of the 'must-match' parameters */
19651       if (!strcasecmp(name1, "maddr")) {
19652          if (matched) {
19653             maddrmatch = 1;
19654          } else {
19655             goto fail;
19656          }
19657       } else if (!strcasecmp(name1, "ttl")) {
19658          if (matched) {
19659             ttlmatch = 1;
19660          } else {
19661             goto fail;
19662          }
19663       } else if (!strcasecmp(name1, "user")) {
19664          if (matched) {
19665             usermatch = 1;
19666          } else {
19667             goto fail;
19668          }
19669       } else if (!strcasecmp(name1, "method")) {
19670          if (matched) {
19671             methodmatch = 1;
19672          } else {
19673             goto fail;
19674          }
19675       }
19676    }
19677 
19678    /* We've made it out of that horrible O(m*n) construct and there are no
19679     * failures yet. We're not done yet, though, because params2 could have
19680     * an maddr, ttl, user, or method header and params1 did not.
19681     */
19682    for (pos2 = strsep(&params2, ";"); pos2; pos2 = strsep(&params2, ";")) {
19683       char *value2 = pos2;
19684       char *name2 = strsep(&value2, "=");
19685       if (!value2) {
19686          value2 = "";
19687       }
19688       if ((!strcasecmp(name2, "maddr") && !maddrmatch) ||
19689             (!strcasecmp(name2, "ttl") && !ttlmatch) ||
19690             (!strcasecmp(name2, "user") && !usermatch) ||
19691             (!strcasecmp(name2, "method") && !methodmatch)) {
19692          goto fail;
19693       }
19694    }
19695    return 0;
19696 
19697 fail:
19698    return 1;
19699 }
19700 
19701 /*! \brief helper routine for sip_uri_cmp
19702  *
19703  * This takes the "headers" from two SIP URIs and determines
19704  * if the URIs match. The rules for headers is simple. If a header
19705  * appears in one URI, then it must also appear in the other URI. The
19706  * order in which the headers appear does not matter.
19707  *
19708  * \param input1 Headers from URI 1
19709  * \param input2 Headers from URI 2
19710  * \return Return 0 if the URIs' headers match, 1 if they do not
19711  */
19712 static int sip_uri_headers_cmp(const char *input1, const char *input2)
19713 {
19714    char *headers1 = NULL;
19715    char *headers2 = NULL;
19716    int zerolength1 = 0;
19717    int zerolength2 = 0;
19718    int different = 0;
19719    char *header1;
19720 
19721    if (ast_strlen_zero(input1)) {
19722       zerolength1 = 1;
19723    } else {
19724       headers1 = ast_strdupa(input1);
19725    }
19726    
19727    if (ast_strlen_zero(input2)) {
19728       zerolength2 = 1;
19729    } else {
19730       headers2 = ast_strdupa(input2);
19731    }
19732 
19733    if ((zerolength1 && !zerolength2) ||
19734          (zerolength2 && !zerolength1))
19735       return 1;
19736 
19737    if (zerolength1 && zerolength2)
19738       return 0;
19739 
19740    /* At this point, we can definitively state that both inputs are
19741     * not zero-length. First, one more optimization. If the length
19742     * of the headers is not equal, then we definitely have no match
19743     */
19744    if (strlen(headers1) != strlen(headers2)) {
19745       return 1;
19746    }
19747 
19748    for (header1 = strsep(&headers1, "&"); header1; header1 = strsep(&headers1, "&")) {
19749       if (!strcasestr(headers2, header1)) {
19750          different = 1;
19751          break;
19752       }
19753    }
19754 
19755    return different;
19756 }
19757 
19758 static int sip_uri_cmp(const char *input1, const char *input2)
19759 {
19760    char *uri1 = ast_strdupa(input1);
19761    char *uri2 = ast_strdupa(input2);
19762    char *host1;
19763    char *host2;
19764    char *params1;
19765    char *params2;
19766    char *headers1;
19767    char *headers2;
19768 
19769    /* Strip off "sip:" from the URI. We know this is present
19770     * because it was checked back in parse_request()
19771     */
19772    strsep(&uri1, ":");
19773    strsep(&uri2, ":");
19774 
19775    if ((host1 = strchr(uri1, '@'))) {
19776       *host1++ = '\0';
19777    }
19778    if ((host2 = strchr(uri2, '@'))) {
19779       *host2++ = '\0';
19780    }
19781 
19782    /* Check for mismatched username and passwords. This is the
19783     * only case-sensitive comparison of a SIP URI
19784     */
19785    if ((host1 && !host2) ||
19786          (host2 && !host1) ||
19787          (host1 && host2 && strcmp(uri1, uri2))) {
19788       return 1;
19789    }
19790 
19791    if (!host1)
19792       host1 = uri1;
19793    if (!host2)
19794       host2 = uri2;
19795 
19796    /* Strip off the parameters and headers so we can compare
19797     * host and port
19798     */
19799 
19800    if ((params1 = strchr(host1, ';'))) {
19801       *params1++ = '\0';
19802    }
19803    if ((params2 = strchr(host2, ';'))) {
19804       *params2++ = '\0';
19805    }
19806 
19807    /* Headers come after parameters, but there may be headers without
19808     * parameters, thus the S_OR
19809     */
19810    if ((headers1 = strchr(S_OR(params1, host1), '?'))) {
19811       *headers1++ = '\0';
19812    }
19813    if ((headers2 = strchr(S_OR(params2, host2), '?'))) {
19814       *headers2++ = '\0';
19815    }
19816 
19817    /* Now the host/port are properly isolated. We can get by with a string comparison
19818     * because the SIP URI checking rules have some interesting exceptions that make
19819     * this possible. I will note 2 in particular
19820     * 1. hostnames which resolve to the same IP address as well as a hostname and its
19821     *    IP address are not considered a match with SIP URI's.
19822     * 2. If one URI specifies a port and the other does not, then the URIs do not match.
19823     *    This includes if one URI explicitly contains port 5060 and the other implies it
19824     *    by not having a port specified.
19825     */
19826 
19827    if (strcasecmp(host1, host2)) {
19828       return 1;
19829    }
19830 
19831    /* Headers have easier rules to follow, so do those first */
19832    if (sip_uri_headers_cmp(headers1, headers2)) {
19833       return 1;
19834    }
19835 
19836    /* And now the parameters. Ugh */
19837    return sip_uri_params_cmp(params1, params2);
19838 }
19839 
19840 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context)
19841 {
19842    struct ast_str *str = ast_str_alloca(AST_MAX_EXTENSION + AST_MAX_CONTEXT + 2);
19843    struct ast_app *pickup = pbx_findapp("Pickup");
19844 
19845    if (!pickup) {
19846       ast_log(LOG_ERROR, "Unable to perform pickup: Application 'Pickup' not loaded (app_directed_pickup.so).\n");
19847       return -1;
19848    }
19849 
19850    ast_str_set(&str, 0, "%s@%s", extension, sip_cfg.notifycid == IGNORE_CONTEXT ? "PICKUPMARK" : context);
19851 
19852    ast_debug(2, "About to call Pickup(%s)\n", str->str);
19853 
19854    /* There is no point in capturing the return value since pickup_exec
19855       doesn't return anything meaningful unless the passed data is an empty
19856       string (which in our case it will not be) */
19857    pbx_exec(channel, pickup, str->str);
19858 
19859    return 0;
19860 }
19861 
19862 /*! \brief Called to deny a T38 reinvite if the core does not respond to our request */
19863 static int sip_t38_abort(const void *data)
19864 {
19865    struct sip_pvt *p = (struct sip_pvt *) data;
19866 
19867    sip_pvt_lock(p);
19868    /* an application may have taken ownership of the T.38 negotiation on this
19869     * channel while we were waiting to grab the lock... if it did, the scheduler
19870     * id will have been reset to -1, which is our indication that we do *not*
19871     * want to abort the negotiation process
19872     */
19873    if (p->t38id != -1) {
19874       change_t38_state(p, T38_DISABLED);
19875       transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
19876       p->t38id = -1;
19877       dialog_unref(p, "unref the dialog ptr from sip_t38_abort, because it held a dialog ptr");
19878    }
19879    sip_pvt_unlock(p);
19880    return 0;
19881 }
19882 
19883 /*! \brief Handle incoming INVITE request
19884 \note    If the INVITE has a Replaces header, it is part of an
19885  * attended transfer. If so, we do not go through the dial
19886  * plan but tries to find the active call and masquerade
19887  * into it 
19888  */
19889 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)
19890 {
19891    int res = 1;
19892    int gotdest;
19893    const char *p_replaces;
19894    char *replace_id = NULL;
19895    int refer_locked = 0;
19896    const char *required;
19897    unsigned int required_profile = 0;
19898    struct ast_channel *c = NULL;    /* New channel */
19899    int reinvite = 0;
19900    int rtn;
19901 
19902    const char *p_uac_se_hdr;       /* UAC's Session-Expires header string                      */
19903    const char *p_uac_min_se;       /* UAC's requested Min-SE interval (char string)            */
19904    int uac_max_se = -1;            /* UAC's Session-Expires in integer format                  */
19905    int uac_min_se = -1;            /* UAC's Min-SE in integer format                           */
19906    int st_active = FALSE;          /* Session-Timer on/off boolean                             */
19907    int st_interval = 0;            /* Session-Timer negotiated refresh interval                */
19908    enum st_refresher st_ref;       /* Session-Timer session refresher                          */
19909    int dlg_min_se = -1;
19910    struct {
19911       char exten[AST_MAX_EXTENSION];
19912       char context[AST_MAX_CONTEXT];
19913    } pickup = {
19914       .exten = "",
19915    };
19916    st_ref = SESSION_TIMER_REFRESHER_AUTO;
19917 
19918    /* Find out what they support */
19919    if (!p->sipoptions) {
19920       const char *supported = get_header(req, "Supported");
19921       if (!ast_strlen_zero(supported))
19922          parse_sip_options(p, supported);
19923    }
19924 
19925    /* Find out what they require */
19926    required = get_header(req, "Require");
19927    if (!ast_strlen_zero(required)) {
19928       required_profile = parse_sip_options(NULL, required);
19929       if (required_profile && !(required_profile & (SIP_OPT_REPLACES | SIP_OPT_TIMER))) {
19930          /* At this point we only support REPLACES and Session-Timer */
19931          transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, required);
19932          ast_log(LOG_WARNING, "Received SIP INVITE with unsupported required extension: %s\n", required);
19933          p->invitestate = INV_COMPLETED;
19934          if (!p->lastinvite)
19935             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19936          res = -1;
19937          goto request_invite_cleanup;
19938       }
19939    }
19940 
19941    /* The option tags may be present in Supported: or Require: headers.
19942    Include the Require: option tags for further processing as well */
19943    p->sipoptions |= required_profile;
19944    p->reqsipoptions = required_profile;
19945 
19946    /* Check if this is a loop */
19947    if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && p->owner && (p->invitestate != INV_TERMINATED && p->invitestate != INV_CONFIRMED)) {
19948       /* This is a call to ourself.  Send ourselves an error code and stop
19949          processing immediately, as SIP really has no good mechanism for
19950          being able to call yourself */
19951       /* If pedantic is on, we need to check the tags. If they're different, this is
19952          in fact a forked call through a SIP proxy somewhere. */
19953       int different;
19954       char *initial_rlPart2 = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
19955       char *this_rlPart2 = REQ_OFFSET_TO_STR(req, rlPart2);
19956       if (sip_cfg.pedanticsipchecking)
19957          different = sip_uri_cmp(initial_rlPart2, this_rlPart2);
19958       else
19959          different = strcmp(initial_rlPart2, this_rlPart2);
19960       if (!different) {
19961          transmit_response(p, "482 Loop Detected", req);
19962          p->invitestate = INV_COMPLETED;
19963          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19964          res = 0;
19965          goto request_invite_cleanup;
19966       } else {
19967          /*! This is a spiral. What we need to do is to just change the outgoing INVITE
19968           * so that it now routes to the new Request URI. Since we created the INVITE ourselves
19969           * that should be all we need to do.
19970           * 
19971           * \todo XXX This needs to be reviewed.  YOu don't change the request URI really, you route the packet
19972           * correctly instead...
19973           */
19974          char *uri = ast_strdupa(this_rlPart2);
19975          char *at = strchr(uri, '@');
19976          char *peerorhost;
19977          ast_debug(2, "Potential spiral detected. Original RURI was %s, new RURI is %s\n", initial_rlPart2, this_rlPart2);
19978          transmit_response(p, "100 Trying", req);
19979          if (at) {
19980             *at = '\0';
19981          }
19982          /* Parse out "sip:" */
19983          if ((peerorhost = strchr(uri, ':'))) {
19984             *peerorhost++ = '\0';
19985          }
19986          ast_string_field_set(p, theirtag, NULL);
19987          /* Treat this as if there were a call forward instead...
19988           */
19989          ast_string_field_set(p->owner, call_forward, peerorhost);
19990          ast_queue_control(p->owner, AST_CONTROL_BUSY);
19991          res = 0;
19992          goto request_invite_cleanup;
19993       }
19994    }
19995 
19996    if (!req->ignore && p->pendinginvite) {
19997       if (!ast_test_flag(&p->flags[0], SIP_OUTGOING) && (p->invitestate == INV_COMPLETED || p->invitestate == INV_TERMINATED)) {
19998          /* What do these circumstances mean? We have received an INVITE for an "incoming" dialog for which we
19999           * have sent a final response. We have not yet received an ACK, though (which is why p->pendinginvite is non-zero).
20000           * We also know that the INVITE is not a retransmission, because otherwise the "ignore" flag would be set.
20001           * This means that either we are receiving a reinvite for a terminated dialog, or we are receiving an INVITE with
20002           * credentials based on one we challenged earlier.
20003           *
20004           * The action to take in either case is to treat the INVITE as though it contains an implicit ACK for the previous
20005           * transaction. Calling __sip_ack will take care of this by clearing the p->pendinginvite and removing the response
20006           * from the previous transaction from the list of outstanding packets.
20007           */
20008          __sip_ack(p, p->pendinginvite, 1, 0);
20009       } else {
20010          /* We already have a pending invite. Sorry. You are on hold. */
20011          p->glareinvite = seqno;     /* must hold on to this seqno to process ack and retransmit correctly */
20012          if (p->rtp && find_sdp(req)) {
20013             struct sockaddr_in sin;
20014             if (get_ip_and_port_from_sdp(req, SDP_AUDIO, &sin)) {
20015                ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Audio may not work properly on this call.\n");
20016             } else {
20017                ast_rtp_set_alt_peer(p->rtp, &sin);
20018             }
20019             if (p->vrtp) {
20020                if (get_ip_and_port_from_sdp(req, SDP_VIDEO, &sin)) {
20021                   ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Video may not work properly on this call.\n");
20022                } else {
20023                   ast_rtp_set_alt_peer(p->vrtp, &sin);
20024                }
20025             }
20026          }
20027          transmit_response_reliable(p, "491 Request Pending", req);
20028          ast_debug(1, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
20029          /* Don't destroy dialog here */
20030          res = 0;
20031          goto request_invite_cleanup;
20032       }
20033    }
20034 
20035    p_replaces = get_header(req, "Replaces");
20036    if (!ast_strlen_zero(p_replaces)) {
20037       /* We have a replaces header */
20038       char *ptr;
20039       char *fromtag = NULL;
20040       char *totag = NULL;
20041       char *start, *to;
20042       int error = 0;
20043 
20044       if (p->owner) {
20045          ast_debug(3, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
20046          transmit_response_reliable(p, "400 Bad request", req);   /* The best way to not not accept the transfer */
20047          /* Do not destroy existing call */
20048          res = -1;
20049          goto request_invite_cleanup;
20050       }
20051 
20052       if (sipdebug)
20053          ast_debug(3, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
20054       /* Create a buffer we can manipulate */
20055       replace_id = ast_strdupa(p_replaces);
20056       ast_uri_decode(replace_id);
20057 
20058       if (!p->refer && !sip_refer_allocate(p)) {
20059          transmit_response_reliable(p, "500 Server Internal Error", req);
20060          append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
20061          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20062          p->invitestate = INV_COMPLETED;
20063          res = -1;
20064          goto request_invite_cleanup;
20065       }
20066 
20067       /*  Todo: (When we find phones that support this)
20068          if the replaces header contains ";early-only"
20069          we can only replace the call in early
20070          stage, not after it's up.
20071 
20072          If it's not in early mode, 486 Busy.
20073       */
20074 
20075       /* Skip leading whitespace */
20076       replace_id = ast_skip_blanks(replace_id);
20077 
20078       start = replace_id;
20079       while ( (ptr = strsep(&start, ";")) ) {
20080          ptr = ast_skip_blanks(ptr); /* XXX maybe unnecessary ? */
20081          if ( (to = strcasestr(ptr, "to-tag=") ) )
20082             totag = to + 7;   /* skip the keyword */
20083          else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
20084             fromtag = to + 9; /* skip the keyword */
20085             fromtag = strsep(&fromtag, "&"); /* trim what ? */
20086          }
20087       }
20088 
20089       if (sipdebug)
20090          ast_debug(4, "Invite/replaces: Will use Replace-Call-ID : %s Fromtag: %s Totag: %s\n",
20091                  replace_id,
20092                  fromtag ? fromtag : "<no from tag>",
20093                  totag ? totag : "<no to tag>");
20094 
20095       /* Try to find call that we are replacing.
20096          If we have a Replaces header, we need to cancel that call if we succeed with this call.
20097          First we cheat a little and look for a magic call-id from phones that support
20098          dialog-info+xml so we can do technology independent pickup... */
20099       if (strncmp(replace_id, "pickup-", 7) == 0) {
20100          struct sip_pvt *subscription = NULL;
20101          replace_id += 7; /* Worst case we are looking at \0 */
20102 
20103          if ((subscription = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
20104             ast_log(LOG_NOTICE, "Unable to find subscription with call-id: %s\n", replace_id);
20105             transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
20106             error = 1;
20107          } else {
20108             ast_log(LOG_NOTICE, "Trying to pick up %s@%s\n", subscription->exten, subscription->context);
20109             ast_copy_string(pickup.exten, subscription->exten, sizeof(pickup.exten));
20110             ast_copy_string(pickup.context, subscription->context, sizeof(pickup.context));
20111             sip_pvt_unlock(subscription);
20112             if (subscription->owner) {
20113                ast_channel_unlock(subscription->owner);
20114             }
20115          }
20116       }
20117 
20118       /* This locks both refer_call pvt and refer_call pvt's owner!!!*/
20119       if (!error && ast_strlen_zero(pickup.exten) && (p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
20120          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
20121          transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
20122          error = 1;
20123       } else {
20124          refer_locked = 1;
20125       }
20126 
20127       /* The matched call is the call from the transferer to Asterisk .
20128          We want to bridge the bridged part of the call to the 
20129          incoming invite, thus taking over the refered call */
20130 
20131       if (p->refer->refer_call == p) {
20132          ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
20133          p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
20134          transmit_response_reliable(p, "400 Bad request", req);   /* The best way to not not accept the transfer */
20135          error = 1;
20136       }
20137 
20138       if (!error && ast_strlen_zero(pickup.exten) && !p->refer->refer_call->owner) {
20139          /* Oops, someting wrong anyway, no owner, no call */
20140          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
20141          /* Check for better return code */
20142          transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replace)", req);
20143          error = 1;
20144       }
20145 
20146       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) {
20147          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
20148          transmit_response_reliable(p, "603 Declined (Replaces)", req);
20149          error = 1;
20150       }
20151 
20152       if (error) {   /* Give up this dialog */
20153          append_history(p, "Xfer", "INVITE/Replace Failed.");
20154          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20155          sip_pvt_unlock(p);
20156          if (p->refer->refer_call) {
20157             sip_pvt_unlock(p->refer->refer_call);
20158             if (p->refer->refer_call->owner) {
20159                ast_channel_unlock(p->refer->refer_call->owner);
20160             }
20161          }
20162          refer_locked = 0;
20163          p->invitestate = INV_COMPLETED;
20164          res = -1;
20165          goto request_invite_cleanup;
20166       }
20167    }
20168 
20169    /* Check if this is an INVITE that sets up a new dialog or
20170       a re-invite in an existing dialog */
20171 
20172    if (!req->ignore) {
20173       int newcall = (p->initreq.headers ? TRUE : FALSE);
20174 
20175       if (sip_cancel_destroy(p))
20176          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
20177       /* This also counts as a pending invite */
20178       p->pendinginvite = seqno;
20179       check_via(p, req);
20180 
20181       copy_request(&p->initreq, req);     /* Save this INVITE as the transaction basis */
20182       if (sipdebug)
20183          ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
20184       if (!p->owner) {  /* Not a re-invite */
20185          if (debug)
20186             ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
20187          if (newcall)
20188             append_history(p, "Invite", "New call: %s", p->callid);
20189          parse_ok_contact(p, req);
20190       } else { /* Re-invite on existing call */
20191          ast_clear_flag(&p->flags[0], SIP_OUTGOING);  /* This is now an inbound dialog */
20192          /* Handle SDP here if we already have an owner */
20193          if (find_sdp(req)) {
20194             if (process_sdp(p, req, SDP_T38_INITIATE)) {
20195                transmit_response_reliable(p, "488 Not acceptable here", req);
20196                if (!p->lastinvite)
20197                   sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20198                res = -1;
20199                goto request_invite_cleanup;
20200             }
20201             ast_queue_control(p->owner, AST_CONTROL_SRCUPDATE);
20202          } else {
20203             p->jointcapability = p->capability;
20204             ast_debug(1, "Hm....  No sdp for the moment\n");
20205             /* Some devices signal they want to be put off hold by sending a re-invite
20206                *without* an SDP, which is supposed to mean "Go back to your state"
20207                and since they put os on remote hold, we go back to off hold */
20208             if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
20209                ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
20210                /* Activate a re-invite */
20211                ast_queue_frame(p->owner, &ast_null_frame);
20212                change_hold_state(p, req, FALSE, 0);
20213             }
20214          }
20215          if (p->do_history) /* This is a response, note what it was for */
20216             append_history(p, "ReInv", "Re-invite received");
20217       }
20218    } else if (debug)
20219       ast_verbose("Ignoring this INVITE request\n");
20220 
20221    if (!p->lastinvite && !req->ignore && !p->owner) {
20222       /* This is a new invite */
20223       /* Handle authentication if this is our first invite */
20224       res = check_user(p, req, SIP_INVITE, e, XMIT_RELIABLE, sin);
20225       if (res == AUTH_CHALLENGE_SENT) {
20226          p->invitestate = INV_COMPLETED;     /* Needs to restart in another INVITE transaction */
20227          res = 0;
20228          goto request_invite_cleanup;
20229       }
20230       if (res < 0) { /* Something failed in authentication */
20231          if (res == AUTH_FAKE_AUTH) {
20232             ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
20233             transmit_fake_auth_response(p, SIP_INVITE, req, XMIT_RELIABLE);
20234          } else {
20235             ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
20236             transmit_response_reliable(p, "403 Forbidden", req);
20237          }
20238          p->invitestate = INV_COMPLETED;
20239          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20240          ast_string_field_set(p, theirtag, NULL);
20241          res = 0;
20242          goto request_invite_cleanup;
20243       }
20244 
20245       /* If T38 is needed but not present, then make it magically appear */
20246       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && !p->udptl) {
20247          if ((p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr))) {
20248             p->t38_maxdatagram = global_t38_maxdatagram;
20249             set_t38_capabilities(p);
20250          } else {
20251             /* udptl creation failed, T38 can not be supported on this dialog */
20252             ast_debug(1, "UDPTL creation failed on dialog.\n");
20253             ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
20254          }
20255       }
20256 
20257       /* We have a succesful authentication, process the SDP portion if there is one */
20258       if (find_sdp(req)) {
20259          if (process_sdp(p, req, SDP_T38_INITIATE)) {
20260             /* Unacceptable codecs */
20261             transmit_response_reliable(p, "488 Not acceptable here", req);
20262             p->invitestate = INV_COMPLETED;
20263             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20264             ast_debug(1, "No compatible codecs for this SIP call.\n");
20265             res = -1;
20266             goto request_invite_cleanup;
20267          }
20268       } else { /* No SDP in invite, call control session */
20269          p->jointcapability = p->capability;
20270          ast_debug(2, "No SDP in Invite, third party call control\n");
20271       }
20272 
20273       /* Queue NULL frame to prod ast_rtp_bridge if appropriate */
20274       /* This seems redundant ... see !p-owner above */
20275       if (p->owner)
20276          ast_queue_frame(p->owner, &ast_null_frame);
20277 
20278 
20279       /* Initialize the context if it hasn't been already */
20280       if (ast_strlen_zero(p->context))
20281          ast_string_field_set(p, context, sip_cfg.default_context);
20282 
20283 
20284       /* Check number of concurrent calls -vs- incoming limit HERE */
20285       ast_debug(1, "Checking SIP call limits for device %s\n", p->username);
20286       if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
20287          if (res < 0) {
20288             ast_log(LOG_NOTICE, "Failed to place call for device %s, too many calls\n", p->username);
20289             transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
20290             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20291             p->invitestate = INV_COMPLETED;
20292          }
20293          res = 0;
20294          goto request_invite_cleanup;
20295       }
20296       gotdest = get_destination(p, NULL); /* Get destination right away */
20297       get_rdnis(p, NULL);        /* Get redirect information */
20298       extract_uri(p, req);       /* Get the Contact URI */
20299       build_contact(p);       /* Build our contact header */
20300 
20301       if (p->rtp) {
20302          ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
20303          ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
20304       }
20305 
20306       if (!replace_id && gotdest) { /* No matching extension found */
20307          if (gotdest == 1 && ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP))
20308             transmit_response_reliable(p, "484 Address Incomplete", req);
20309          else {
20310             char *decoded_exten = ast_strdupa(p->exten);
20311 
20312             transmit_response_reliable(p, "404 Not Found", req);
20313             ast_uri_decode(decoded_exten);
20314             ast_log(LOG_NOTICE, "Call from '%s' to extension"
20315                " '%s' rejected because extension not found in context '%s'.\n",
20316                S_OR(p->username, p->peername), decoded_exten, p->context);
20317          }
20318          p->invitestate = INV_COMPLETED;
20319          update_call_counter(p, DEC_CALL_LIMIT);
20320          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20321          res = 0;
20322          goto request_invite_cleanup;
20323       } else {
20324 
20325          /* If no extension was specified, use the s one */
20326          /* Basically for calling to IP/Host name only */
20327          if (ast_strlen_zero(p->exten))
20328             ast_string_field_set(p, exten, "s");
20329          /* Initialize our tag */
20330 
20331          make_our_tag(p->tag, sizeof(p->tag));
20332          /* First invitation - create the channel.  Allocation
20333           * failures are handled below. */
20334          c = sip_new(p, AST_STATE_DOWN, S_OR(p->peername, NULL));
20335          *recount = 1;
20336 
20337          /* Save Record-Route for any later requests we make on this dialogue */
20338          build_route(p, req, 0);
20339 
20340          if (c) {
20341             /* Pre-lock the call */
20342             ast_channel_lock(c);
20343          }
20344       }
20345    } else {
20346       if (sipdebug) {
20347          if (!req->ignore)
20348             ast_debug(2, "Got a SIP re-invite for call %s\n", p->callid);
20349          else
20350             ast_debug(2, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
20351       }
20352       if (!req->ignore)
20353          reinvite = 1;
20354       c = p->owner;
20355    }
20356 
20357    /* Session-Timers */
20358    if ((p->sipoptions & SIP_OPT_TIMER) && !ast_strlen_zero(get_header(req, "Session-Expires"))) {
20359       /* The UAC has requested session-timers for this session. Negotiate
20360       the session refresh interval and who will be the refresher */
20361       ast_debug(2, "Incoming INVITE with 'timer' option supported and \"Session-Expires\" header.\n");
20362 
20363       /* Allocate Session-Timers struct w/in the dialog */
20364       if (!p->stimer)
20365          sip_st_alloc(p);
20366 
20367       /* Parse the Session-Expires header */
20368       p_uac_se_hdr = get_header(req, "Session-Expires");
20369       rtn = parse_session_expires(p_uac_se_hdr, &uac_max_se, &st_ref);
20370       if (rtn != 0) {
20371          transmit_response_reliable(p, "400 Session-Expires Invalid Syntax", req);
20372          p->invitestate = INV_COMPLETED;
20373          if (!p->lastinvite) {
20374             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20375          }
20376          res = -1;
20377          goto request_invite_cleanup;
20378       }
20379 
20380       /* Parse the Min-SE header */
20381       p_uac_min_se = get_header(req, "Min-SE");
20382       if (!ast_strlen_zero(p_uac_min_se)) {
20383          rtn = parse_minse(p_uac_min_se, &uac_min_se); 
20384          if (rtn != 0) {
20385             transmit_response_reliable(p, "400 Min-SE Invalid Syntax", req);
20386             p->invitestate = INV_COMPLETED;
20387             if (!p->lastinvite) {
20388                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20389             }
20390             res = -1;
20391             goto request_invite_cleanup;
20392          }
20393       }
20394 
20395       dlg_min_se = st_get_se(p, FALSE);
20396       switch (st_get_mode(p)) {
20397       case SESSION_TIMER_MODE_ACCEPT:
20398       case SESSION_TIMER_MODE_ORIGINATE:
20399          if (uac_max_se > 0 && uac_max_se < dlg_min_se) {
20400             transmit_response_with_minse(p, "422 Session Interval Too Small", req, dlg_min_se);
20401             p->invitestate = INV_COMPLETED;
20402             if (!p->lastinvite) {
20403                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20404             }
20405             res = -1;
20406             goto request_invite_cleanup;
20407          }
20408 
20409          p->stimer->st_active_peer_ua = TRUE;
20410          st_active = TRUE;
20411          if (st_ref == SESSION_TIMER_REFRESHER_AUTO) {
20412             st_ref = st_get_refresher(p);
20413          }
20414 
20415          if (uac_max_se > 0) {
20416             int dlg_max_se = st_get_se(p, TRUE);
20417             if (dlg_max_se >= uac_min_se) {
20418                st_interval = (uac_max_se < dlg_max_se) ? uac_max_se : dlg_max_se;
20419             } else {
20420                st_interval = uac_max_se;
20421             }
20422          } else {
20423             /* Set to default max value */
20424             st_interval = global_max_se;
20425          }
20426          break;
20427 
20428       case SESSION_TIMER_MODE_REFUSE:
20429          if (p->reqsipoptions & SIP_OPT_TIMER) {
20430             transmit_response_with_unsupported(p, "420 Option Disabled", req, required);
20431             ast_log(LOG_WARNING, "Received SIP INVITE with supported but disabled option: %s\n", required);
20432             p->invitestate = INV_COMPLETED;
20433             if (!p->lastinvite) {
20434                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20435             }
20436             res = -1;
20437             goto request_invite_cleanup;
20438          }
20439          break;
20440 
20441       default:
20442          ast_log(LOG_ERROR, "Internal Error %d at %s:%d\n", st_get_mode(p), __FILE__, __LINE__);
20443          break;
20444       }
20445    } else {
20446       /* The UAC did not request session-timers.  Asterisk (UAS), will now decide
20447       (based on session-timer-mode in sip.conf) whether to run session-timers for
20448       this session or not. */
20449       switch (st_get_mode(p)) {
20450       case SESSION_TIMER_MODE_ORIGINATE:
20451          st_active = TRUE;
20452          st_interval = st_get_se(p, TRUE);
20453          st_ref = SESSION_TIMER_REFRESHER_UAS;
20454          p->stimer->st_active_peer_ua = FALSE;
20455          break;
20456 
20457       default:
20458          break;
20459       }
20460    }
20461 
20462    if (reinvite == 0) {
20463       /* Session-Timers: Start session refresh timer based on negotiation/config */
20464       if (st_active == TRUE) {
20465          p->stimer->st_active   = TRUE;
20466          p->stimer->st_interval = st_interval;
20467          p->stimer->st_ref      = st_ref;
20468          start_session_timer(p);
20469       }
20470    } else {
20471       if (p->stimer->st_active == TRUE) {
20472          /* Session-Timers:  A re-invite request sent within a dialog will serve as 
20473          a refresh request, no matter whether the re-invite was sent for refreshing 
20474          the session or modifying it.*/
20475          ast_debug (2, "Restarting session-timers on a refresh - %s\n", p->callid);
20476 
20477          /* The UAC may be adjusting the session-timers mid-session */
20478          if (st_interval > 0) {
20479             p->stimer->st_interval = st_interval;
20480             p->stimer->st_ref      = st_ref;
20481          }
20482 
20483          restart_session_timer(p);
20484          if (p->stimer->st_expirys > 0) {
20485             p->stimer->st_expirys--;
20486          }
20487       }
20488    }
20489 
20490    if (!req->ignore && p)
20491       p->lastinvite = seqno;
20492 
20493    if (c && replace_id) {  /* Attended transfer or call pickup - we're the target */
20494       if (!ast_strlen_zero(pickup.exten)) {
20495          append_history(p, "Xfer", "INVITE/Replace received");
20496 
20497          /* Let the caller know we're giving it a shot */
20498          transmit_response(p, "100 Trying", req);
20499          p->invitestate = INV_PROCEEDING;
20500          ast_setstate(c, AST_STATE_RING);
20501 
20502          /* Do the pickup itself */
20503          ast_channel_unlock(c);
20504          *nounlock = 1;
20505          do_magic_pickup(c, pickup.exten, pickup.context);
20506 
20507          /* Now we're either masqueraded or we failed to pickup, in either case we... */
20508          sip_pvt_unlock(p);
20509          ast_hangup(c);
20510          sip_pvt_lock(p);
20511 
20512          res = 0;
20513          goto request_invite_cleanup;
20514       } else {
20515          /* Go and take over the target call */
20516          if (sipdebug)
20517             ast_debug(4, "Sending this call to the invite/replcaes handler %s\n", p->callid);
20518          res = handle_invite_replaces(p, req, debug, seqno, sin, nounlock);
20519          refer_locked = 0;
20520          goto request_invite_cleanup;
20521       }
20522    }
20523 
20524 
20525    if (c) { /* We have a call  -either a new call or an old one (RE-INVITE) */
20526       enum ast_channel_state c_state = c->_state;
20527 
20528       if (c_state != AST_STATE_UP && reinvite &&
20529          (p->invitestate == INV_TERMINATED || p->invitestate == INV_CONFIRMED)) {
20530          /* If these conditions are true, and the channel is still in the 'ringing'
20531           * state, then this likely means that we have a situation where the initial
20532           * INVITE transaction has completed *but* the channel's state has not yet been
20533           * changed to UP. The reason this could happen is if the reinvite is received
20534           * on the SIP socket prior to an application calling ast_read on this channel
20535           * to read the answer frame we earlier queued on it. In this case, the reinvite
20536           * is completely legitimate so we need to handle this the same as if the channel 
20537           * were already UP. Thus we are purposely falling through to the AST_STATE_UP case.
20538           */
20539          c_state = AST_STATE_UP;
20540       }
20541 
20542       switch(c_state) {
20543       case AST_STATE_DOWN:
20544          ast_debug(2, "%s: New call is still down.... Trying... \n", c->name);
20545          transmit_provisional_response(p, "100 Trying", req, 0);
20546          p->invitestate = INV_PROCEEDING;
20547          ast_setstate(c, AST_STATE_RING);
20548          if (strcmp(p->exten, ast_pickup_ext())) { /* Call to extension -start pbx on this call */
20549             enum ast_pbx_result result;
20550 
20551             result = ast_pbx_start(c);
20552 
20553             switch(result) {
20554             case AST_PBX_FAILED:
20555                ast_log(LOG_WARNING, "Failed to start PBX :(\n");
20556                p->invitestate = INV_COMPLETED;
20557                transmit_response_reliable(p, "503 Unavailable", req);
20558                break;
20559             case AST_PBX_CALL_LIMIT:
20560                ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
20561                p->invitestate = INV_COMPLETED;
20562                transmit_response_reliable(p, "480 Temporarily Unavailable", req);
20563                break;
20564             case AST_PBX_SUCCESS:
20565                /* nothing to do */
20566                break;
20567             }
20568 
20569             if (result) {
20570 
20571                /* Unlock locks so ast_hangup can do its magic */
20572                ast_channel_unlock(c);
20573                sip_pvt_unlock(p);
20574                ast_hangup(c);
20575                sip_pvt_lock(p);
20576                c = NULL;
20577             }
20578          } else { /* Pickup call in call group */
20579             ast_channel_unlock(c);
20580             *nounlock = 1;
20581             if (ast_pickup_call(c)) {
20582                ast_log(LOG_NOTICE, "Nothing to pick up for %s\n", p->callid);
20583                transmit_response_reliable(p, "503 Unavailable", req);
20584                sip_alreadygone(p);
20585                /* Unlock locks so ast_hangup can do its magic */
20586                sip_pvt_unlock(p);
20587                c->hangupcause = AST_CAUSE_CALL_REJECTED;
20588             } else {
20589                sip_pvt_unlock(p);
20590                ast_setstate(c, AST_STATE_DOWN);
20591                c->hangupcause = AST_CAUSE_NORMAL_CLEARING;
20592             }
20593             p->invitestate = INV_COMPLETED;
20594             ast_hangup(c);
20595             sip_pvt_lock(p);
20596             c = NULL;
20597          }
20598          break;
20599       case AST_STATE_RING:
20600          transmit_provisional_response(p, "100 Trying", req, 0);
20601          p->invitestate = INV_PROCEEDING;
20602          break;
20603       case AST_STATE_RINGING:
20604          transmit_provisional_response(p, "180 Ringing", req, 0);
20605          p->invitestate = INV_PROCEEDING;
20606          break;
20607       case AST_STATE_UP:
20608          ast_debug(2, "%s: This call is UP.... \n", c->name);
20609 
20610          transmit_response(p, "100 Trying", req);
20611 
20612          if (p->t38.state == T38_PEER_REINVITE) {
20613             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."));
20614          } else if (p->t38.state == T38_ENABLED) {
20615             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
20616             transmit_response_with_t38_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ?  XMIT_UNRELIABLE : XMIT_CRITICAL)));
20617          } else if (p->t38.state == T38_DISABLED) {
20618             /* If this is not a re-invite or something to ignore - it's critical */
20619             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
20620             transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ?  XMIT_UNRELIABLE : XMIT_CRITICAL)), p->session_modify == TRUE ? FALSE:TRUE); 
20621          }
20622 
20623          p->invitestate = INV_TERMINATED;
20624          break;
20625       default:
20626          ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
20627          transmit_response(p, "100 Trying", req);
20628          break;
20629       }
20630    } else {
20631       if (p && (p->autokillid == -1)) {
20632          const char *msg;
20633 
20634          if (!p->jointcapability)
20635             msg = "488 Not Acceptable Here (codec error)";
20636          else {
20637             ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
20638             msg = "503 Unavailable";
20639          }
20640          transmit_response_reliable(p, msg, req);
20641          p->invitestate = INV_COMPLETED;
20642          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20643       }
20644    }
20645 
20646 request_invite_cleanup:
20647 
20648    if (refer_locked && p->refer && p->refer->refer_call) {
20649       sip_pvt_unlock(p->refer->refer_call);
20650       if (p->refer->refer_call->owner) {
20651          ast_channel_unlock(p->refer->refer_call->owner);
20652       }
20653    }
20654 
20655    return res;
20656 }
20657 
20658 /*! \brief  Find all call legs and bridge transferee with target 
20659  * called from handle_request_refer */
20660 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno)
20661 {
20662    struct sip_dual target;    /* Chan 1: Call from tranferer to Asterisk */
20663                /* Chan 2: Call from Asterisk to target */
20664    int res = 0;
20665    struct sip_pvt *targetcall_pvt;
20666 
20667    /* Check if the call ID of the replaces header does exist locally */
20668    if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag, 
20669       transferer->refer->replaces_callid_fromtag))) {
20670       if (transferer->refer->localtransfer) {
20671          /* We did not find the refered call. Sorry, can't accept then */
20672          /* Let's fake a response from someone else in order
20673             to follow the standard */
20674          transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
20675          append_history(transferer, "Xfer", "Refer failed");
20676          ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);  
20677          transferer->refer->status = REFER_FAILED;
20678          return -1;
20679       }
20680       /* Fall through for remote transfers that we did not find locally */
20681       ast_debug(3, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
20682       return 0;
20683    }
20684 
20685    /* Ok, we can accept this transfer */
20686    append_history(transferer, "Xfer", "Refer accepted");
20687    if (!targetcall_pvt->owner) { /* No active channel */
20688       ast_debug(4, "SIP attended transfer: Error: No owner of target call\n");
20689       /* Cancel transfer */
20690       transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
20691       append_history(transferer, "Xfer", "Refer failed");
20692       ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
20693       transferer->refer->status = REFER_FAILED;
20694       sip_pvt_unlock(targetcall_pvt);
20695       if (targetcall_pvt)
20696          ao2_t_ref(targetcall_pvt, -1, "Drop targetcall_pvt pointer");
20697       return -1;
20698    }
20699 
20700    /* We have a channel, find the bridge */
20701    target.chan1 = targetcall_pvt->owner;           /* Transferer to Asterisk */
20702    target.chan2 = ast_bridged_channel(targetcall_pvt->owner);  /* Asterisk to target */
20703 
20704    if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
20705       /* Wrong state of new channel */
20706       if (target.chan2) 
20707          ast_debug(4, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
20708       else if (target.chan1->_state != AST_STATE_RING)
20709          ast_debug(4, "SIP attended transfer: Error: No target channel\n");
20710       else
20711          ast_debug(4, "SIP attended transfer: Attempting transfer in ringing state\n");
20712    }
20713 
20714    /* Transfer */
20715    if (sipdebug) {
20716       if (current->chan2)  /* We have two bridges */
20717          ast_debug(4, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
20718       else        /* One bridge, propably transfer of IVR/voicemail etc */
20719          ast_debug(4, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
20720    }
20721 
20722    ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);   /* Delay hangup */
20723 
20724    /* Perform the transfer */
20725    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",
20726       transferer->owner->name,
20727       transferer->owner->uniqueid,
20728       transferer->callid,
20729       target.chan1->name,
20730       target.chan1->uniqueid);
20731    res = attempt_transfer(current, &target);
20732    sip_pvt_unlock(targetcall_pvt);
20733    if (res) {
20734       /* Failed transfer */
20735       transmit_notify_with_sipfrag(transferer, seqno, "486 Busy Here", TRUE);
20736       append_history(transferer, "Xfer", "Refer failed");
20737       if (targetcall_pvt->owner)
20738          ast_channel_unlock(targetcall_pvt->owner);
20739       ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
20740    } else {
20741       /* Transfer succeeded! */
20742       const char *xfersound = pbx_builtin_getvar_helper(target.chan1, "ATTENDED_TRANSFER_COMPLETE_SOUND");
20743 
20744       /* Tell transferer that we're done. */
20745       transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
20746       append_history(transferer, "Xfer", "Refer succeeded");
20747       transferer->refer->status = REFER_200OK;
20748       if (target.chan2 && !ast_strlen_zero(xfersound) && ast_streamfile(target.chan2, xfersound, target.chan2->language) >= 0) {
20749          ast_waitstream(target.chan2, "");
20750       }
20751       if (targetcall_pvt->owner) {
20752          ast_debug(1, "SIP attended transfer: Unlocking channel %s\n", targetcall_pvt->owner->name);
20753          ast_channel_unlock(targetcall_pvt->owner);
20754       }
20755    }
20756    if (targetcall_pvt)
20757       ao2_t_ref(targetcall_pvt, -1, "drop targetcall_pvt");
20758    return 1;
20759 }
20760 
20761 
20762 /*! \brief Handle incoming REFER request */
20763 /*! \page SIP_REFER SIP transfer Support (REFER)
20764 
20765    REFER is used for call transfer in SIP. We get a REFER
20766    to place a new call with an INVITE somwhere and then
20767    keep the transferor up-to-date of the transfer. If the
20768    transfer fails, get back on line with the orginal call. 
20769 
20770    - REFER can be sent outside or inside of a dialog.
20771      Asterisk only accepts REFER inside of a dialog.
20772 
20773    - If we get a replaces header, it is an attended transfer
20774 
20775    \par Blind transfers
20776    The transferor provides the transferee
20777    with the transfer targets contact. The signalling between
20778    transferer or transferee should not be cancelled, so the
20779    call is recoverable if the transfer target can not be reached 
20780    by the transferee.
20781 
20782    In this case, Asterisk receives a TRANSFER from
20783    the transferor, thus is the transferee. We should
20784    try to set up a call to the contact provided
20785    and if that fails, re-connect the current session.
20786    If the new call is set up, we issue a hangup.
20787    In this scenario, we are following section 5.2
20788    in the SIP CC Transfer draft. (Transfer without
20789    a GRUU)
20790 
20791    \par Transfer with consultation hold
20792    In this case, the transferor
20793    talks to the transfer target before the transfer takes place.
20794    This is implemented with SIP hold and transfer.
20795    Note: The invite From: string could indicate a transfer.
20796    (Section 6. Transfer with consultation hold)
20797    The transferor places the transferee on hold, starts a call
20798    with the transfer target to alert them to the impending
20799    transfer, terminates the connection with the target, then
20800    proceeds with the transfer (as in Blind transfer above)
20801 
20802    \par Attended transfer
20803    The transferor places the transferee
20804    on hold, calls the transfer target to alert them,
20805    places the target on hold, then proceeds with the transfer
20806    using a Replaces header field in the Refer-to header. This
20807    will force the transfee to send an Invite to the target,
20808    with a replaces header that instructs the target to
20809    hangup the call between the transferor and the target.
20810    In this case, the Refer/to: uses the AOR address. (The same
20811    URI that the transferee used to establish the session with
20812    the transfer target (To: ). The Require: replaces header should
20813    be in the INVITE to avoid the wrong UA in a forked SIP proxy
20814    scenario to answer and have no call to replace with.
20815 
20816    The referred-by header is *NOT* required, but if we get it,
20817    can be copied into the INVITE to the transfer target to 
20818    inform the target about the transferor
20819 
20820    "Any REFER request has to be appropriately authenticated.".
20821    
20822    We can't destroy dialogs, since we want the call to continue.
20823    
20824    */
20825 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock)
20826 {
20827    struct sip_dual current;   /* Chan1: Call between asterisk and transferer */
20828                /* Chan2: Call between asterisk and transferee */
20829 
20830    int res = 0;
20831    current.req.data = NULL;
20832 
20833    if (req->debug)
20834       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");
20835 
20836    if (!p->owner) {
20837       /* This is a REFER outside of an existing SIP dialog */
20838       /* We can't handle that, so decline it */
20839       ast_debug(3, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
20840       transmit_response(p, "603 Declined (No dialog)", req);
20841       if (!req->ignore) {
20842          append_history(p, "Xfer", "Refer failed. Outside of dialog.");
20843          sip_alreadygone(p);
20844          pvt_set_needdestroy(p, "outside of dialog");
20845       }
20846       return 0;
20847    }
20848 
20849 
20850    /* Check if transfer is allowed from this device */
20851    if (p->allowtransfer == TRANSFER_CLOSED ) {
20852       /* Transfer not allowed, decline */
20853       transmit_response(p, "603 Declined (policy)", req);
20854       append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
20855       /* Do not destroy SIP session */
20856       return 0;
20857    }
20858 
20859    if (!req->ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
20860       /* Already have a pending REFER */
20861       transmit_response(p, "491 Request pending", req);
20862       append_history(p, "Xfer", "Refer failed. Request pending.");
20863       return 0;
20864    }
20865 
20866    /* Allocate memory for call transfer data */
20867    if (!p->refer && !sip_refer_allocate(p)) {
20868       transmit_response(p, "500 Internal Server Error", req);
20869       append_history(p, "Xfer", "Refer failed. Memory allocation error.");
20870       return -3;
20871    }
20872 
20873    res = get_refer_info(p, req); /* Extract headers */
20874 
20875    p->refer->status = REFER_SENT;
20876 
20877    if (res != 0) {
20878       switch (res) {
20879       case -2: /* Syntax error */
20880          transmit_response(p, "400 Bad Request (Refer-to missing)", req);
20881          append_history(p, "Xfer", "Refer failed. Refer-to missing.");
20882          if (req->debug)
20883             ast_debug(1, "SIP transfer to black hole can't be handled (no refer-to: )\n");
20884          break;
20885       case -3:
20886          transmit_response(p, "603 Declined (Non sip: uri)", req);
20887          append_history(p, "Xfer", "Refer failed. Non SIP uri");
20888          if (req->debug)
20889             ast_debug(1, "SIP transfer to non-SIP uri denied\n");
20890          break;
20891       default:
20892          /* Refer-to extension not found, fake a failed transfer */
20893          transmit_response(p, "202 Accepted", req);
20894          append_history(p, "Xfer", "Refer failed. Bad extension.");
20895          transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
20896          ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
20897          if (req->debug)
20898             ast_debug(1, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
20899          break;
20900       } 
20901       return 0;
20902    }
20903    if (ast_strlen_zero(p->context))
20904       ast_string_field_set(p, context, sip_cfg.default_context);
20905 
20906    /* If we do not support SIP domains, all transfers are local */
20907    if (sip_cfg.allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
20908       p->refer->localtransfer = 1;
20909       if (sipdebug)
20910          ast_debug(3, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
20911    } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
20912       /* This PBX doesn't bother with SIP domains or domain is local, so this transfer is local */
20913       p->refer->localtransfer = 1;
20914    } else if (sipdebug)
20915          ast_debug(3, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
20916 
20917    /* Is this a repeat of a current request? Ignore it */
20918    /* Don't know what else to do right now. */
20919    if (req->ignore) 
20920       return res;
20921 
20922    /* If this is a blind transfer, we have the following
20923    channels to work with:
20924    - chan1, chan2: The current call between transferer and transferee (2 channels)
20925    - target_channel: A new call from the transferee to the target (1 channel)
20926    We need to stay tuned to what happens in order to be able
20927    to bring back the call to the transferer */
20928 
20929    /* If this is a attended transfer, we should have all call legs within reach:
20930    - chan1, chan2: The call between the transferer and transferee (2 channels)
20931    - target_channel, targetcall_pvt: The call between the transferer and the target (2 channels)
20932    We want to bridge chan2 with targetcall_pvt!
20933    
20934    The replaces call id in the refer message points
20935    to the call leg between Asterisk and the transferer.
20936    So we need to connect the target and the transferee channel
20937    and hangup the two other channels silently 
20938    
20939    If the target is non-local, the call ID could be on a remote
20940    machine and we need to send an INVITE with replaces to the
20941    target. We basically handle this as a blind transfer
20942    and let the sip_call function catch that we need replaces
20943    header in the INVITE.
20944    */
20945 
20946 
20947    /* Get the transferer's channel */
20948    current.chan1 = p->owner;
20949 
20950    /* Find the other part of the bridge (2) - transferee */
20951    current.chan2 = ast_bridged_channel(current.chan1);
20952    
20953    if (sipdebug)
20954       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>");
20955 
20956    if (!current.chan2 && !p->refer->attendedtransfer) {
20957       /* No bridged channel, propably IVR or echo or similar... */
20958       /* Guess we should masquerade or something here */
20959       /* Until we figure it out, refuse transfer of such calls */
20960       if (sipdebug)
20961          ast_debug(3, "Refused SIP transfer on non-bridged channel.\n");
20962       p->refer->status = REFER_FAILED;
20963       append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
20964       transmit_response(p, "603 Declined", req);
20965       return -1;
20966    }
20967 
20968    if (current.chan2) {
20969       if (sipdebug)
20970          ast_debug(4, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);
20971 
20972       ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
20973    }
20974 
20975    ast_set_flag(&p->flags[0], SIP_GOTREFER);
20976 
20977    /* From here on failures will be indicated with NOTIFY requests */
20978    transmit_response(p, "202 Accepted", req);
20979 
20980    /* Attended transfer: Find all call legs and bridge transferee with target*/
20981    if (p->refer->attendedtransfer) {
20982       if ((res = local_attended_transfer(p, &current, req, seqno)))
20983          return res; /* We're done with the transfer */
20984       /* Fall through for remote transfers that we did not find locally */
20985       if (sipdebug)
20986          ast_debug(4, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
20987       /* Fallthrough if we can't find the call leg internally */
20988    }
20989 
20990 
20991    /* Parking a call */
20992    if (p->refer->localtransfer && !strcmp(p->refer->refer_to, ast_parking_ext())) {
20993       /* Must release c's lock now, because it will not longer be accessible after the transfer! */
20994       *nounlock = 1;
20995       ast_channel_unlock(current.chan1);
20996       copy_request(&current.req, req);
20997       ast_clear_flag(&p->flags[0], SIP_GOTREFER);
20998       p->refer->status = REFER_200OK;
20999       append_history(p, "Xfer", "REFER to call parking.");
21000       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",
21001          current.chan1->name,
21002          current.chan1->uniqueid,
21003          p->callid,
21004          current.chan2->name,
21005          current.chan2->uniqueid,
21006          p->refer->refer_to);
21007       if (sipdebug)
21008          ast_debug(4, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
21009       if ((res = sip_park(current.chan2, current.chan1, req, seqno))) {
21010          transmit_notify_with_sipfrag(p, seqno, "500 Internal Server Error", TRUE);
21011       }
21012       return res;
21013    } 
21014 
21015    /* Blind transfers and remote attended xfers */
21016    if (current.chan1 && current.chan2) {
21017       ast_debug(3, "chan1->name: %s\n", current.chan1->name);
21018       pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
21019    }
21020    if (current.chan2) {
21021       pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
21022       pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", p->refer->refer_to_domain);
21023       pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
21024       /* One for the new channel */
21025       pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
21026       /* Attended transfer to remote host, prepare headers for the INVITE */
21027       if (p->refer->referred_by) 
21028          pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", p->refer->referred_by);
21029    }
21030    /* Generate a Replaces string to be used in the INVITE during attended transfer */
21031    if (!ast_strlen_zero(p->refer->replaces_callid)) {
21032       char tempheader[SIPBUFSIZE];
21033       snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid, 
21034             p->refer->replaces_callid_totag ? ";to-tag=" : "", 
21035             p->refer->replaces_callid_totag, 
21036             p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
21037             p->refer->replaces_callid_fromtag);
21038       if (current.chan2)
21039          pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
21040    }
21041    /* Must release lock now, because it will not longer
21042       be accessible after the transfer! */
21043    *nounlock = 1;
21044    ast_channel_unlock(current.chan1);
21045 
21046    /* Connect the call */
21047 
21048    /* FAKE ringing if not attended transfer */
21049    if (!p->refer->attendedtransfer)
21050       transmit_notify_with_sipfrag(p, seqno, "183 Ringing", FALSE); 
21051 
21052    /* For blind transfer, this will lead to a new call */
21053    /* For attended transfer to remote host, this will lead to
21054       a new SIP call with a replaces header, if the dial plan allows it 
21055    */
21056    if (!current.chan2) {
21057       /* We have no bridge, so we're talking with Asterisk somehow */
21058       /* We need to masquerade this call */
21059       /* What to do to fix this situation:
21060          * Set up the new call in a new channel 
21061          * Let the new channel masq into this channel
21062          Please add that code here :-)
21063       */
21064       p->refer->status = REFER_FAILED;
21065       transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
21066       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
21067       append_history(p, "Xfer", "Refer failed (only bridged calls).");
21068       return -1;
21069    }
21070    ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);   /* Delay hangup */
21071 
21072 
21073    /* For blind transfers, move the call to the new extensions. For attended transfers on multiple
21074       servers - generate an INVITE with Replaces. Either way, let the dial plan decided  */
21075    /* indicate before masquerade so the indication actually makes it to the real channel
21076       when using local channels with MOH passthru */
21077    ast_indicate(current.chan2, AST_CONTROL_UNHOLD);
21078    res = ast_async_goto(current.chan2, p->refer->refer_to_context, p->refer->refer_to, 1);
21079 
21080    if (!res) {
21081       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",
21082          current.chan1->name,
21083          current.chan1->uniqueid,
21084          p->callid,
21085          current.chan2->name,
21086          current.chan2->uniqueid,
21087          p->refer->refer_to, p->refer->refer_to_context);
21088       /* Success  - we have a new channel */
21089       ast_debug(3, "%s transfer succeeded. Telling transferer.\n", p->refer->attendedtransfer? "Attended" : "Blind");
21090       transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
21091       if (p->refer->localtransfer)
21092          p->refer->status = REFER_200OK;
21093       if (p->owner)
21094          p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
21095       append_history(p, "Xfer", "Refer succeeded.");
21096       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
21097       /* Do not hangup call, the other side do that when we say 200 OK */
21098       /* We could possibly implement a timer here, auto congestion */
21099       res = 0;
21100    } else {
21101       ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Don't delay hangup */
21102       ast_debug(3, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
21103       append_history(p, "Xfer", "Refer failed.");
21104       /* Failure of some kind */
21105       p->refer->status = REFER_FAILED;
21106       transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
21107       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
21108       res = -1;
21109    }
21110    return res;
21111 }
21112 
21113 /*! \brief Handle incoming CANCEL request */
21114 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
21115 {
21116       
21117    check_via(p, req);
21118    sip_alreadygone(p);
21119 
21120    /* At this point, we could have cancelled the invite at the same time
21121       as the other side sends a CANCEL. Our final reply with error code
21122       might not have been received by the other side before the CANCEL
21123       was sent, so let's just give up retransmissions and waiting for
21124       ACK on our error code. The call is hanging up any way. */
21125    if (p->invitestate == INV_TERMINATED)
21126       __sip_pretend_ack(p);
21127    else
21128       p->invitestate = INV_CANCELLED;
21129    
21130    if (p->owner && p->owner->_state == AST_STATE_UP) {
21131       /* This call is up, cancel is ignored, we need a bye */
21132       transmit_response(p, "200 OK", req);
21133       ast_debug(1, "Got CANCEL on an answered call. Ignoring... \n");
21134       return 0;
21135    }
21136 
21137    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) 
21138       update_call_counter(p, DEC_CALL_LIMIT);
21139 
21140    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
21141    if (p->owner)
21142       ast_queue_hangup(p->owner);
21143    else
21144       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21145    if (p->initreq.len > 0) {
21146       struct sip_pkt *pkt, *prev_pkt;
21147       /* If the CANCEL we are receiving is a retransmission, and we already have scheduled
21148        * a reliable 487, then we don't want to schedule another one on top of the previous
21149        * one.
21150        *
21151        * As odd as this may sound, we can't rely on the previously-transmitted "reliable" 
21152        * response in this situation. What if we've sent all of our reliable responses 
21153        * already and now all of a sudden, we get this second CANCEL?
21154        *
21155        * The only way to do this correctly is to cancel our previously-scheduled reliably-
21156        * transmitted response and send a new one in its place.
21157        */
21158       for (pkt = p->packets, prev_pkt = NULL; pkt; prev_pkt = pkt, pkt = pkt->next) {
21159          if (pkt->seqno == p->lastinvite && pkt->response_code == 487) {
21160             AST_SCHED_DEL(sched, pkt->retransid);
21161             UNLINK(pkt, p->packets, prev_pkt);
21162             ast_free(pkt);
21163             break;
21164          }
21165       }
21166       transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
21167       transmit_response(p, "200 OK", req);
21168       return 1;
21169    } else {
21170       transmit_response(p, "481 Call Leg Does Not Exist", req);
21171       return 0;
21172    }
21173 }
21174 
21175 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen)
21176 {
21177    struct sip_pvt *p = chan->tech_pvt;
21178    char *all = "", *parse = ast_strdupa(preparse);
21179    int res = 0;
21180    AST_DECLARE_APP_ARGS(args,
21181       AST_APP_ARG(param);
21182       AST_APP_ARG(type);
21183       AST_APP_ARG(field);
21184    );
21185    AST_STANDARD_APP_ARGS(args, parse);
21186 
21187    /* Sanity check */
21188    if (!IS_SIP_TECH(chan->tech)) {
21189       ast_log(LOG_ERROR, "Cannot call %s on a non-SIP channel\n", funcname);
21190       return 0;
21191    }
21192 
21193    memset(buf, 0, buflen);
21194 
21195    if (p == NULL) {
21196       return -1;
21197    }
21198 
21199    if (!strcasecmp(args.param, "peerip")) {
21200       ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", buflen);
21201    } else if (!strcasecmp(args.param, "recvip")) {
21202       ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", buflen);
21203    } else if (!strcasecmp(args.param, "from")) {
21204       ast_copy_string(buf, p->from, buflen);
21205    } else if (!strcasecmp(args.param, "uri")) {
21206       ast_copy_string(buf, p->uri, buflen);
21207    } else if (!strcasecmp(args.param, "useragent")) {
21208       ast_copy_string(buf, p->useragent, buflen);
21209    } else if (!strcasecmp(args.param, "peername")) {
21210       ast_copy_string(buf, p->peername, buflen);
21211    } else if (!strcasecmp(args.param, "t38passthrough")) {
21212       ast_copy_string(buf, (p->t38.state == T38_DISABLED) ? "0" : "1", buflen);
21213    } else if (!strcasecmp(args.param, "rtpdest")) {
21214       struct sockaddr_in sin;
21215       struct ast_rtp *stream = NULL;
21216 
21217       if (ast_strlen_zero(args.type))
21218          args.type = "audio";
21219 
21220       if (!strcasecmp(args.type, "audio")) {
21221          stream = p->rtp;
21222       } else if (!strcasecmp(args.type, "video")) {
21223          stream = p->vrtp;
21224       } else if (!strcasecmp(args.type, "text")) {
21225          stream = p->trtp;
21226       } else {
21227          return -1;
21228       }
21229 
21230       if (!stream) {
21231          return -1;
21232       }
21233 
21234       ast_rtp_get_peer(stream, &sin);
21235       snprintf(buf, buflen, "%s:%d", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
21236    } else if (!strcasecmp(args.param, "rtpqos")) {
21237       struct ast_rtp_quality qos;
21238       struct ast_rtp *rtp = p->rtp;
21239       
21240       memset(&qos, 0, sizeof(qos));
21241 
21242       if (ast_strlen_zero(args.type))
21243          args.type = "audio";
21244       if (ast_strlen_zero(args.field))
21245          args.field = "all";
21246       
21247       if (!strcasecmp(args.type, "AUDIO")) {
21248          all = ast_rtp_get_quality(rtp = p->rtp, &qos, RTPQOS_SUMMARY);
21249       } else if (!strcasecmp(args.type, "VIDEO")) {
21250          all = ast_rtp_get_quality(rtp = p->vrtp, &qos, RTPQOS_SUMMARY);
21251       } else if (!strcasecmp(args.type, "TEXT")) {
21252          all = ast_rtp_get_quality(rtp = p->trtp, &qos, RTPQOS_SUMMARY);
21253       } else {
21254          return -1;
21255       }
21256       
21257       if (!strcasecmp(args.field, "local_ssrc"))
21258          snprintf(buf, buflen, "%u", qos.local_ssrc);
21259       else if (!strcasecmp(args.field, "local_lostpackets"))
21260          snprintf(buf, buflen, "%u", qos.local_lostpackets);
21261       else if (!strcasecmp(args.field, "local_jitter"))
21262          snprintf(buf, buflen, "%.0f", qos.local_jitter * 1000.0);
21263       else if (!strcasecmp(args.field, "local_count"))
21264          snprintf(buf, buflen, "%u", qos.local_count);
21265       else if (!strcasecmp(args.field, "remote_ssrc"))
21266          snprintf(buf, buflen, "%u", qos.remote_ssrc);
21267       else if (!strcasecmp(args.field, "remote_lostpackets"))
21268          snprintf(buf, buflen, "%u", qos.remote_lostpackets);
21269       else if (!strcasecmp(args.field, "remote_jitter"))
21270          snprintf(buf, buflen, "%.0f", qos.remote_jitter * 1000.0);
21271       else if (!strcasecmp(args.field, "remote_count"))
21272          snprintf(buf, buflen, "%u", qos.remote_count);
21273       else if (!strcasecmp(args.field, "rtt"))
21274          snprintf(buf, buflen, "%.0f", qos.rtt * 1000.0);
21275       else if (!strcasecmp(args.field, "all"))
21276          ast_copy_string(buf, all, buflen);
21277       else if (!ast_rtp_get_qos(rtp, args.field, buf, buflen))
21278           ;
21279       else {
21280          ast_log(LOG_WARNING, "Unrecognized argument '%s' to %s\n", preparse, funcname);
21281          return -1;
21282       }
21283    } else {
21284       res = -1;
21285    }
21286    return res;
21287 }
21288 
21289 /*! \brief Handle incoming BYE request */
21290 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
21291 {
21292    struct ast_channel *c=NULL;
21293    int res;
21294    struct ast_channel *bridged_to;
21295    
21296    /* If we have an INCOMING invite that we haven't answered, terminate that transaction */
21297    if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !req->ignore) {
21298       transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
21299    }
21300 
21301    __sip_pretend_ack(p);
21302 
21303    p->invitestate = INV_TERMINATED;
21304 
21305    copy_request(&p->initreq, req);
21306    if (sipdebug)
21307       ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
21308    check_via(p, req);
21309    sip_alreadygone(p);
21310 
21311    /* Get RTCP quality before end of call */
21312    if (p->do_history || p->owner) {
21313       struct ast_channel *bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
21314       char *videoqos, *textqos;
21315 
21316       /* We need to get the lock on bridge because ast_rtp_set_vars will attempt
21317        * to lock the bridge. This may get hairy...
21318        */
21319       while (bridge && ast_channel_trylock(bridge)) {
21320          ast_channel_unlock(p->owner);
21321          do {
21322             /* Can't use DEADLOCK_AVOIDANCE since p is an ao2 object */
21323             sip_pvt_unlock(p);
21324             usleep(1);
21325             sip_pvt_lock(p);
21326          } while (p->owner && ast_channel_trylock(p->owner));
21327          bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
21328       }
21329 
21330       if (p->rtp) {  
21331          if (p->do_history) {
21332             char *audioqos,
21333                  *audioqos_jitter,
21334                  *audioqos_loss,
21335                  *audioqos_rtt;
21336 
21337             audioqos        = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_SUMMARY);
21338             audioqos_jitter = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_JITTER);
21339             audioqos_loss   = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_LOSS);
21340             audioqos_rtt    = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_RTT);
21341 
21342             append_history(p, "RTCPaudio", "Quality:%s", audioqos);
21343             append_history(p, "RTCPaudioJitter", "Quality:%s", audioqos_jitter);
21344             append_history(p, "RTCPaudioLoss", "Quality:%s", audioqos_loss);
21345             append_history(p, "RTCPaudioRTT", "Quality:%s", audioqos_rtt);
21346          }
21347          
21348          if (p->owner) {
21349             ast_rtp_set_vars(p->owner, p->rtp);
21350          }
21351       }
21352 
21353       if (bridge) {
21354          struct sip_pvt *q = bridge->tech_pvt;
21355 
21356          if (IS_SIP_TECH(bridge->tech) && q && q->rtp)
21357             ast_rtp_set_vars(bridge, q->rtp);
21358          ast_channel_unlock(bridge);
21359       }
21360 
21361       if (p->vrtp) {
21362          videoqos = ast_rtp_get_quality(p->vrtp, NULL, RTPQOS_SUMMARY);
21363          if (p->do_history)
21364             append_history(p, "RTCPvideo", "Quality:%s", videoqos);
21365          if (p->owner)
21366             pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", videoqos);
21367       }
21368 
21369       if (p->trtp) {
21370          textqos = ast_rtp_get_quality(p->trtp, NULL, RTPQOS_SUMMARY);
21371          if (p->do_history)
21372             append_history(p, "RTCPtext", "Quality:%s", textqos);
21373          if (p->owner)
21374             pbx_builtin_setvar_helper(p->owner, "RTPTEXTQOS", textqos);
21375       }
21376    }
21377 
21378    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
21379    stop_session_timer(p); /* Stop Session-Timer */
21380 
21381    if (!ast_strlen_zero(get_header(req, "Also"))) {
21382       ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method.  Ask vendor to support REFER instead\n",
21383          ast_inet_ntoa(p->recv.sin_addr));
21384       if (ast_strlen_zero(p->context))
21385          ast_string_field_set(p, context, sip_cfg.default_context);
21386       res = get_also_info(p, req);
21387       if (!res) {
21388          c = p->owner;
21389          if (c) {
21390             bridged_to = ast_bridged_channel(c);
21391             if (bridged_to) {
21392                /* Don't actually hangup here... */
21393                ast_queue_control(c, AST_CONTROL_UNHOLD);
21394                ast_async_goto(bridged_to, p->context, p->refer->refer_to, 1);
21395             } else
21396                ast_queue_hangup(p->owner);
21397          }
21398       } else {
21399          ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_inet_ntoa(p->recv.sin_addr));
21400          if (p->owner)
21401             ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
21402       }
21403    } else if (p->owner) {
21404       ast_queue_hangup(p->owner);
21405       ast_debug(3, "Received bye, issuing owner hangup\n");
21406    } else {
21407       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21408       ast_debug(3, "Received bye, no owner, selfdestruct soon.\n");
21409    }
21410    ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21411    transmit_response(p, "200 OK", req);
21412 
21413    return 1;
21414 }
21415 
21416 /*! \brief Handle incoming MESSAGE request */
21417 static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
21418 {
21419    if (!req->ignore) {
21420       if (req->debug)
21421          ast_verbose("Receiving message!\n");
21422       receive_message(p, req);
21423    } else
21424       transmit_response(p, "202 Accepted", req);
21425    return 1;
21426 }
21427 
21428 static void add_peer_mwi_subs(struct sip_peer *peer)
21429 {
21430    struct sip_mailbox *mailbox;
21431 
21432    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
21433       mailbox->event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, peer,
21434          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
21435          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
21436          AST_EVENT_IE_END);
21437    }
21438 }
21439 
21440 /*! \brief  Handle incoming SUBSCRIBE request */
21441 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
21442 {
21443    int gotdest = 0;
21444    int res = 0;
21445    int firststate = AST_EXTENSION_REMOVED;
21446    struct sip_peer *authpeer = NULL;
21447    const char *eventheader = get_header(req, "Event");   /* Get Event package name */
21448    int resubscribe = (p->subscribed != NONE) && !req->ignore;
21449    char *temp, *event;
21450 
21451    if (p->initreq.headers) {  
21452       /* We already have a dialog */
21453       if (p->initreq.method != SIP_SUBSCRIBE) {
21454          /* This is a SUBSCRIBE within another SIP dialog, which we do not support */
21455          /* For transfers, this could happen, but since we haven't seen it happening, let us just refuse this */
21456          transmit_response(p, "403 Forbidden (within dialog)", req);
21457          /* Do not destroy session, since we will break the call if we do */
21458          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);
21459          return 0;
21460       } else if (req->debug) {
21461          if (resubscribe)
21462             ast_debug(1, "Got a re-subscribe on existing subscription %s\n", p->callid);
21463          else
21464             ast_debug(1, "Got a new subscription %s (possibly with auth) or retransmission\n", p->callid);
21465       }
21466    }
21467 
21468    /* Check if we have a global disallow setting on subscriptions. 
21469       if so, we don't have to check peer settings after auth, which saves a lot of processing
21470    */
21471    if (!sip_cfg.allowsubscribe) {
21472       transmit_response(p, "403 Forbidden (policy)", req);
21473       pvt_set_needdestroy(p, "forbidden");
21474       return 0;
21475    }
21476 
21477    if (!req->ignore && !resubscribe) { /* Set up dialog, new subscription */
21478       const char *to = get_header(req, "To");
21479       char totag[128];
21480 
21481       /* Check to see if a tag was provided, if so this is actually a resubscription of a dialog we no longer know about */
21482       if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
21483          if (req->debug)
21484             ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
21485          transmit_response(p, "481 Subscription does not exist", req);
21486          pvt_set_needdestroy(p, "subscription does not exist");
21487          return 0;
21488       }
21489 
21490       /* Use this as the basis */
21491       if (req->debug)
21492          ast_verbose("Creating new subscription\n");
21493 
21494       copy_request(&p->initreq, req);
21495       if (sipdebug)
21496          ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
21497       check_via(p, req);
21498       build_route(p, req, 0);
21499    } else if (req->debug && req->ignore)
21500       ast_verbose("Ignoring this SUBSCRIBE request\n");
21501 
21502    /* Find parameters to Event: header value and remove them for now */
21503    if (ast_strlen_zero(eventheader)) {
21504       transmit_response(p, "489 Bad Event", req);
21505       ast_debug(2, "Received SIP subscribe for unknown event package: <none>\n");
21506       pvt_set_needdestroy(p, "unknown event package in subscribe");
21507       return 0;
21508    }
21509 
21510    if ( (strchr(eventheader, ';'))) {
21511       event = ast_strdupa(eventheader);   /* Since eventheader is a const, we can't change it */
21512       temp = strchr(event, ';');       
21513       *temp = '\0';           /* Remove any options for now */
21514                      /* We might need to use them later :-) */
21515    } else
21516       event = (char *) eventheader;    /* XXX is this legal ? */
21517 
21518    /* Handle authentication if we're new and not a retransmission. We can't just
21519     * use if !req->ignore, because then we'll end up sending
21520     * a 200 OK if someone retransmits without sending auth */
21521    if (p->subscribed == NONE || resubscribe) {
21522       res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, sin, &authpeer);
21523 
21524       /* if an authentication response was sent, we are done here */
21525       if (res == AUTH_CHALLENGE_SENT)  /* authpeer = NULL here */
21526          return 0;
21527       if (res < 0) {
21528          if (res == AUTH_FAKE_AUTH) {
21529             ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
21530             transmit_fake_auth_response(p, SIP_SUBSCRIBE, req, XMIT_UNRELIABLE);
21531          } else {
21532             ast_log(LOG_NOTICE, "Failed to authenticate device %s for SUBSCRIBE\n", get_header(req, "From"));
21533             transmit_response_reliable(p, "403 Forbidden", req);
21534          }
21535 
21536          pvt_set_needdestroy(p, "authentication failed");
21537          return 0;
21538       }
21539    }
21540 
21541    /* At this point, authpeer cannot be NULL. Remember we hold a reference,
21542     * so we must release it when done.
21543     * XXX must remove all the checks for authpeer == NULL.
21544     */
21545 
21546    /* Check if this device  is allowed to subscribe at all */
21547    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
21548       transmit_response(p, "403 Forbidden (policy)", req);
21549       pvt_set_needdestroy(p, "subscription not allowed");
21550       if (authpeer)
21551          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 1)");
21552       return 0;
21553    }
21554 
21555    if (strcmp(event, "message-summary")) {
21556       /* Get destination right away */
21557       gotdest = get_destination(p, NULL);
21558    }
21559 
21560    /* Get full contact header - this needs to be used as a request URI in NOTIFY's */
21561    parse_ok_contact(p, req);
21562 
21563    build_contact(p);
21564    if (gotdest) {
21565       transmit_response(p, "404 Not Found", req);
21566       pvt_set_needdestroy(p, "subscription target not found");
21567       if (authpeer)
21568          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
21569       return 0;
21570    }
21571 
21572    /* Initialize tag for new subscriptions */   
21573    if (ast_strlen_zero(p->tag))
21574       make_our_tag(p->tag, sizeof(p->tag));
21575 
21576    if (!strcmp(event, "presence") || !strcmp(event, "dialog")) { /* Presence, RFC 3842 */
21577       unsigned int pidf_xml;
21578       const char *accept;
21579       int start = 0;
21580       enum subscriptiontype subscribed = NONE;
21581       const char *unknown_acceptheader = NULL;
21582 
21583       if (authpeer)  /* We do not need the authpeer any more */
21584          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
21585 
21586       /* Header from Xten Eye-beam Accept: multipart/related, application/rlmi+xml, application/pidf+xml, application/xpidf+xml */
21587 
21588       accept = __get_header(req, "Accept", &start);
21589       while ((subscribed == NONE) && !ast_strlen_zero(accept)) {
21590          pidf_xml = strstr(accept, "application/pidf+xml") ? 1 : 0;
21591 
21592          /* Older versions of Polycom firmware will claim pidf+xml, but really
21593           * they only support xpidf+xml. */
21594          if (pidf_xml && strstr(p->useragent, "Polycom")) {
21595             subscribed = XPIDF_XML;
21596          } else if (pidf_xml) {
21597             subscribed = PIDF_XML;         /* RFC 3863 format */
21598          } else if (strstr(accept, "application/dialog-info+xml")) {
21599             subscribed = DIALOG_INFO_XML;
21600             /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
21601          } else if (strstr(accept, "application/cpim-pidf+xml")) {
21602             subscribed = CPIM_PIDF_XML;    /* RFC 3863 format */
21603          } else if (strstr(accept, "application/xpidf+xml")) {
21604             subscribed = XPIDF_XML;        /* Early pre-RFC 3863 format with MSN additions (Microsoft Messenger) */
21605          } else {
21606             unknown_acceptheader = accept;
21607          }
21608          /* check to see if there is another Accept header present */
21609          accept = __get_header(req, "Accept", &start);
21610       }
21611 
21612       if (!start) {
21613          if (p->subscribed == NONE) { /* if the subscribed field is not already set, and there is no accept header... */
21614             transmit_response(p, "489 Bad Event", req);
21615             ast_log(LOG_WARNING,"SUBSCRIBE failure: no Accept header: pvt: "
21616                "stateid: %d, laststate: %d, dialogver: %d, subscribecont: "
21617                "'%s', subscribeuri: '%s'\n",
21618                p->stateid,
21619                p->laststate,
21620                p->dialogver,
21621                p->subscribecontext,
21622                p->subscribeuri);
21623             pvt_set_needdestroy(p, "no Accept header");
21624             return 0;
21625          }
21626          /* if p->subscribed is non-zero, then accept is not obligatory; according to rfc 3265 section 3.1.3, at least.
21627             so, we'll just let it ride, keeping the value from a previous subscription, and not abort the subscription */
21628       } else if (subscribed == NONE) {
21629          /* Can't find a format for events that we know about */
21630          char mybuf[200];
21631          if (!ast_strlen_zero(unknown_acceptheader)) {
21632             snprintf(mybuf, sizeof(mybuf), "489 Bad Event (format %s)", unknown_acceptheader);
21633          } else {
21634             snprintf(mybuf, sizeof(mybuf), "489 Bad Event");
21635          }
21636          transmit_response(p, mybuf, req);
21637          ast_log(LOG_WARNING,"SUBSCRIBE failure: unrecognized format:"
21638             "'%s' pvt: subscribed: %d, stateid: %d, laststate: %d,"
21639             "dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
21640             unknown_acceptheader,
21641             (int)p->subscribed,
21642             p->stateid,
21643             p->laststate,
21644             p->dialogver,
21645             p->subscribecontext,
21646             p->subscribeuri);
21647          pvt_set_needdestroy(p, "unrecognized format");
21648          return 0;
21649       } else {
21650          p->subscribed = subscribed;
21651       }
21652    } else if (!strcmp(event, "message-summary")) {
21653       int start = 0;
21654       int found_supported = 0;
21655       const char *acceptheader;
21656 
21657       acceptheader = __get_header(req, "Accept", &start);
21658       while (!found_supported && !ast_strlen_zero(acceptheader)) {
21659          found_supported = strcmp(acceptheader, "application/simple-message-summary") ? 0 : 1;
21660          if (!found_supported && (option_debug > 2)) {
21661             ast_log(LOG_DEBUG, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
21662          }
21663          acceptheader = __get_header(req, "Accept", &start);
21664       }
21665       if (start && !found_supported) {
21666          /* Format requested that we do not support */
21667          transmit_response(p, "406 Not Acceptable", req);
21668          ast_debug(2, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
21669          pvt_set_needdestroy(p, "unknown format");
21670          if (authpeer)
21671             unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 3)");
21672          return 0;
21673       }
21674 
21675       /* Looks like they actually want a mailbox status 
21676         This version of Asterisk supports mailbox subscriptions
21677         The subscribed URI needs to exist in the dial plan
21678         In most devices, this is configurable to the voicemailmain extension you use
21679       */
21680       if (!authpeer || AST_LIST_EMPTY(&authpeer->mailboxes)) {
21681          transmit_response(p, "404 Not found (no mailbox)", req);
21682          pvt_set_needdestroy(p, "received 404 response");
21683          ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", authpeer->name);
21684          if (authpeer)
21685             unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 4)");
21686          return 0;
21687       }
21688 
21689       p->subscribed = MWI_NOTIFICATION;
21690       if (ast_test_flag(&authpeer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY)) {
21691          add_peer_mwi_subs(authpeer);
21692       }
21693       if (authpeer->mwipvt && authpeer->mwipvt != p) {   /* Destroy old PVT if this is a new one */
21694          /* We only allow one subscription per peer */
21695          dialog_unlink_all(authpeer->mwipvt, TRUE, TRUE);
21696          authpeer->mwipvt = dialog_unref(authpeer->mwipvt, "unref dialog authpeer->mwipvt");
21697          /* sip_destroy(authpeer->mwipvt); */
21698       }
21699       if (authpeer->mwipvt)
21700          dialog_unref(authpeer->mwipvt, "Unref previously stored mwipvt dialog pointer");
21701       authpeer->mwipvt = dialog_ref(p, "setting peers' mwipvt to p");      /* Link from peer to pvt UH- should this be dialog_ref()? */
21702       if (p->relatedpeer)
21703          unref_peer(p->relatedpeer, "Unref previously stored relatedpeer ptr");
21704       p->relatedpeer = ref_peer(authpeer, "setting dialog's relatedpeer pointer");  /* already refcounted...Link from pvt to peer UH- should this be dialog_ref()? */
21705       /* Do not release authpeer here */
21706    } else { /* At this point, Asterisk does not understand the specified event */
21707       transmit_response(p, "489 Bad Event", req);
21708       ast_debug(2, "Received SIP subscribe for unknown event package: %s\n", event);
21709       pvt_set_needdestroy(p, "unknown event package");
21710       if (authpeer)
21711          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 5)");
21712       return 0;
21713    }
21714 
21715    /* Add subscription for extension state from the PBX core */
21716    if (p->subscribed != MWI_NOTIFICATION && !resubscribe) {
21717       if (p->stateid > -1) {
21718          ast_extension_state_del(p->stateid, cb_extensionstate);
21719          /* we need to dec the refcount, now that the extensionstate is removed */
21720          dialog_unref(p, "the extensionstate containing this dialog ptr was deleted");
21721       }
21722       p->stateid = ast_extension_state_add(p->context, p->exten, cb_extensionstate, dialog_ref(p,"copying dialog ptr into extension state struct"));
21723    }
21724 
21725    if (!req->ignore && p)
21726       p->lastinvite = seqno;
21727    if (p && !p->needdestroy) {
21728       p->expiry = atoi(get_header(req, "Expires"));
21729 
21730       /* check if the requested expiry-time is within the approved limits from sip.conf */
21731       if (p->expiry > max_expiry)
21732          p->expiry = max_expiry;
21733       if (p->expiry < min_expiry && p->expiry > 0)
21734          p->expiry = min_expiry;
21735 
21736       if (sipdebug) {
21737          if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
21738             ast_debug(2, "Adding subscription for mailbox notification - peer %s\n", p->relatedpeer->name);
21739          else
21740             ast_debug(2, "Adding subscription for extension %s context %s for peer %s\n", p->exten, p->context, p->username);
21741       }
21742       if (p->autokillid > -1 && sip_cancel_destroy(p))   /* Remove subscription expiry for renewals */
21743          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
21744       if (p->expiry > 0)
21745          sip_scheddestroy(p, (p->expiry + 10) * 1000);   /* Set timer for destruction of call at expiration */
21746 
21747       if (p->subscribed == MWI_NOTIFICATION) {
21748          ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21749          transmit_response(p, "200 OK", req);
21750          if (p->relatedpeer) {   /* Send first notification */
21751             ao2_lock(p->relatedpeer); /* was WRLOCK */
21752             sip_send_mwi_to_peer(p->relatedpeer, NULL, 0);
21753             ao2_unlock(p->relatedpeer);
21754          }
21755       } else {
21756 
21757          if ((firststate = ast_extension_state(NULL, p->context, p->exten)) < 0) {
21758 
21759             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));
21760             transmit_response(p, "404 Not found", req);
21761             pvt_set_needdestroy(p, "no extension for SUBSCRIBE");
21762             return 0;
21763          }
21764          ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21765          transmit_response(p, "200 OK", req);
21766          transmit_state_notify(p, firststate, 1, FALSE); /* Send first notification */
21767          append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
21768          /* hide the 'complete' exten/context in the refer_to field for later display */
21769          ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
21770          /* Deleted the slow iteration of all sip dialogs to find old subscribes from this peer for exten@context */
21771 
21772       }
21773       if (!p->expiry) {
21774          pvt_set_needdestroy(p, "forcing expiration");
21775       }
21776    }
21777    return 1;
21778 }
21779 
21780 /*! \brief Handle incoming REGISTER request */
21781 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e)
21782 {
21783    enum check_auth_result res;
21784 
21785    /* If this is not the intial request, and the initial request isn't
21786     * a register, something screwy happened, so bail */
21787    if (p->initreq.headers && p->initreq.method != SIP_REGISTER) {
21788       ast_log(LOG_WARNING, "Ignoring spurious REGISTER with Call-ID: %s\n", p->callid);
21789       return -1;
21790    }
21791 
21792    /* Use this as the basis */
21793    copy_request(&p->initreq, req);
21794    if (sipdebug)
21795       ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
21796    check_via(p, req);
21797    if ((res = register_verify(p, sin, req, e)) < 0) {
21798       const char *reason;
21799 
21800       switch (res) {
21801       case AUTH_SECRET_FAILED:
21802          reason = "Wrong password";
21803          break;
21804       case AUTH_USERNAME_MISMATCH:
21805          reason = "Username/auth name mismatch";
21806          break;
21807       case AUTH_NOT_FOUND:
21808          reason = "No matching peer found";
21809          break;
21810       case AUTH_UNKNOWN_DOMAIN:
21811          reason = "Not a local domain";
21812          break;
21813       case AUTH_PEER_NOT_DYNAMIC:
21814          reason = "Peer is not supposed to register";
21815          break;
21816       case AUTH_ACL_FAILED:
21817          reason = "Device does not match ACL";
21818          break;
21819       case AUTH_BAD_TRANSPORT:
21820          reason = "Device not configured to use this transport type";
21821          break;
21822       default:
21823          reason = "Unknown failure";
21824          break;
21825       }
21826       ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
21827          get_header(req, "To"), ast_inet_ntoa(sin->sin_addr),
21828          reason);
21829       append_history(p, "RegRequest", "Failed : Account %s : %s", get_header(req, "To"), reason);
21830    } else
21831       append_history(p, "RegRequest", "Succeeded : Account %s", get_header(req, "To"));
21832 
21833    if (res < 1) {
21834       /* Destroy the session, but keep us around for just a bit in case they don't
21835          get our 200 OK */
21836       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21837    }
21838    return res;
21839 }
21840 
21841 /*!
21842  * \brief Handle incoming SIP requests (methods)
21843  * \note
21844  * This is where all incoming requests go first.
21845  * \note
21846  * called with p and p->owner locked
21847  */
21848 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock)
21849 {
21850    /* Called with p->lock held, as well as p->owner->lock if appropriate, keeping things
21851       relatively static */
21852    const char *cmd;
21853    const char *cseq;
21854    const char *useragent;
21855    const char *via;
21856    const char *callid;
21857    int via_pos = 0;
21858    int seqno;
21859    int len;
21860    int respid;
21861    int res = 0;
21862    int debug = sip_debug_test_pvt(p);
21863    char *e;
21864    int error = 0;
21865    int oldmethod = p->method;
21866    int acked = 0;
21867 
21868    /* RFC 3261 - 8.1.1 A valid SIP request must contain To, From, CSeq, Call-ID and Via.
21869     * 8.2.6.2 Response must have To, From, Call-ID CSeq, and Via related to the request,
21870     * so we can check to make sure these fields exist for all requests and responses */
21871    cseq = get_header(req, "Cseq");
21872    cmd = REQ_OFFSET_TO_STR(req, header[0]);
21873    /* Save the via_pos so we can check later that responses only have 1 Via header */
21874    via = __get_header(req, "Via", &via_pos);
21875    /* This must exist already because we've called find_call by now */
21876    callid = get_header(req, "Call-ID");
21877 
21878    /* Must have Cseq */
21879    if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq) || ast_strlen_zero(via)) {
21880       ast_log(LOG_ERROR, "Dropping this SIP message with Call-ID '%s', it's incomplete.\n", callid);
21881       error = 1;
21882    }
21883    if (!error && sscanf(cseq, "%30d%n", &seqno, &len) != 1) {
21884       ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
21885       error = 1;
21886    }
21887    if (error) {
21888       if (!p->initreq.headers) { /* New call */
21889          pvt_set_needdestroy(p, "no headers");
21890       }
21891       return -1;
21892    }
21893    /* Get the command XXX */
21894 
21895    cmd = REQ_OFFSET_TO_STR(req, rlPart1);
21896    e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlPart2));
21897 
21898    /* Save useragent of the client */
21899    useragent = get_header(req, "User-Agent");
21900    if (!ast_strlen_zero(useragent))
21901       ast_string_field_set(p, useragent, useragent);
21902 
21903    /* Find out SIP method for incoming request */
21904    if (req->method == SIP_RESPONSE) {  /* Response to our request */
21905       /* ignore means "don't do anything with it" but still have to 
21906        * respond appropriately.
21907        * But in this case this is a response already, so we really
21908        * have nothing to do with this message, and even setting the
21909        * ignore flag is pointless.
21910        */
21911       if (ast_strlen_zero(e)) {
21912          return 0;
21913       }
21914       if (sscanf(e, "%30d %n", &respid, &len) != 1) {
21915          ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
21916          return 0;
21917       }
21918       if (respid <= 0) {
21919          ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
21920          return 0;
21921       }
21922       /* RFC 3261 - 8.1.3.3 If more than one Via header field value is present in a reponse
21923        * the UAC SHOULD discard the message. This is not perfect, as it will not catch multiple
21924        * headers joined with a comma. Fixing that would pretty much involve writing a new parser */
21925       if (!ast_strlen_zero(__get_header(req, "via", &via_pos))) {
21926          ast_log(LOG_WARNING, "Misrouted SIP response '%s' with Call-ID '%s', too many vias\n", e, callid);
21927          return 0;
21928       }
21929       if (p->ocseq && (p->ocseq < seqno)) {
21930          if (option_debug)
21931             ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
21932          return -1;
21933       } else {
21934          if ((respid == 200) || ((respid >= 300) && (respid <= 399))) {
21935             extract_uri(p, req);
21936          }
21937          handle_response(p, respid, e + len, req, seqno);
21938       }
21939       return 0;
21940    }
21941 
21942    /* New SIP request coming in 
21943       (could be new request in existing SIP dialog as well...) 
21944     */         
21945    
21946    p->method = req->method;   /* Find out which SIP method they are using */
21947    ast_debug(4, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd); 
21948 
21949    if (p->icseq && (p->icseq > seqno) ) {
21950       if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
21951          ast_debug(2, "Got CANCEL or ACK on INVITE with transactions in between.\n");
21952       }  else {
21953          ast_debug(1, "Ignoring too old SIP packet packet %d (expecting >= %d)\n", seqno, p->icseq);
21954          if (req->method != SIP_ACK)
21955             transmit_response(p, "500 Server error", req);  /* We must respond according to RFC 3261 sec 12.2 */
21956          return -1;
21957       }
21958    } else if (p->icseq &&
21959          p->icseq == seqno &&
21960          req->method != SIP_ACK &&
21961          (p->method != SIP_CANCEL || p->alreadygone)) {
21962       /* ignore means "don't do anything with it" but still have to 
21963          respond appropriately.  We do this if we receive a repeat of
21964          the last sequence number  */
21965       req->ignore = 1;
21966       ast_debug(3, "Ignoring SIP message because of retransmit (%s Seqno %d, ours %d)\n", sip_methods[p->method].text, p->icseq, seqno);
21967    }
21968       
21969    if (seqno >= p->icseq)
21970       /* Next should follow monotonically (but not necessarily 
21971          incrementally -- thanks again to the genius authors of SIP --
21972          increasing */
21973       p->icseq = seqno;
21974 
21975    /* Find their tag if we haven't got it */
21976    if (ast_strlen_zero(p->theirtag)) {
21977       char tag[128];
21978 
21979       gettag(req, "From", tag, sizeof(tag));
21980       ast_string_field_set(p, theirtag, tag);
21981    }
21982    snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
21983 
21984    if (sip_cfg.pedanticsipchecking) {
21985       /* If this is a request packet without a from tag, it's not
21986          correct according to RFC 3261  */
21987       /* Check if this a new request in a new dialog with a totag already attached to it,
21988          RFC 3261 - section 12.2 - and we don't want to mess with recovery  */
21989       if (!p->initreq.headers && req->has_to_tag) {
21990          /* If this is a first request and it got a to-tag, it is not for us */
21991          if (!req->ignore && req->method == SIP_INVITE) {
21992             transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
21993             /* Will cease to exist after ACK */
21994          } else if (req->method != SIP_ACK) {
21995             transmit_response(p, "481 Call/Transaction Does Not Exist", req);
21996             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21997          } else {
21998             ast_debug(1, "Got ACK for unknown dialog... strange.\n");
21999          }
22000          return res;
22001       }
22002    }
22003 
22004    if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY)) {
22005       transmit_response(p, "400 Bad request", req);
22006       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22007       return -1;
22008    }
22009 
22010    /* Handle various incoming SIP methods in requests */
22011    switch (p->method) {
22012    case SIP_OPTIONS:
22013       res = handle_request_options(p, req);
22014       break;
22015    case SIP_INVITE:
22016       res = handle_request_invite(p, req, debug, seqno, sin, recount, e, nounlock);
22017       break;
22018    case SIP_REFER:
22019       res = handle_request_refer(p, req, debug, seqno, nounlock);
22020       break;
22021    case SIP_CANCEL:
22022       res = handle_request_cancel(p, req);
22023       break;
22024    case SIP_BYE:
22025       res = handle_request_bye(p, req);
22026       break;
22027    case SIP_MESSAGE:
22028       res = handle_request_message(p, req);
22029       break;
22030    case SIP_SUBSCRIBE:
22031       res = handle_request_subscribe(p, req, sin, seqno, e);
22032       break;
22033    case SIP_REGISTER:
22034       res = handle_request_register(p, req, sin, e);
22035       break;
22036    case SIP_INFO:
22037       if (req->debug)
22038          ast_verbose("Receiving INFO!\n");
22039       if (!req->ignore) 
22040          handle_request_info(p, req);
22041       else  /* if ignoring, transmit response */
22042          transmit_response(p, "200 OK", req);
22043       break;
22044    case SIP_NOTIFY:
22045       res = handle_request_notify(p, req, sin, seqno, e);
22046       break;
22047    case SIP_ACK:
22048       /* Make sure we don't ignore this */
22049       if (seqno == p->pendinginvite) {
22050          p->invitestate = INV_TERMINATED;
22051          p->pendinginvite = 0;
22052          acked = __sip_ack(p, seqno, 1 /* response */, 0);
22053          if (find_sdp(req)) {
22054             if (process_sdp(p, req, SDP_T38_NONE))
22055                return -1;
22056          }
22057          check_pendings(p);
22058       } else if (p->glareinvite == seqno) {
22059          /* handle ack for the 491 pending sent for glareinvite */
22060          p->glareinvite = 0;
22061          acked = __sip_ack(p, seqno, 1, 0);
22062       }
22063       if (!acked) {
22064          /* Got an ACK that did not match anything. Ignore
22065           * silently and restore previous method */
22066          p->method = oldmethod;
22067       }
22068       if (!p->lastinvite && ast_strlen_zero(p->randdata)) {
22069          pvt_set_needdestroy(p, "unmatched ACK");
22070       }
22071       break;
22072    default:
22073       transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
22074       ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n", 
22075          cmd, ast_inet_ntoa(p->sa.sin_addr));
22076       /* If this is some new method, and we don't have a call, destroy it now */
22077       if (!p->initreq.headers) {
22078          pvt_set_needdestroy(p, "unimplemented method");
22079       }
22080       break;
22081    }
22082    return res;
22083 }
22084 
22085 static void process_request_queue(struct sip_pvt *p, int *recount, int *nounlock)
22086 {
22087    struct sip_request *req;
22088 
22089    while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
22090       if (handle_incoming(p, req, &p->recv, recount, nounlock) == -1) {
22091          /* Request failed */
22092          if (option_debug) {
22093             ast_log(LOG_DEBUG, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
22094          }
22095       }
22096       ast_free(req);
22097    }
22098 }
22099 
22100 static int scheduler_process_request_queue(const void *data)
22101 {
22102    struct sip_pvt *p = (struct sip_pvt *) data;
22103    int recount = 0;
22104    int nounlock = 0;
22105    int lockretry;
22106 
22107    for (lockretry = 10; lockretry > 0; lockretry--) {
22108       sip_pvt_lock(p);
22109 
22110       /* lock the owner if it has one -- we may need it */
22111       /* because this is deadlock-prone, we need to try and unlock if failed */
22112       if (!p->owner || !ast_channel_trylock(p->owner)) {
22113          break;   /* locking succeeded */
22114       }
22115 
22116       if (lockretry != 1) {
22117          sip_pvt_unlock(p);
22118          /* Sleep for a very short amount of time */
22119          usleep(1);
22120       }
22121    }
22122 
22123    if (!lockretry) {
22124       int retry = !AST_LIST_EMPTY(&p->request_queue);
22125 
22126       /* we couldn't get the owner lock, which is needed to process
22127          the queued requests, so return a non-zero value, which will
22128          cause the scheduler to run this request again later if there
22129          still requests to be processed
22130       */
22131       sip_pvt_unlock(p);
22132       if (!retry) {
22133          dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
22134       }
22135       return retry;
22136    };
22137 
22138    process_request_queue(p, &recount, &nounlock);
22139    p->request_queue_sched_id = -1;
22140 
22141    if (p->owner && !nounlock) {
22142       ast_channel_unlock(p->owner);
22143    }
22144    sip_pvt_unlock(p);
22145 
22146    if (recount) {
22147       ast_update_use_count();
22148    }
22149 
22150    dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
22151 
22152    return 0;
22153 }
22154 
22155 static int queue_request(struct sip_pvt *p, const struct sip_request *req)
22156 {
22157    struct sip_request *newreq;
22158 
22159    if (!(newreq = ast_calloc(1, sizeof(*newreq)))) {
22160       return -1;
22161    }
22162 
22163    copy_request(newreq, req);
22164    AST_LIST_INSERT_TAIL(&p->request_queue, newreq, next);
22165    if (p->request_queue_sched_id == -1) {
22166       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) {
22167          dialog_unref(p, "Decrement refcount due to sched_add failure");
22168       }
22169    }
22170 
22171    return 0;
22172 }
22173 
22174 /*! \brief Read data from SIP UDP socket
22175 \note sipsock_read locks the owner channel while we are processing the SIP message
22176 \return 1 on error, 0 on success
22177 \note Successful messages is connected to SIP call and forwarded to handle_incoming() 
22178 */
22179 static int sipsock_read(int *id, int fd, short events, void *ignore)
22180 {
22181    struct sip_request req;
22182    struct sockaddr_in sin = { 0, };
22183    int res;
22184    socklen_t len = sizeof(sin);
22185    static char readbuf[65535];
22186 
22187    memset(&req, 0, sizeof(req));
22188    res = recvfrom(fd, readbuf, sizeof(readbuf) - 1, 0, (struct sockaddr *)&sin, &len);
22189    if (res < 0) {
22190 #if !defined(__FreeBSD__)
22191       if (errno == EAGAIN)
22192          ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
22193       else 
22194 #endif
22195       if (errno != ECONNREFUSED)
22196          ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
22197       return 1;
22198    }
22199 
22200    readbuf[res] = '\0';
22201 
22202    if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
22203       return 1;
22204    }
22205 
22206    if (ast_str_set(&req.data, 0, "%s", readbuf) == AST_DYNSTR_BUILD_FAILED) {
22207       return -1;
22208    }
22209 
22210    req.len = res;
22211    req.socket.fd = sipsock;
22212    set_socket_transport(&req.socket, SIP_TRANSPORT_UDP);
22213    req.socket.tcptls_session  = NULL;
22214    req.socket.port = bindaddr.sin_port;
22215 
22216    handle_request_do(&req, &sin);
22217    deinit_req(&req);
22218 
22219    return 1;
22220 }
22221 
22222 /*! \brief Handle incoming SIP message - request or response 
22223 
22224    This is used for all transports (udp, tcp and tcp/tls)
22225 */
22226 static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin) 
22227 {
22228    struct sip_pvt *p;
22229    int recount = 0;
22230    int nounlock = 0;
22231    int lockretry;
22232 
22233    if (sip_debug_test_addr(sin)) /* Set the debug flag early on packet level */
22234       req->debug = 1;
22235    if (sip_cfg.pedanticsipchecking)
22236       req->len = lws2sws(req->data->str, req->len);   /* Fix multiline headers */
22237    if (req->debug) {
22238       ast_verbose("\n<--- SIP read from %s:%s:%d --->\n%s\n<------------->\n", 
22239          get_transport(req->socket.type), ast_inet_ntoa(sin->sin_addr), 
22240          ntohs(sin->sin_port), req->data->str);
22241    }
22242 
22243    if (parse_request(req) == -1) { /* Bad packet, can't parse */
22244       ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
22245       return 1;
22246    }
22247    req->method = find_sip_method(REQ_OFFSET_TO_STR(req, rlPart1));
22248 
22249    if (req->debug)
22250       ast_verbose("--- (%d headers %d lines)%s ---\n", req->headers, req->lines, (req->headers + req->lines == 0) ? " Nat keepalive" : "");
22251 
22252    if (req->headers < 2) { /* Must have at least two headers */
22253       ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
22254       return 1;
22255    }
22256 
22257    /* Process request, with netlock held, and with usual deadlock avoidance */
22258    for (lockretry = 10; lockretry > 0; lockretry--) {
22259       ast_mutex_lock(&netlock);
22260 
22261       /* Find the active SIP dialog or create a new one */
22262       p = find_call(req, sin, req->method);  /* returns p locked */
22263       if (p == NULL) {
22264          ast_debug(1, "Invalid SIP message - rejected , no callid, len %d\n", req->len);
22265          ast_mutex_unlock(&netlock);
22266          return 1;
22267       }
22268 
22269       copy_socket_data(&p->socket, &req->socket);
22270 
22271       /* Go ahead and lock the owner if it has one -- we may need it */
22272       /* becaues this is deadlock-prone, we need to try and unlock if failed */
22273       if (!p->owner || !ast_channel_trylock(p->owner))
22274          break;   /* locking succeeded */
22275 
22276       if (lockretry != 1) {
22277          sip_pvt_unlock(p);
22278          ao2_t_ref(p, -1, "release p (from find_call) inside lockretry loop"); /* we'll look for it again, but p is dead now */
22279          ast_mutex_unlock(&netlock);
22280          /* Sleep for a very short amount of time */
22281          usleep(1);
22282       }
22283    }
22284    p->recv = *sin;
22285 
22286    if (p->do_history) /* This is a request or response, note what it was for */
22287       append_history(p, "Rx", "%s / %s / %s", req->data->str, get_header(req, "CSeq"), REQ_OFFSET_TO_STR(req, rlPart2));
22288 
22289    if (!lockretry) {
22290       if (!queue_request(p, req)) {
22291          /* the request has been queued for later handling */
22292          sip_pvt_unlock(p);
22293          ao2_t_ref(p, -1, "release p (from find_call) after queueing request");
22294          ast_mutex_unlock(&netlock);
22295          return 1;
22296       }
22297 
22298       if (p->owner)
22299          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 ??? - "));
22300       ast_log(LOG_ERROR, "SIP transaction failed: %s \n", p->callid);
22301       if (req->method != SIP_ACK)
22302          transmit_response(p, "503 Server error", req);  /* We must respond according to RFC 3261 sec 12.2 */
22303       /* XXX We could add retry-after to make sure they come back */
22304       append_history(p, "LockFail", "Owner lock failed, transaction failed.");
22305       sip_pvt_unlock(p);
22306       ao2_t_ref(p, -1, "release p (from find_call) at end of lockretry"); /* p is gone after the return */
22307       ast_mutex_unlock(&netlock);
22308       return 1;
22309    }
22310 
22311    /* if there are queued requests on this sip_pvt, process them first, so that everything is
22312       handled in order
22313    */
22314    if (!AST_LIST_EMPTY(&p->request_queue)) {
22315       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"));
22316       process_request_queue(p, &recount, &nounlock);
22317    }
22318 
22319    if (handle_incoming(p, req, sin, &recount, &nounlock) == -1) {
22320       /* Request failed */
22321       ast_debug(1, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
22322    }
22323       
22324    if (recount)
22325       ast_update_use_count();
22326 
22327    if (p->owner && !nounlock)
22328       ast_channel_unlock(p->owner);
22329    sip_pvt_unlock(p);
22330    ao2_t_ref(p, -1, "throw away dialog ptr from find_call at end of routine"); /* p is gone after the return */
22331    ast_mutex_unlock(&netlock);
22332    return 1;
22333 }
22334 
22335 /*! \brief Returns the port to use for this socket
22336  *
22337  * \param type The type of transport used
22338  * \param port Port we are checking to see if it's the standard port.
22339  * \note port is expected in host byte order
22340  */
22341 static int sip_standard_port(enum sip_transport type, int port)
22342 {
22343    if (type & SIP_TRANSPORT_TLS)
22344       return port == STANDARD_TLS_PORT;
22345    else
22346       return port == STANDARD_SIP_PORT;
22347 }
22348 
22349 static int threadinfo_locate_cb(void *obj, void *arg, int flags)
22350 {
22351    struct sip_threadinfo *th = obj;
22352    struct sockaddr_in *s = arg;
22353 
22354    if (!inaddrcmp(&th->tcptls_session->remote_address, s)) {
22355       return CMP_MATCH | CMP_STOP;
22356    }
22357 
22358    return 0;
22359 }
22360 
22361 /*! 
22362  * \brief Find thread for TCP/TLS session (based on IP/Port 
22363  *
22364  * \note This function returns an astobj2 reference
22365  */
22366 static struct ast_tcptls_session_instance *sip_tcp_locate(struct sockaddr_in *s)
22367 {
22368    struct sip_threadinfo *th;
22369    struct ast_tcptls_session_instance *tcptls_instance = NULL;
22370 
22371    if ((th = ao2_callback(threadt, 0, threadinfo_locate_cb, s))) {
22372       tcptls_instance = (ao2_ref(th->tcptls_session, +1), th->tcptls_session);
22373       ao2_t_ref(th, -1, "decrement ref from callback");
22374    }
22375    return tcptls_instance;
22376 }
22377 
22378 /*! \todo Get socket for dialog, prepare if needed, and return file handle  */
22379 static int sip_prepare_socket(struct sip_pvt *p) 
22380 {
22381    struct sip_socket *s = &p->socket;
22382    static const char name[] = "SIP socket";
22383    struct sip_threadinfo *th = NULL;
22384    struct ast_tcptls_session_instance *tcptls_session;
22385    struct ast_tcptls_session_args tmp_ca = {
22386       .name = name,
22387       .accept_fd = -1,
22388    };
22389    struct ast_tcptls_session_args *ca;
22390 
22391    /* check to see if a socket is already active */
22392    if ((s->fd != -1) && (s->type == SIP_TRANSPORT_UDP)) {
22393       return s->fd;
22394    }
22395    if ((s->type & (SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS)) &&
22396          (s->tcptls_session) &&
22397          (s->tcptls_session->fd != -1)) {
22398       return s->tcptls_session->fd;
22399    }
22400 
22401    /*! \todo Check this... This might be wrong, depending on the proxy configuration
22402       If proxy is in "force" mode its correct.
22403     */
22404    if (p->outboundproxy && p->outboundproxy->transport) {
22405       s->type = p->outboundproxy->transport;
22406    }
22407 
22408    if (s->type == SIP_TRANSPORT_UDP) {
22409       s->fd = sipsock;
22410       return s->fd;
22411    }
22412 
22413    /* At this point we are dealing with a TCP/TLS connection
22414     * 1. We need to check to see if a connectin thread exists
22415     *    for this address, if so use that.
22416     * 2. If a thread does not exist for this address, but the tcptls_session
22417     *    exists on the socket, the connection was closed.
22418     * 3. If no tcptls_session thread exists for the address, and no tcptls_session
22419     *    already exists on the socket, create a new one and launch a new thread.
22420     */
22421 
22422    /* 1.  check for existing threads */
22423    tmp_ca.remote_address = *(sip_real_dst(p));
22424    if ((tcptls_session = sip_tcp_locate(&tmp_ca.remote_address))) {
22425       s->fd = tcptls_session->fd;
22426       if (s->tcptls_session) {
22427          ao2_ref(s->tcptls_session, -1);
22428          s->tcptls_session = NULL;
22429       }
22430       s->tcptls_session = tcptls_session;
22431       return s->fd;
22432    /* 2.  Thread not found, if tcptls_session already exists, it once had a thread and is now terminated */
22433    } else if (s->tcptls_session) {
22434       return s->fd; /* XXX whether reconnection is ever necessary here needs to be investigated further */
22435    }
22436 
22437    /* 3.  Create a new TCP/TLS client connection */
22438    /* create new session arguments for the client connection */
22439    if (!(ca = ao2_alloc(sizeof(*ca), sip_tcptls_client_args_destructor)) ||
22440       !(ca->name = ast_strdup(name))) {
22441       goto create_tcptls_session_fail;
22442    }
22443    ca->accept_fd = -1;
22444    ca->remote_address = *(sip_real_dst(p));
22445    /* if type is TLS, we need to create a tls cfg for this session arg */
22446    if (s->type == SIP_TRANSPORT_TLS) {
22447       if (!(ca->tls_cfg = ast_calloc(1, sizeof(*ca->tls_cfg)))) {
22448          goto create_tcptls_session_fail;
22449       }
22450       memcpy(ca->tls_cfg, &default_tls_cfg, sizeof(*ca->tls_cfg));
22451 
22452       if (!(ca->tls_cfg->certfile = ast_strdup(default_tls_cfg.certfile)) ||
22453          !(ca->tls_cfg->cipher = ast_strdup(default_tls_cfg.cipher)) ||
22454          !(ca->tls_cfg->cafile = ast_strdup(default_tls_cfg.cafile)) ||
22455          !(ca->tls_cfg->capath = ast_strdup(default_tls_cfg.capath))) {
22456 
22457          goto create_tcptls_session_fail;
22458       }
22459 
22460       /* this host is used as the common name in ssl/tls */
22461       if (!ast_strlen_zero(p->tohost)) {
22462          ast_copy_string(ca->hostname, p->tohost, sizeof(ca->hostname));
22463       }
22464    }
22465    /* Create a client connection for address, this does not start the connection, just sets it up. */
22466    if (!(s->tcptls_session = ast_tcptls_client_create(ca))) {
22467       goto create_tcptls_session_fail;
22468    }
22469 
22470    s->fd = s->tcptls_session->fd;
22471 
22472    /* client connections need to have the sip_threadinfo object created before
22473     * the thread is detached.  This ensures the alert_pipe is up before it will
22474     * be used.  Note that this function links the new threadinfo object into the
22475     * threadt container. */
22476    if (!(th = sip_threadinfo_create(s->tcptls_session, s->type))) {
22477       goto create_tcptls_session_fail;
22478 
22479    }
22480 
22481    /* Give the new thread a reference to the tcptls_session */
22482    ao2_ref(s->tcptls_session, +1);
22483 
22484    if (ast_pthread_create_background(&ca->master, NULL, sip_tcp_worker_fn, s->tcptls_session)) {
22485       ast_debug(1, "Unable to launch '%s'.", ca->name);
22486       ao2_ref(s->tcptls_session, -1); /* take away the thread ref we just gave it */
22487       goto create_tcptls_session_fail;
22488    }
22489 
22490    return s->fd;
22491 
22492 create_tcptls_session_fail:
22493    if (ca) {
22494       ao2_t_ref(ca, -1, "failed to create client, getting rid of client tcptls_session arguments");
22495    }
22496    if (s->tcptls_session) {
22497       close(tcptls_session->fd);
22498       s->fd = tcptls_session->fd = -1;
22499       ao2_ref(s->tcptls_session, -1);
22500       s->tcptls_session = NULL;
22501    }
22502    if (th) {
22503       ao2_t_unlink(threadt, th, "Removing tcptls thread info object, thread failed to open");
22504    }
22505 
22506    return -1;
22507 }
22508 
22509 /*!
22510  * \brief Small function to parse a config line for a host with a transport
22511  *        i.e. tls://www.google.com:8056
22512  */
22513 static int sip_parse_host(char *line, int lineno, char **hostname, int *portnum, enum sip_transport *transport)
22514 {
22515    char *port;
22516 
22517    if ((*hostname = strstr(line, "://"))) {
22518       *hostname += 3;
22519 
22520       if (!strncasecmp(line, "tcp", 3))
22521          *transport = SIP_TRANSPORT_TCP;
22522       else if (!strncasecmp(line, "tls", 3))
22523          *transport = SIP_TRANSPORT_TLS;
22524       else if (!strncasecmp(line, "udp", 3))
22525          *transport = SIP_TRANSPORT_UDP;
22526       else
22527          ast_log(LOG_NOTICE, "'%.3s' is not a valid transport type on line %d of sip.conf. defaulting to udp.\n", line, lineno);
22528    } else {
22529       *hostname = line;
22530       *transport = SIP_TRANSPORT_UDP;
22531    }
22532 
22533    if ((line = strrchr(*hostname, '@')))
22534       line++;
22535    else
22536       line = *hostname;
22537 
22538    if ((port = strrchr(line, ':'))) {
22539       *port++ = '\0';
22540 
22541       if (!sscanf(port, "%5u", portnum)) {
22542          ast_log(LOG_NOTICE, "'%s' is not a valid port number on line %d of sip.conf. using default.\n", port, lineno);
22543          port = NULL;
22544       }
22545    }
22546 
22547    if (!port) {
22548       if (*transport & SIP_TRANSPORT_TLS) {
22549          *portnum = STANDARD_TLS_PORT;
22550       } else {
22551          *portnum = STANDARD_SIP_PORT;
22552       }
22553    }
22554 
22555    return 0;
22556 }
22557 
22558 /*!
22559  * \brief Get cached MWI info
22560  * \retval 0 At least one message is waiting
22561  * \retval 1 no messages waiting
22562  */
22563 static int get_cached_mwi(struct sip_peer *peer, int *new, int *old)
22564 {
22565    struct sip_mailbox *mailbox;
22566 
22567    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
22568       struct ast_event *event;
22569       event = ast_event_get_cached(AST_EVENT_MWI,
22570          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
22571          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
22572          AST_EVENT_IE_END);
22573       if (!event)
22574          continue;
22575       *new += ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
22576       *old += ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
22577       ast_event_destroy(event);
22578    }
22579 
22580    return (*new || *old) ? 0 : 1;
22581 }
22582 
22583 /*! \brief Send message waiting indication to alert peer that they've got voicemail */
22584 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only)
22585 {
22586    /* Called with peerl lock, but releases it */
22587    struct sip_pvt *p;
22588    int newmsgs = 0, oldmsgs = 0;
22589 
22590    if (ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY) && !peer->mwipvt)
22591       return 0;
22592 
22593    /* Do we have an IP address? If not, skip this peer */
22594    if (!peer->addr.sin_addr.s_addr && !peer->defaddr.sin_addr.s_addr) 
22595       return 0;
22596 
22597    if (event) {
22598       newmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
22599       oldmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
22600    } else if (!cache_only) { /* Fall back to manually checking the mailbox */
22601       struct ast_str *mailbox_str = ast_str_alloca(512);
22602       peer_mailboxes_to_str(&mailbox_str, peer);
22603       ast_app_inboxcount(mailbox_str->str, &newmsgs, &oldmsgs);
22604    } else {
22605       get_cached_mwi(peer, &newmsgs, &oldmsgs);
22606    }
22607    
22608    if (peer->mwipvt) {
22609       /* Base message on subscription */
22610       p = dialog_ref(peer->mwipvt, "sip_send_mwi_to_peer: Setting dialog ptr p from peer->mwipvt-- should this be done?");
22611    } else {
22612       /* Build temporary dialog for this message */
22613       if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) 
22614          return -1;
22615       /* If we don't set the socket type to 0, then create_addr_from_peer will fail immediately if the peer
22616        * uses any transport other than UDP. We set the type to 0 here and then let create_addr_from_peer copy 
22617        * the peer's socket information to the sip_pvt we just allocated
22618        */
22619       set_socket_transport(&p->socket, 0);
22620       if (create_addr_from_peer(p, peer)) {
22621          /* Maybe they're not registered, etc. */
22622          dialog_unlink_all(p, TRUE, TRUE);
22623          dialog_unref(p, "unref dialog p just created via sip_alloc");
22624          /* sip_destroy(p); */
22625          return 0;
22626       }
22627       /* Recalculate our side, and recalculate Call ID */
22628       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
22629       build_via(p);
22630       ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
22631       build_callid_pvt(p);
22632       ao2_t_link(dialogs, p, "Linking in under new name");
22633       /* Destroy this session after 32 secs */
22634       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22635    }
22636 
22637    /* Send MWI */
22638    ast_set_flag(&p->flags[0], SIP_OUTGOING);
22639    /* the following will decrement the refcount on p as it finishes */
22640    transmit_notify_with_mwi(p, newmsgs, oldmsgs, peer->vmexten);
22641    dialog_unref(p, "unref dialog ptr p just before it goes out of scope at the end of sip_send_mwi_to_peer.");
22642    return 0;
22643 }
22644 
22645 /*! \brief helper function for the monitoring thread -- seems to be called with the assumption that the dialog is locked */
22646 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t)
22647 {
22648    /* If we have no RTP or no active owner, no need to check timers */
22649    if (!dialog->rtp || !dialog->owner)
22650       return;
22651    /* If the call is not in UP state or redirected outside Asterisk, no need to check timers */
22652 
22653    if (dialog->owner->_state != AST_STATE_UP || dialog->redirip.sin_addr.s_addr)
22654       return;
22655 
22656    /* If the call is involved in a T38 fax session do not check RTP timeout */
22657    if (dialog->t38.state == T38_ENABLED)
22658       return;
22659 
22660    /* If we have no timers set, return now */
22661    if ((ast_rtp_get_rtpkeepalive(dialog->rtp) == 0) && (ast_rtp_get_rtptimeout(dialog->rtp) == 0) && (ast_rtp_get_rtpholdtimeout(dialog->rtp) == 0))
22662       return;
22663 
22664    /* Check AUDIO RTP keepalives */
22665    if (dialog->lastrtptx && ast_rtp_get_rtpkeepalive(dialog->rtp) &&
22666           (t > dialog->lastrtptx + ast_rtp_get_rtpkeepalive(dialog->rtp))) {
22667       /* Need to send an empty RTP packet */
22668       dialog->lastrtptx = time(NULL);
22669       ast_rtp_sendcng(dialog->rtp, 0);
22670    }
22671 
22672    /*! \todo Check video RTP keepalives
22673 
22674       Do we need to move the lastrtptx to the RTP structure to have one for audio and one
22675       for video? It really does belong to the RTP structure.
22676    */
22677 
22678    /* Check AUDIO RTP timers */
22679    if (dialog->lastrtprx && (ast_rtp_get_rtptimeout(dialog->rtp) || ast_rtp_get_rtpholdtimeout(dialog->rtp)) &&
22680           (t > dialog->lastrtprx + ast_rtp_get_rtptimeout(dialog->rtp))) {
22681 
22682       /* Might be a timeout now -- see if we're on hold */
22683       struct sockaddr_in sin;
22684       ast_rtp_get_peer(dialog->rtp, &sin);
22685       if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD) || (ast_rtp_get_rtpholdtimeout(dialog->rtp) &&
22686            (t > dialog->lastrtprx + ast_rtp_get_rtpholdtimeout(dialog->rtp)))) {
22687          /* Needs a hangup */
22688          if (ast_rtp_get_rtptimeout(dialog->rtp)) {
22689             while (dialog->owner && ast_channel_trylock(dialog->owner)) {
22690                sip_pvt_unlock(dialog);
22691                usleep(1);
22692                sip_pvt_lock(dialog);
22693             }
22694             if (!dialog->owner) {
22695                return; /* channel hangup can occur during deadlock avoidance. */
22696             }
22697             ast_log(LOG_NOTICE, "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
22698                dialog->owner->name, (long) (t - dialog->lastrtprx));
22699             /* Issue a softhangup */
22700             ast_softhangup_nolock(dialog->owner, AST_SOFTHANGUP_DEV);
22701             ast_channel_unlock(dialog->owner);
22702             /* forget the timeouts for this call, since a hangup
22703                has already been requested and we don't want to
22704                repeatedly request hangups
22705             */
22706             ast_rtp_set_rtptimeout(dialog->rtp, 0);
22707             ast_rtp_set_rtpholdtimeout(dialog->rtp, 0);
22708             if (dialog->vrtp) {
22709                ast_rtp_set_rtptimeout(dialog->vrtp, 0);
22710                ast_rtp_set_rtpholdtimeout(dialog->vrtp, 0);
22711             }
22712          }
22713       }
22714    }
22715 }
22716 
22717 /*! \brief The SIP monitoring thread 
22718 \note This thread monitors all the SIP sessions and peers that needs notification of mwi
22719    (and thus do not have a separate thread) indefinitely 
22720 */
22721 static void *do_monitor(void *data)
22722 {
22723    int res;
22724    time_t t;
22725    int reloading;
22726 
22727    /* Add an I/O event to our SIP UDP socket */
22728    if (sipsock > -1) 
22729       sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
22730 
22731    /* From here on out, we die whenever asked */
22732    for(;;) {
22733       /* Check for a reload request */
22734       ast_mutex_lock(&sip_reload_lock);
22735       reloading = sip_reloading;
22736       sip_reloading = FALSE;
22737       ast_mutex_unlock(&sip_reload_lock);
22738       if (reloading) {
22739          ast_verb(1, "Reloading SIP\n");
22740          sip_do_reload(sip_reloadreason);
22741 
22742          /* Change the I/O fd of our UDP socket */
22743          if (sipsock > -1) {
22744             if (sipsock_read_id)
22745                sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
22746             else
22747                sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
22748          } else if (sipsock_read_id) {
22749             ast_io_remove(io, sipsock_read_id);
22750             sipsock_read_id = NULL;
22751          }
22752       }
22753 
22754       /* Check for dialogs needing to be killed */
22755       t = time(NULL);
22756       /* don't scan the dialogs list if it hasn't been a reasonable period
22757          of time since the last time we did it (when MWI is being sent, we can
22758          get back to this point every millisecond or less)
22759       */
22760       ao2_t_callback(dialogs, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, dialog_needdestroy, &t,
22761             "callback to remove dialogs w/needdestroy");
22762 
22763       /* the old methodology would be to restart the search for dialogs to delete with every 
22764          dialog that was found and destroyed, probably because the list contents would change,
22765          so we'd need to restart. This isn't the best thing to do with callbacks. */
22766 
22767       /* XXX TODO The scheduler usage in this module does not have sufficient 
22768        * synchronization being done between running the scheduler and places 
22769        * scheduling tasks.  As it is written, any scheduled item may not run 
22770        * any sooner than about  1 second, regardless of whether a sooner time 
22771        * was asked for. */
22772 
22773       pthread_testcancel();
22774       /* Wait for sched or io */
22775       res = ast_sched_wait(sched);
22776       if ((res < 0) || (res > 1000))
22777          res = 1000;
22778       res = ast_io_wait(io, res);
22779       if (res > 20)
22780          ast_debug(1, "chan_sip: ast_io_wait ran %d all at once\n", res);
22781       ast_mutex_lock(&monlock);
22782       res = ast_sched_runq(sched);
22783       if (res >= 20)
22784          ast_debug(1, "chan_sip: ast_sched_runq ran %d all at once\n", res);
22785       ast_mutex_unlock(&monlock);
22786    }
22787 
22788    /* Never reached */
22789    return NULL;
22790 }
22791 
22792 /*! \brief Start the channel monitor thread */
22793 static int restart_monitor(void)
22794 {
22795    /* If we're supposed to be stopped -- stay stopped */
22796    if (monitor_thread == AST_PTHREADT_STOP)
22797       return 0;
22798    ast_mutex_lock(&monlock);
22799    if (monitor_thread == pthread_self()) {
22800       ast_mutex_unlock(&monlock);
22801       ast_log(LOG_WARNING, "Cannot kill myself\n");
22802       return -1;
22803    }
22804    if (monitor_thread != AST_PTHREADT_NULL) {
22805       /* Wake up the thread */
22806       pthread_kill(monitor_thread, SIGURG);
22807    } else {
22808       /* Start a new monitor */
22809       if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
22810          ast_mutex_unlock(&monlock);
22811          ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
22812          return -1;
22813       }
22814    }
22815    ast_mutex_unlock(&monlock);
22816    return 0;
22817 }
22818 
22819 
22820 /*! \brief Session-Timers: Restart session timer */
22821 static void restart_session_timer(struct sip_pvt *p)
22822 {
22823    if (!p->stimer) {
22824       ast_log(LOG_WARNING, "Null stimer in restart_session_timer - %s\n", p->callid);
22825       return;
22826    }
22827 
22828    if (p->stimer->st_active == TRUE) {
22829       AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
22830             dialog_unref(p, "Removing session timer ref"));
22831       ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
22832       start_session_timer(p);
22833    }
22834 }
22835 
22836 
22837 /*! \brief Session-Timers: Stop session timer */
22838 static void stop_session_timer(struct sip_pvt *p)
22839 {
22840    if (!p->stimer) {
22841       ast_log(LOG_WARNING, "Null stimer in stop_session_timer - %s\n", p->callid);
22842       return;
22843    }
22844 
22845    if (p->stimer->st_active == TRUE) {
22846       p->stimer->st_active = FALSE;
22847       AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
22848             dialog_unref(p, "removing session timer ref"));
22849       ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
22850    }
22851 }
22852 
22853 
22854 /*! \brief Session-Timers: Start session timer */
22855 static void start_session_timer(struct sip_pvt *p)
22856 {
22857    if (!p->stimer) {
22858       ast_log(LOG_WARNING, "Null stimer in start_session_timer - %s\n", p->callid);
22859       return;
22860    }
22861 
22862    p->stimer->st_schedid  = ast_sched_add(sched, p->stimer->st_interval * 1000 / 2, proc_session_timer, 
22863          dialog_ref(p, "adding session timer ref"));
22864    if (p->stimer->st_schedid < 0) {
22865       dialog_unref(p, "removing session timer ref");
22866       ast_log(LOG_ERROR, "ast_sched_add failed.\n");
22867    }
22868    ast_debug(2, "Session timer started: %d - %s\n", p->stimer->st_schedid, p->callid);
22869 }
22870 
22871 
22872 /*! \brief Session-Timers: Process session refresh timeout event */
22873 static int proc_session_timer(const void *vp)
22874 {
22875    struct sip_pvt *p = (struct sip_pvt *) vp;
22876    int sendreinv = FALSE;
22877    int res = 0;
22878 
22879    if (!p->stimer) {
22880       ast_log(LOG_WARNING, "Null stimer in proc_session_timer - %s\n", p->callid);
22881       goto return_unref;
22882    }
22883 
22884    ast_debug(2, "Session timer expired: %d - %s\n", p->stimer->st_schedid, p->callid);
22885 
22886    if (!p->owner) {
22887       goto return_unref;
22888    }
22889 
22890    if ((p->stimer->st_active != TRUE) || (p->owner->_state != AST_STATE_UP)) {
22891       goto return_unref;
22892    }
22893 
22894    switch (p->stimer->st_ref) {
22895    case SESSION_TIMER_REFRESHER_UAC:
22896       if (p->outgoing_call == TRUE) {
22897          sendreinv = TRUE;
22898       }
22899       break;
22900    case SESSION_TIMER_REFRESHER_UAS:
22901       if (p->outgoing_call != TRUE) {
22902          sendreinv = TRUE;
22903       }
22904       break;
22905    default:
22906       ast_log(LOG_ERROR, "Unknown session refresher %d\n", p->stimer->st_ref);
22907       goto return_unref;
22908    }
22909 
22910    if (sendreinv == TRUE) {
22911       res = 1;
22912       transmit_reinvite_with_sdp(p, FALSE, TRUE);
22913    } else {
22914       p->stimer->st_expirys++;
22915       if (p->stimer->st_expirys >= 2) {
22916          if (p->stimer->quit_flag) {
22917             goto return_unref;
22918          }
22919          ast_log(LOG_WARNING, "Session-Timer expired - %s\n", p->callid);
22920          sip_pvt_lock(p);
22921          while (p->owner && ast_channel_trylock(p->owner)) {
22922             sip_pvt_unlock(p);
22923             usleep(1);
22924             if (p->stimer && p->stimer->quit_flag) {
22925                goto return_unref;
22926             }
22927             sip_pvt_lock(p);
22928          }
22929 
22930          ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
22931          ast_channel_unlock(p->owner);
22932          sip_pvt_unlock(p);
22933       }
22934    }
22935 
22936 return_unref:
22937    if (!res) {
22938       /* An error occurred.  Stop session timer processing */
22939       if (p->stimer) {
22940          p->stimer->st_schedid = -1;
22941          stop_session_timer(p);
22942       }
22943 
22944       /* If we are not asking to be rescheduled, then we need to release our
22945        * reference to the dialog. */
22946       dialog_unref(p, "removing session timer ref");
22947    }
22948 
22949    return res;
22950 }
22951 
22952 
22953 /*! \brief Session-Timers: Function for parsing Min-SE header */
22954 int parse_minse (const char *p_hdrval, int *const p_interval)
22955 {
22956    if (ast_strlen_zero(p_hdrval)) {
22957       ast_log(LOG_WARNING, "Null Min-SE header\n");
22958       return -1;
22959    }
22960 
22961    *p_interval = 0;
22962    p_hdrval = ast_skip_blanks(p_hdrval);
22963    if (!sscanf(p_hdrval, "%30d", p_interval)) {
22964       ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
22965       return -1;
22966    }
22967 
22968    ast_debug(2, "Received Min-SE: %d\n", *p_interval);
22969    return 0;
22970 }
22971 
22972 
22973 /*! \brief Session-Timers: Function for parsing Session-Expires header */
22974 int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref)
22975 {
22976    char *p_token;
22977    int  ref_idx;
22978    char *p_se_hdr;
22979 
22980    if (ast_strlen_zero(p_hdrval)) {
22981       ast_log(LOG_WARNING, "Null Session-Expires header\n");
22982       return -1;
22983    }
22984 
22985    *p_ref = SESSION_TIMER_REFRESHER_AUTO;
22986    *p_interval = 0;
22987 
22988    p_se_hdr = ast_strdupa(p_hdrval);
22989    p_se_hdr = ast_skip_blanks(p_se_hdr);
22990 
22991    while ((p_token = strsep(&p_se_hdr, ";"))) {
22992       p_token = ast_skip_blanks(p_token);
22993       if (!sscanf(p_token, "%30d", p_interval)) {
22994          ast_log(LOG_WARNING, "Parsing of Session-Expires failed\n");
22995          return -1;
22996       }
22997 
22998       ast_debug(2, "Session-Expires: %d\n", *p_interval);
22999 
23000       if (!p_se_hdr)
23001          continue;
23002 
23003       p_se_hdr = ast_skip_blanks(p_se_hdr);
23004       ref_idx = strlen("refresher=");
23005       if (!strncasecmp(p_se_hdr, "refresher=", ref_idx)) {
23006          p_se_hdr += ref_idx;
23007          p_se_hdr = ast_skip_blanks(p_se_hdr);
23008 
23009          if (!strncasecmp(p_se_hdr, "uac", strlen("uac"))) {
23010             *p_ref = SESSION_TIMER_REFRESHER_UAC;
23011             ast_debug(2, "Refresher: UAC\n");
23012          } else if (!strncasecmp(p_se_hdr, "uas", strlen("uas"))) {
23013             *p_ref = SESSION_TIMER_REFRESHER_UAS;
23014             ast_debug(2, "Refresher: UAS\n");
23015          } else {
23016             ast_log(LOG_WARNING, "Invalid refresher value %s\n", p_se_hdr);
23017             return -1;
23018          }
23019          break;
23020       }
23021    }
23022    return 0;
23023 }
23024 
23025 
23026 /*! \brief Handle 422 response to INVITE with session-timer requested
23027 
23028    Session-Timers:   An INVITE originated by Asterisk that asks for session-timers support
23029    from the UAS can result into a 422 response. This is how a UAS or an intermediary proxy 
23030    server tells Asterisk that the session refresh interval offered by Asterisk is too low 
23031    for them.  The proc_422_rsp() function handles a 422 response.  It extracts the Min-SE 
23032    header that comes back in 422 and sends a new INVITE accordingly. */
23033 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp)
23034 {
23035    int rtn;
23036    const char *p_hdrval;
23037    int minse;
23038 
23039    p_hdrval = get_header(rsp, "Min-SE");
23040    if (ast_strlen_zero(p_hdrval)) {
23041       ast_log(LOG_WARNING, "422 response without a Min-SE header %s\n", p_hdrval);
23042       return;
23043    }
23044    rtn = parse_minse(p_hdrval, &minse);
23045    if (rtn != 0) {
23046       ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
23047       return;
23048    }
23049    p->stimer->st_interval = minse;
23050    transmit_invite(p, SIP_INVITE, 1, 2); 
23051 }
23052 
23053 
23054 /*! \brief Get Max or Min SE (session timer expiry)
23055  * \param p pointer to the SIP dialog 
23056  * \param max if true, get max se, otherwise min se
23057 */
23058 int st_get_se(struct sip_pvt *p, int max)
23059 {
23060    if (max == TRUE) {
23061       if (p->stimer->st_cached_max_se) {
23062          return p->stimer->st_cached_max_se;
23063       } else if (p->peername) {
23064          struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
23065          if (pp) {
23066             p->stimer->st_cached_max_se = pp->stimer.st_max_se;
23067             unref_peer(pp, "unref peer pointer from find_peer call in st_get_se");
23068             return (p->stimer->st_cached_max_se);
23069          }
23070       }
23071       p->stimer->st_cached_max_se = global_max_se;
23072       return (p->stimer->st_cached_max_se);
23073    } else {
23074       if (p->stimer->st_cached_min_se) {
23075          return p->stimer->st_cached_min_se;
23076       } else if (p->peername) {
23077          struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
23078          if (pp) {
23079             p->stimer->st_cached_min_se = pp->stimer.st_min_se;
23080             unref_peer(pp, "unref peer pointer from find_peer call in st_get_se (2)");
23081             return (p->stimer->st_cached_min_se);
23082          }
23083       }
23084       p->stimer->st_cached_min_se = global_min_se;
23085       return (p->stimer->st_cached_min_se);
23086    }
23087 }
23088 
23089 
23090 /*! \brief Get the entity (UAC or UAS) that's acting as the session-timer refresher 
23091  * \param p pointer to the SIP dialog 
23092 */
23093 enum st_refresher st_get_refresher(struct sip_pvt *p)
23094 {
23095    if (p->stimer->st_cached_ref != SESSION_TIMER_REFRESHER_AUTO) 
23096       return p->stimer->st_cached_ref;
23097 
23098    if (p->peername) {
23099       struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
23100       if (pp) {
23101          p->stimer->st_cached_ref = pp->stimer.st_ref;
23102          unref_peer(pp, "unref peer pointer from find_peer call in st_get_refresher");
23103          return pp->stimer.st_ref;
23104       }
23105    }
23106    
23107    p->stimer->st_cached_ref = global_st_refresher;
23108    return global_st_refresher;
23109 }
23110 
23111 
23112 /*! \brief Get the session-timer mode 
23113  * \param p pointer to the SIP dialog 
23114 */
23115 enum st_mode st_get_mode(struct sip_pvt *p)
23116 {
23117    if (!p->stimer) 
23118       sip_st_alloc(p);
23119 
23120    if (p->stimer->st_cached_mode != SESSION_TIMER_MODE_INVALID) 
23121       return p->stimer->st_cached_mode;
23122 
23123    if (p->peername) {
23124       struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
23125       if (pp) {
23126          p->stimer->st_cached_mode = pp->stimer.st_mode_oper;
23127          unref_peer(pp, "unref peer pointer from find_peer call in st_get_mode");
23128          return pp->stimer.st_mode_oper;
23129       }
23130    }
23131 
23132    p->stimer->st_cached_mode = global_st_mode;
23133    return global_st_mode;
23134 }
23135 
23136 
23137 /*! \brief React to lack of answer to Qualify poke */
23138 static int sip_poke_noanswer(const void *data)
23139 {
23140    struct sip_peer *peer = (struct sip_peer *)data;
23141 
23142    peer->pokeexpire = -1;
23143 
23144    if (peer->lastms > -1) {
23145       ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE!  Last qualify: %d\n", peer->name, peer->lastms);
23146       if (sip_cfg.peer_rtupdate) {
23147          ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", "-1", SENTINEL);
23148       }
23149       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
23150       if (sip_cfg.regextenonqualify) {
23151          register_peer_exten(peer, FALSE);
23152       }
23153    }
23154 
23155    if (peer->call) {
23156       dialog_unlink_all(peer->call, TRUE, TRUE);
23157       peer->call = dialog_unref(peer->call, "unref dialog peer->call");
23158       /* peer->call = sip_destroy(peer->call);*/
23159    }
23160 
23161    /* Don't send a devstate change if nothing changed. */
23162    if (peer->lastms > -1) {
23163       peer->lastms = -1;
23164       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
23165    }
23166 
23167    /* Try again quickly */
23168    AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
23169          DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer,
23170          unref_peer(_data, "removing poke peer ref"),
23171          unref_peer(peer, "removing poke peer ref"),
23172          ref_peer(peer, "adding poke peer ref"));
23173 
23174    /* Release the ref held by the running scheduler entry */
23175    unref_peer(peer, "release peer poke noanswer ref");
23176 
23177    return 0;
23178 }
23179 
23180 /*! \brief Check availability of peer, also keep NAT open
23181 \note This is done with 60 seconds between each ping,
23182    unless forced by cli or manager. If peer is unreachable,
23183    we check every 10th second by default. 
23184 */
23185 static int sip_poke_peer(struct sip_peer *peer, int force)
23186 {
23187    struct sip_pvt *p;
23188    int xmitres = 0;
23189    
23190    if ((!peer->maxms && !force) || !peer->addr.sin_addr.s_addr) {
23191       /* IF we have no IP, or this isn't to be monitored, return
23192         immediately after clearing things out */
23193       AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
23194             unref_peer(peer, "removing poke peer ref"));
23195       
23196       peer->lastms = 0;
23197       if (peer->call) {
23198          peer->call = dialog_unref(peer->call, "unref dialog peer->call");
23199       }
23200       return 0;
23201    }
23202    if (peer->call) {
23203       if (sipdebug) {
23204          ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
23205       }
23206       dialog_unlink_all(peer->call, TRUE, TRUE);
23207       peer->call = dialog_unref(peer->call, "unref dialog peer->call");
23208       /* peer->call = sip_destroy(peer->call); */
23209    }
23210    if (!(p = sip_alloc(NULL, NULL, 0, SIP_OPTIONS, NULL))) {
23211       return -1;
23212    }
23213    peer->call = dialog_ref(p, "copy sip alloc from p to peer->call");
23214    
23215    p->sa = peer->addr;
23216    p->recv = peer->addr;
23217    copy_socket_data(&p->socket, &peer->socket);
23218    ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
23219    ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
23220 
23221    /* Send OPTIONs to peer's fullcontact */
23222    if (!ast_strlen_zero(peer->fullcontact))
23223       ast_string_field_set(p, fullcontact, peer->fullcontact);
23224 
23225    if (!ast_strlen_zero(peer->tohost))
23226       ast_string_field_set(p, tohost, peer->tohost);
23227    else
23228       ast_string_field_set(p, tohost, ast_inet_ntoa(peer->addr.sin_addr));
23229 
23230    /* Recalculate our side, and recalculate Call ID */
23231    ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
23232    build_via(p);
23233    ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
23234    build_callid_pvt(p);
23235    ao2_t_link(dialogs, p, "Linking in under new name");
23236 
23237    AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
23238          unref_peer(peer, "removing poke peer ref"));
23239    
23240    if (p->relatedpeer)
23241       p->relatedpeer = unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
23242    p->relatedpeer = ref_peer(peer, "setting the relatedpeer field in the dialog");
23243    ast_set_flag(&p->flags[0], SIP_OUTGOING);
23244 #ifdef VOCAL_DATA_HACK
23245    ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
23246    xmitres = transmit_invite(p, SIP_INVITE, 0, 2); /* sinks the p refcount */
23247 #else
23248    xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2); /* sinks the p refcount */
23249 #endif
23250    peer->ps = ast_tvnow();
23251    if (xmitres == XMIT_ERROR) {
23252       sip_poke_noanswer(peer);   /* Immediately unreachable, network problems */
23253    } else if (!force) {
23254       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, peer->maxms * 2, sip_poke_noanswer, peer,
23255             unref_peer(_data, "removing poke peer ref"),
23256             unref_peer(peer, "removing poke peer ref"),
23257             ref_peer(peer, "adding poke peer ref"));
23258    }
23259    dialog_unref(p, "unref dialog at end of sip_poke_peer, obtained from sip_alloc, just before it goes out of scope");
23260    return 0;
23261 }
23262 
23263 /*! \brief Part of PBX channel interface
23264 \note
23265 \par  Return values:---
23266 
23267    If we have qualify on and the device is not reachable, regardless of registration
23268    state we return AST_DEVICE_UNAVAILABLE
23269 
23270    For peers with call limit:
23271       - not registered        AST_DEVICE_UNAVAILABLE
23272       - registered, no call         AST_DEVICE_NOT_INUSE
23273       - registered, active calls    AST_DEVICE_INUSE
23274       - registered, call limit reached AST_DEVICE_BUSY
23275       - registered, onhold       AST_DEVICE_ONHOLD
23276       - registered, ringing         AST_DEVICE_RINGING
23277 
23278    For peers without call limit:
23279       - not registered        AST_DEVICE_UNAVAILABLE
23280       - registered            AST_DEVICE_NOT_INUSE
23281       - fixed IP (!dynamic)         AST_DEVICE_NOT_INUSE
23282    
23283    Peers that does not have a known call and can't be reached by OPTIONS
23284       - unreachable           AST_DEVICE_UNAVAILABLE
23285 
23286    If we return AST_DEVICE_UNKNOWN, the device state engine will try to find
23287    out a state by walking the channel list.
23288 
23289    The queue system (\ref app_queue.c) treats a member as "active"
23290    if devicestate is != AST_DEVICE_UNAVAILBALE && != AST_DEVICE_INVALID
23291 
23292    When placing a call to the queue member, queue system sets a member to busy if
23293    != AST_DEVICE_NOT_INUSE and != AST_DEVICE_UNKNOWN
23294 
23295 */
23296 static int sip_devicestate(void *data)
23297 {
23298    char *host;
23299    char *tmp;
23300    struct sip_peer *p;
23301 
23302    int res = AST_DEVICE_INVALID;
23303 
23304    /* make sure data is not null. Maybe unnecessary, but better be safe */
23305    host = ast_strdupa(data ? data : "");
23306    if ((tmp = strchr(host, '@')))
23307       host = tmp + 1;
23308 
23309    ast_debug(3, "Checking device state for peer %s\n", host);
23310 
23311    /* If find_peer asks for a realtime peer, then this breaks rtautoclear.  This
23312     * is because when a peer tries to autoexpire, the last thing it does is to
23313     * queue up an event telling the system that the devicestate has changed
23314     * (presumably to unavailable).  If we ask for a realtime peer here, this would
23315     * load it BACK into memory, thus defeating the point of trying to clear dead
23316     * hosts out of memory.
23317     */
23318    if ((p = find_peer(host, NULL, FALSE, FINDALLDEVICES, TRUE, 0))) {
23319       if (p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) {
23320          /* we have an address for the peer */
23321       
23322          /* Check status in this order
23323             - Hold
23324             - Ringing
23325             - Busy (enforced only by call limit)
23326             - Inuse (we have a call)
23327             - Unreachable (qualify)
23328             If we don't find any of these state, report AST_DEVICE_NOT_INUSE
23329             for registered devices */
23330 
23331          if (p->onHold)
23332             /* First check for hold or ring states */
23333             res = AST_DEVICE_ONHOLD;
23334          else if (p->inRinging) {
23335             if (p->inRinging == p->inUse)
23336                res = AST_DEVICE_RINGING;
23337             else
23338                res = AST_DEVICE_RINGINUSE;
23339          } else if (p->call_limit && (p->inUse == p->call_limit))
23340             /* check call limit */
23341             res = AST_DEVICE_BUSY;
23342          else if (p->call_limit && p->busy_level && p->inUse >= p->busy_level)
23343             /* We're forcing busy before we've reached the call limit */
23344             res = AST_DEVICE_BUSY;
23345          else if (p->call_limit && p->inUse)
23346             /* Not busy, but we do have a call */
23347             res = AST_DEVICE_INUSE;
23348          else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0))) 
23349             /* We don't have a call. Are we reachable at all? Requires qualify= */
23350             res = AST_DEVICE_UNAVAILABLE;
23351          else  /* Default reply if we're registered and have no other data */
23352             res = AST_DEVICE_NOT_INUSE;
23353       } else {
23354          /* there is no address, it's unavailable */
23355          res = AST_DEVICE_UNAVAILABLE;
23356       }
23357       unref_peer(p, "unref_peer, from sip_devicestate, release ref from find_peer");
23358    } else {
23359       res = AST_DEVICE_UNKNOWN;
23360    }
23361 
23362    return res;
23363 }
23364 
23365 /*! \brief PBX interface function -build SIP pvt structure 
23366  * SIP calls initiated by the PBX arrive here. 
23367  *
23368  * \verbatim   
23369  *    SIP Dial string syntax
23370  *    SIP/exten@host!dnid
23371  * or SIP/host/exten!dnid
23372  * or SIP/host!dnid
23373  * \endverbatim
23374 */
23375 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause)
23376 {
23377    struct sip_pvt *p;
23378    struct ast_channel *tmpc = NULL;
23379    char *ext = NULL, *host;
23380    char tmp[256];
23381    char *dest = data;
23382    char *dnid;
23383    char *secret = NULL;
23384    char *md5secret = NULL;
23385    char *authname = NULL;
23386    char *trans = NULL;
23387    enum sip_transport transport = 0;
23388    int oldformat = format;
23389 
23390    /* mask request with some set of allowed formats.
23391     * XXX this needs to be fixed.
23392     * The original code uses AST_FORMAT_AUDIO_MASK, but it is
23393     * unclear what to use here. We have global_capabilities, which is
23394     * configured from sip.conf, and sip_tech.capabilities, which is
23395     * hardwired to all audio formats.
23396     */
23397    format &= AST_FORMAT_AUDIO_MASK;
23398    if (!format) {
23399       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));
23400       *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;   /* Can't find codec to connect to host */
23401       return NULL;
23402    }
23403    ast_debug(1, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));
23404 
23405    if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE, NULL))) {
23406       ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", dest);
23407       *cause = AST_CAUSE_SWITCH_CONGESTION;
23408       return NULL;
23409    }
23410 
23411    p->outgoing_call = TRUE;
23412 
23413    if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
23414       dialog_unlink_all(p, TRUE, TRUE);
23415       dialog_unref(p, "unref dialog p from mem fail");
23416       /* sip_destroy(p); */
23417       ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
23418       *cause = AST_CAUSE_SWITCH_CONGESTION;
23419       return NULL;
23420    }
23421 
23422    /* Save the destination, the SIP dial string */
23423    ast_copy_string(tmp, dest, sizeof(tmp));
23424 
23425 
23426    /* Find DNID and take it away */
23427    dnid = strchr(tmp, '!');
23428    if (dnid != NULL) {
23429       *dnid++ = '\0';
23430       ast_string_field_set(p, todnid, dnid);
23431    }
23432 
23433    /* Find at sign - @ */
23434    host = strchr(tmp, '@');
23435    if (host) {
23436       *host++ = '\0';
23437       ext = tmp;
23438       secret = strchr(ext, ':');
23439    }
23440    if (secret) {
23441       *secret++ = '\0';
23442       md5secret = strchr(secret, ':');
23443    }
23444    if (md5secret) {
23445       *md5secret++ = '\0';
23446       authname = strchr(md5secret, ':');
23447    }
23448    if (authname) {
23449       *authname++ = '\0';
23450       trans = strchr(authname, ':');
23451    }
23452    if (trans) {
23453       *trans++ = '\0';
23454       if (!strcasecmp(trans, "tcp"))
23455          transport = SIP_TRANSPORT_TCP;
23456       else if (!strcasecmp(trans, "tls"))
23457          transport = SIP_TRANSPORT_TLS;
23458       else {
23459          if (strcasecmp(trans, "udp"))
23460             ast_log(LOG_WARNING, "'%s' is not a valid transport option to Dial() for SIP calls, using udp by default.\n", trans);
23461          transport = SIP_TRANSPORT_UDP;
23462       }
23463    } else { /* use default */
23464       transport = SIP_TRANSPORT_UDP;
23465    }
23466 
23467    if (!host) {
23468       ext = strchr(tmp, '/');
23469       if (ext) 
23470          *ext++ = '\0';
23471       host = tmp;
23472    }
23473 
23474    set_socket_transport(&p->socket, transport);
23475 
23476    /* We now have 
23477       host = peer name, DNS host name or DNS domain (for SRV) 
23478       ext = extension (user part of URI)
23479       dnid = destination of the call (applies to the To: header)
23480    */
23481    if (create_addr(p, host, NULL, 1)) {
23482       *cause = AST_CAUSE_UNREGISTERED;
23483       ast_debug(3, "Cant create SIP call - target device not registered\n");
23484       dialog_unlink_all(p, TRUE, TRUE);
23485       dialog_unref(p, "unref dialog p UNREGISTERED");
23486       /* sip_destroy(p); */
23487       return NULL;
23488    }
23489    if (ast_strlen_zero(p->peername) && ext)
23490       ast_string_field_set(p, peername, ext);
23491    /* Recalculate our side, and recalculate Call ID */
23492    ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
23493    build_via(p);
23494    ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
23495    build_callid_pvt(p);
23496    ao2_t_link(dialogs, p, "Linking in under new name");
23497    
23498    /* We have an extension to call, don't use the full contact here */
23499    /* This to enable dialing registered peers with extension dialling,
23500       like SIP/peername/extension   
23501       SIP/peername will still use the full contact 
23502     */
23503    if (ext) {
23504       ast_string_field_set(p, username, ext);
23505       ast_string_field_set(p, fullcontact, NULL);
23506    }
23507    if (secret && !ast_strlen_zero(secret))
23508       ast_string_field_set(p, peersecret, secret);
23509 
23510    if (md5secret && !ast_strlen_zero(md5secret))
23511       ast_string_field_set(p, peermd5secret, md5secret);
23512 
23513    if (authname && !ast_strlen_zero(authname))
23514       ast_string_field_set(p, authname, authname);
23515 #if 0
23516    printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
23517 #endif
23518    p->prefcodec = oldformat;           /* Format for this call */
23519    p->jointcapability = oldformat & p->capability;
23520    sip_pvt_lock(p);
23521    tmpc = sip_new(p, AST_STATE_DOWN, host);  /* Place the call */
23522    if (sip_cfg.callevents)
23523       manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
23524          "Channel: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
23525          p->owner? p->owner->name : "", "SIP", p->callid, p->fullcontact, p->peername);
23526    sip_pvt_unlock(p);
23527    if (!tmpc) {
23528       dialog_unlink_all(p, TRUE, TRUE);
23529       /* sip_destroy(p); */
23530    }
23531    dialog_unref(p, "toss pvt ptr at end of sip_request_call");
23532    ast_update_use_count();
23533    restart_monitor();
23534    return tmpc;
23535 }
23536 
23537 /*! \brief Parse insecure= setting in sip.conf and set flags according to setting */
23538 static void set_insecure_flags (struct ast_flags *flags, const char *value, int lineno)
23539 {
23540    if (ast_strlen_zero(value))
23541       return;
23542 
23543    if (!ast_false(value)) {
23544       char buf[64];
23545       char *word, *next;
23546 
23547       ast_copy_string(buf, value, sizeof(buf));
23548       next = buf;
23549       while ((word = strsep(&next, ","))) {
23550          if (!strcasecmp(word, "port"))
23551             ast_set_flag(&flags[0], SIP_INSECURE_PORT);
23552          else if (!strcasecmp(word, "invite"))
23553             ast_set_flag(&flags[0], SIP_INSECURE_INVITE);
23554          else
23555             ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
23556       }
23557    }
23558 }
23559 
23560 /*!
23561   \brief Handle T.38 configuration options common to users and peers
23562   \returns non-zero if any config options were handled, zero otherwise
23563 */
23564 static int handle_t38_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v,
23565                int *maxdatagram)
23566 {
23567    int res = 1;
23568 
23569    if (!strcasecmp(v->name, "t38pt_udptl")) {
23570       char *buf = ast_strdupa(v->value);
23571       char *word, *next = buf;
23572 
23573       ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT);
23574 
23575       while ((word = strsep(&next, ","))) {
23576          if (ast_true(word) || !strcasecmp(word, "fec")) {
23577             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
23578             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_FEC);
23579          } else if (!strcasecmp(word, "redundancy")) {
23580             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
23581             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY);
23582          } else if (!strcasecmp(word, "none")) {
23583             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
23584             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
23585          } else if (!strncasecmp(word, "maxdatagram=", 12)) {
23586             if (sscanf(&word[12], "%30u", maxdatagram) != 1) {
23587                ast_log(LOG_WARNING, "Invalid maxdatagram '%s' at line %d of %s\n", v->value, v->lineno, config);
23588                *maxdatagram = global_t38_maxdatagram;
23589             }
23590          }
23591       }
23592    } else if (!strcasecmp(v->name, "t38pt_usertpsource")) {
23593       ast_set_flag(&mask[1], SIP_PAGE2_UDPTL_DESTINATION);
23594       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_UDPTL_DESTINATION);
23595    } else if (!strcasecmp(v->name, "forwardloopdetected")) {
23596       ast_set_flag(&mask[1], SIP_PAGE2_FORWARD_LOOP_DETECTED);
23597       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_FORWARD_LOOP_DETECTED);
23598    } else {
23599       res = 0;
23600    }
23601 
23602    return res;
23603 }
23604 
23605 /*!
23606   \brief Handle flag-type options common to configuration of devices - peers
23607   \param flags array of two struct ast_flags
23608   \param mask array of two struct ast_flags
23609   \param v linked list of config variables to process
23610   \returns non-zero if any config options were handled, zero otherwise
23611 */
23612 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
23613 {
23614    int res = 1;
23615 
23616    if (!strcasecmp(v->name, "trustrpid")) {
23617       ast_set_flag(&mask[0], SIP_TRUSTRPID);
23618       ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
23619    } else if (!strcasecmp(v->name, "sendrpid")) {
23620       ast_set_flag(&mask[0], SIP_SENDRPID);
23621       ast_set2_flag(&flags[0], ast_true(v->value), SIP_SENDRPID);
23622    } else if (!strcasecmp(v->name, "g726nonstandard")) {
23623       ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
23624       ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
23625    } else if (!strcasecmp(v->name, "useclientcode")) {
23626       ast_set_flag(&mask[0], SIP_USECLIENTCODE);
23627       ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
23628    } else if (!strcasecmp(v->name, "dtmfmode")) {
23629       ast_set_flag(&mask[0], SIP_DTMF);
23630       ast_clear_flag(&flags[0], SIP_DTMF);
23631       if (!strcasecmp(v->value, "inband"))
23632          ast_set_flag(&flags[0], SIP_DTMF_INBAND);
23633       else if (!strcasecmp(v->value, "rfc2833"))
23634          ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
23635       else if (!strcasecmp(v->value, "info"))
23636          ast_set_flag(&flags[0], SIP_DTMF_INFO);
23637       else if (!strcasecmp(v->value, "shortinfo"))
23638          ast_set_flag(&flags[0], SIP_DTMF_SHORTINFO);
23639       else if (!strcasecmp(v->value, "auto"))
23640          ast_set_flag(&flags[0], SIP_DTMF_AUTO);
23641       else {
23642          ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
23643          ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
23644       }
23645    } else if (!strcasecmp(v->name, "nat")) {
23646       ast_set_flag(&mask[0], SIP_NAT);
23647       ast_clear_flag(&flags[0], SIP_NAT);
23648       if (!strcasecmp(v->value, "never"))
23649          ast_set_flag(&flags[0], SIP_NAT_NEVER);
23650       else if (!strcasecmp(v->value, "route"))
23651          ast_set_flag(&flags[0], SIP_NAT_ROUTE);
23652       else if (ast_true(v->value))
23653          ast_set_flag(&flags[0], SIP_NAT_ALWAYS);
23654       else
23655          ast_set_flag(&flags[0], SIP_NAT_RFC3581);
23656    } else if (!strcasecmp(v->name, "directmedia") || !strcasecmp(v->name, "canreinvite")) {
23657       ast_set_flag(&mask[0], SIP_REINVITE);
23658       ast_clear_flag(&flags[0], SIP_REINVITE);
23659       if (ast_true(v->value)) {
23660          ast_set_flag(&flags[0], SIP_DIRECT_MEDIA | SIP_DIRECT_MEDIA_NAT);
23661       } else if (!ast_false(v->value)) {
23662          char buf[64];
23663          char *word, *next = buf;
23664 
23665          ast_copy_string(buf, v->value, sizeof(buf));
23666          while ((word = strsep(&next, ","))) {
23667             if (!strcasecmp(word, "update")) {
23668                ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_DIRECT_MEDIA);
23669             } else if (!strcasecmp(word, "nonat")) {
23670                ast_set_flag(&flags[0], SIP_DIRECT_MEDIA);
23671                ast_clear_flag(&flags[0], SIP_DIRECT_MEDIA_NAT);
23672             } else {
23673                ast_log(LOG_WARNING, "Unknown directmedia mode '%s' on line %d\n", v->value, v->lineno);
23674             }
23675          }
23676       }
23677    } else if (!strcasecmp(v->name, "insecure")) {
23678       ast_set_flag(&mask[0], SIP_INSECURE);
23679       ast_clear_flag(&flags[0], SIP_INSECURE);
23680       set_insecure_flags(&flags[0], v->value, v->lineno);   
23681    } else if (!strcasecmp(v->name, "progressinband")) {
23682       ast_set_flag(&mask[0], SIP_PROG_INBAND);
23683       ast_clear_flag(&flags[0], SIP_PROG_INBAND);
23684       if (ast_true(v->value))
23685          ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
23686       else if (strcasecmp(v->value, "never"))
23687          ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
23688    } else if (!strcasecmp(v->name, "promiscredir")) {
23689       ast_set_flag(&mask[0], SIP_PROMISCREDIR);
23690       ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
23691    } else if (!strcasecmp(v->name, "videosupport")) {
23692       if (!strcasecmp(v->value, "always")) {
23693          ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
23694          ast_set_flag(&flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
23695       } else {
23696          ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
23697          ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
23698       }
23699    } else if (!strcasecmp(v->name, "textsupport")) {
23700       ast_set_flag(&mask[1], SIP_PAGE2_TEXTSUPPORT);
23701       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_TEXTSUPPORT);
23702       res = 1;
23703    } else if (!strcasecmp(v->name, "allowoverlap")) {
23704       ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
23705       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWOVERLAP);
23706    } else if (!strcasecmp(v->name, "allowsubscribe")) {
23707       ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
23708       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
23709    } else if (!strcasecmp(v->name, "ignoresdpversion")) {
23710       ast_set_flag(&mask[1], SIP_PAGE2_IGNORESDPVERSION);
23711       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_IGNORESDPVERSION);
23712    } else if (!strcasecmp(v->name, "faxdetect")) {
23713       ast_set_flag(&mask[1], SIP_PAGE2_FAX_DETECT);
23714       if (ast_true(v->value)) {
23715          ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
23716       } else if (ast_false(v->value)) {
23717          ast_clear_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
23718       } else {
23719          char *buf = ast_strdupa(v->value);
23720          char *word, *next = buf;
23721 
23722          while ((word = strsep(&next, ","))) {
23723             if (!strcasecmp(word, "cng")) {
23724                ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_CNG);
23725             } else if (!strcasecmp(word, "t38")) {
23726                ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_T38);
23727             } else {
23728                ast_log(LOG_WARNING, "Unknown faxdetect mode '%s' on line %d.\n", word, v->lineno);
23729             }
23730          }
23731       }
23732    } else if (!strcasecmp(v->name, "rfc2833compensate")) {
23733       ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
23734       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
23735    } else if (!strcasecmp(v->name, "buggymwi")) {
23736       ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
23737       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
23738    } else
23739       res = 0;
23740 
23741    return res;
23742 }
23743 
23744 /*! \brief Add SIP domain to list of domains we are responsible for */
23745 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
23746 {
23747    struct domain *d;
23748 
23749    if (ast_strlen_zero(domain)) {
23750       ast_log(LOG_WARNING, "Zero length domain.\n");
23751       return 1;
23752    }
23753 
23754    if (!(d = ast_calloc(1, sizeof(*d))))
23755       return 0;
23756 
23757    ast_copy_string(d->domain, domain, sizeof(d->domain));
23758 
23759    if (!ast_strlen_zero(context))
23760       ast_copy_string(d->context, context, sizeof(d->context));
23761 
23762    d->mode = mode;
23763 
23764    AST_LIST_LOCK(&domain_list);
23765    AST_LIST_INSERT_TAIL(&domain_list, d, list);
23766    AST_LIST_UNLOCK(&domain_list);
23767 
23768    if (sipdebug)  
23769       ast_debug(1, "Added local SIP domain '%s'\n", domain);
23770 
23771    return 1;
23772 }
23773 
23774 /*! \brief  check_sip_domain: Check if domain part of uri is local to our server */
23775 static int check_sip_domain(const char *domain, char *context, size_t len)
23776 {
23777    struct domain *d;
23778    int result = 0;
23779 
23780    AST_LIST_LOCK(&domain_list);
23781    AST_LIST_TRAVERSE(&domain_list, d, list) {
23782       if (strcasecmp(d->domain, domain))
23783          continue;
23784 
23785       if (len && !ast_strlen_zero(d->context))
23786          ast_copy_string(context, d->context, len);
23787       
23788       result = 1;
23789       break;
23790    }
23791    AST_LIST_UNLOCK(&domain_list);
23792 
23793    return result;
23794 }
23795 
23796 /*! \brief Clear our domain list (at reload) */
23797 static void clear_sip_domains(void)
23798 {
23799    struct domain *d;
23800 
23801    AST_LIST_LOCK(&domain_list);
23802    while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
23803       ast_free(d);
23804    AST_LIST_UNLOCK(&domain_list);
23805 }
23806 
23807 
23808 /*! \brief Add realm authentication in list */
23809 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno)
23810 {
23811    char authcopy[256];
23812    char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
23813    struct sip_auth *a, *b, *auth;
23814 
23815    if (ast_strlen_zero(configuration))
23816       return authlist;
23817 
23818    ast_debug(1, "Auth config ::  %s\n", configuration);
23819 
23820    ast_copy_string(authcopy, configuration, sizeof(authcopy));
23821    username = authcopy;
23822 
23823    /* split user[:secret] and relm */
23824    realm = strrchr(username, '@');
23825    if (realm)
23826       *realm++ = '\0';
23827    if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
23828       ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
23829       return authlist;
23830    }
23831 
23832    /* parse username at ':' for secret, or '#" for md5secret */
23833    if ((secret = strchr(username, ':'))) {
23834       *secret++ = '\0';
23835    } else if ((md5secret = strchr(username, '#'))) {
23836       *md5secret++ = '\0';
23837    }
23838 
23839    if (!(auth = ast_calloc(1, sizeof(*auth))))
23840       return authlist;
23841 
23842    ast_copy_string(auth->realm, realm, sizeof(auth->realm));
23843    ast_copy_string(auth->username, username, sizeof(auth->username));
23844    if (secret)
23845       ast_copy_string(auth->secret, secret, sizeof(auth->secret));
23846    if (md5secret)
23847       ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
23848 
23849    /* find the end of the list */
23850    for (b = NULL, a = authlist; a ; b = a, a = a->next)
23851       ;
23852    if (b)
23853       b->next = auth;   /* Add structure add end of list */
23854    else
23855       authlist = auth;
23856 
23857    ast_verb(3, "Added authentication for realm %s\n", realm);
23858 
23859    return authlist;
23860 
23861 }
23862 
23863 /*! \brief Clear realm authentication list (at reload) */
23864 static int clear_realm_authentication(struct sip_auth *authlist)
23865 {
23866    struct sip_auth *a = authlist;
23867    struct sip_auth *b;
23868 
23869    while (a) {
23870       b = a;
23871       a = a->next;
23872       ast_free(b);
23873    }
23874 
23875    return 1;
23876 }
23877 
23878 /*! \brief Find authentication for a specific realm */
23879 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm)
23880 {
23881    struct sip_auth *a;
23882 
23883    for (a = authlist; a; a = a->next) {
23884       if (!strcasecmp(a->realm, realm))
23885          break;
23886    }
23887 
23888    return a;
23889 }
23890 
23891 /*! \brief
23892  * implement the setvar config line
23893  */
23894 static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
23895 {
23896    struct ast_variable *tmpvar = NULL;
23897    char *varname = ast_strdupa(buf), *varval = NULL;
23898    
23899    if ((varval = strchr(varname, '='))) {
23900       *varval++ = '\0';
23901       if ((tmpvar = ast_variable_new(varname, varval, ""))) {
23902          tmpvar->next = list;
23903          list = tmpvar;
23904       }
23905    }
23906    return list;
23907 }
23908 
23909 /*! \brief Set peer defaults before configuring specific configurations */
23910 static void set_peer_defaults(struct sip_peer *peer)
23911 {
23912    if (peer->expire == 0) {
23913       /* Don't reset expire or port time during reload 
23914          if we have an active registration 
23915       */
23916       peer->expire = -1;
23917       peer->pokeexpire = -1;
23918       peer->addr.sin_port = htons(STANDARD_SIP_PORT);
23919       set_socket_transport(&peer->socket, SIP_TRANSPORT_UDP);
23920    }
23921    peer->type = SIP_TYPE_PEER;
23922    ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
23923    ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
23924    ast_string_field_set(peer, context, sip_cfg.default_context);
23925    ast_string_field_set(peer, subscribecontext, sip_cfg.default_subscribecontext);
23926    ast_string_field_set(peer, language, default_language);
23927    ast_string_field_set(peer, mohinterpret, default_mohinterpret);
23928    ast_string_field_set(peer, mohsuggest, default_mohsuggest);
23929    peer->addr.sin_family = AF_INET;
23930    peer->defaddr.sin_family = AF_INET;
23931    peer->capability = global_capability;
23932    peer->maxcallbitrate = default_maxcallbitrate;
23933    peer->rtptimeout = global_rtptimeout;
23934    peer->rtpholdtimeout = global_rtpholdtimeout;
23935    peer->rtpkeepalive = global_rtpkeepalive;
23936    peer->allowtransfer = sip_cfg.allowtransfer;
23937    peer->autoframing = global_autoframing;
23938    peer->t38_maxdatagram = global_t38_maxdatagram;
23939    peer->qualifyfreq = global_qualifyfreq;
23940    if (global_callcounter)
23941       peer->call_limit=INT_MAX;
23942    ast_string_field_set(peer, vmexten, default_vmexten);
23943    ast_string_field_set(peer, secret, "");
23944    ast_string_field_set(peer, remotesecret, "");
23945    ast_string_field_set(peer, md5secret, "");
23946    ast_string_field_set(peer, cid_num, "");
23947    ast_string_field_set(peer, cid_name, "");
23948    ast_string_field_set(peer, fromdomain, "");
23949    ast_string_field_set(peer, fromuser, "");
23950    ast_string_field_set(peer, regexten, "");
23951    peer->callgroup = 0;
23952    peer->pickupgroup = 0;
23953    peer->maxms = default_qualify;
23954    peer->prefs = default_prefs;
23955    peer->stimer.st_mode_oper = global_st_mode;  /* Session-Timers */
23956    peer->stimer.st_ref = global_st_refresher;
23957    peer->stimer.st_min_se = global_min_se;
23958    peer->stimer.st_max_se = global_max_se;
23959    peer->timer_t1 = global_t1;
23960    peer->timer_b = global_timer_b;
23961    clear_peer_mailboxes(peer);
23962    peer->transports = default_transports;
23963    peer->default_outbound_transport = default_primary_transport;
23964 }
23965 
23966 /*! \brief Create temporary peer (used in autocreatepeer mode) */
23967 static struct sip_peer *temp_peer(const char *name)
23968 {
23969    struct sip_peer *peer;
23970 
23971    if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
23972       return NULL;
23973 
23974    if (ast_string_field_init(peer, 512)) {
23975       ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
23976       return NULL;
23977    }
23978 
23979    ast_atomic_fetchadd_int(&apeerobjs, 1);
23980    set_peer_defaults(peer);
23981 
23982    ast_copy_string(peer->name, name, sizeof(peer->name));
23983 
23984    peer->selfdestruct = TRUE;
23985    peer->host_dynamic = TRUE;
23986    peer->prefs = default_prefs;
23987    reg_source_db(peer);
23988 
23989    return peer;
23990 }
23991 
23992 /*! \todo document this function */
23993 static void add_peer_mailboxes(struct sip_peer *peer, const char *value)
23994 {
23995    char *next, *mbox, *context;
23996 
23997    next = ast_strdupa(value);
23998 
23999    while ((mbox = context = strsep(&next, ","))) {
24000       struct sip_mailbox *mailbox;
24001       int duplicate = 0;
24002 
24003       strsep(&context, "@");
24004 
24005       if (ast_strlen_zero(mbox)) {
24006          continue;
24007       }
24008 
24009       /* Check whether the mailbox is already in the list */
24010       AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
24011          if (!strcmp(mailbox->mailbox, mbox) && !strcmp(S_OR(mailbox->context, ""), S_OR(context, ""))) {
24012             duplicate = 1;
24013             mailbox->delme = 1;
24014             break;
24015          }
24016       }
24017       if (duplicate) {
24018          continue;
24019       }
24020 
24021       if (!(mailbox = ast_calloc(1, sizeof(*mailbox)))) {
24022          continue;
24023       }
24024 
24025       mailbox->mailbox = ast_strdup(mbox);
24026       mailbox->context = ast_strdup(context);
24027 
24028       AST_LIST_INSERT_TAIL(&peer->mailboxes, mailbox, entry);
24029    }
24030 }
24031 
24032 /*! \brief Build peer from configuration (file or realtime static/dynamic) */
24033 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only)
24034 {
24035    struct sip_peer *peer = NULL;
24036    struct ast_ha *oldha = NULL;
24037    int found = 0;
24038    int firstpass = 1;
24039    uint16_t port = 0;
24040    int format = 0;      /* Ama flags */
24041    time_t regseconds = 0;
24042    struct ast_flags peerflags[2] = {{(0)}};
24043    struct ast_flags mask[2] = {{(0)}};
24044    char callback[256] = "";
24045    struct sip_peer tmp_peer;
24046    const char *srvlookup = NULL;
24047    static int deprecation_warning = 1;
24048    int alt_fullcontact = alt ? 1 : 0;
24049    struct ast_str *fullcontact = ast_str_alloca(512);
24050 
24051    if (!realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
24052       /* Note we do NOT use find_peer here, to avoid realtime recursion */
24053       /* We also use a case-sensitive comparison (unlike find_peer) so
24054          that case changes made to the peer name will be properly handled
24055          during reload
24056       */
24057       ast_copy_string(tmp_peer.name, name, sizeof(tmp_peer.name));
24058       peer = ao2_t_find(peers, &tmp_peer, OBJ_POINTER | OBJ_UNLINK, "find and unlink peer from peers table");
24059    }
24060 
24061    if (peer) {
24062       /* Already in the list, remove it and it will be added back (or FREE'd)  */
24063       found++;
24064       if (!(peer->the_mark))
24065          firstpass = 0;
24066    } else {
24067       if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
24068          return NULL;
24069 
24070       if (ast_string_field_init(peer, 512)) {
24071          ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
24072          return NULL;
24073       }
24074 
24075       if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
24076          ast_atomic_fetchadd_int(&rpeerobjs, 1);
24077          ast_debug(3, "-REALTIME- peer built. Name: %s. Peer objects: %d\n", name, rpeerobjs);
24078       } else
24079          ast_atomic_fetchadd_int(&speerobjs, 1);
24080    }
24081 
24082    /* Note that our peer HAS had its reference count increased */
24083    if (firstpass) {
24084       peer->lastmsgssent = -1;
24085       oldha = peer->ha;
24086       peer->ha = NULL;
24087       set_peer_defaults(peer);   /* Set peer defaults */
24088       peer->type = 0;
24089    }
24090    if (!found && name)
24091       ast_copy_string(peer->name, name, sizeof(peer->name));
24092 
24093    /* If we have channel variables, remove them (reload) */
24094    if (peer->chanvars) {
24095       ast_variables_destroy(peer->chanvars);
24096       peer->chanvars = NULL;
24097       /* XXX should unregister ? */
24098    }
24099 
24100    if (found)
24101       peer->portinuri = 0;
24102 
24103    /* If we have realm authentication information, remove them (reload) */
24104    clear_realm_authentication(peer->auth);
24105    peer->auth = NULL;
24106    /* clear the transport information.  We will detect if a default value is required after parsing the config */
24107    peer->default_outbound_transport = 0;
24108    peer->transports = 0;
24109 
24110    if (!devstate_only) {
24111       struct sip_mailbox *mailbox;
24112       AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
24113          mailbox->delme = 1;
24114       }
24115    }
24116 
24117    for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
24118       if (!devstate_only) {
24119          if (handle_common_options(&peerflags[0], &mask[0], v)) {
24120             continue;
24121          }
24122          if (handle_t38_options(&peerflags[0], &mask[0], v, &peer->t38_maxdatagram)) {
24123             continue;
24124          }
24125          if (!strcasecmp(v->name, "transport") && !ast_strlen_zero(v->value)) {
24126             char *val = ast_strdupa(v->value);
24127             char *trans;
24128 
24129             while ((trans = strsep(&val, ","))) {
24130                trans = ast_skip_blanks(trans);
24131 
24132                if (!strncasecmp(trans, "udp", 3)) {
24133                   peer->transports |= SIP_TRANSPORT_UDP;
24134                } else if (!strncasecmp(trans, "tcp", 3)) {
24135                   peer->transports |= SIP_TRANSPORT_TCP;
24136                } else if (!strncasecmp(trans, "tls", 3)) {
24137                   peer->transports |= SIP_TRANSPORT_TLS;
24138                } else {
24139                   ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
24140                }
24141 
24142                if (!peer->default_outbound_transport) { /*!< The first transport listed should be default outbound */
24143                   peer->default_outbound_transport = peer->transports;
24144                }
24145             }
24146          } else if (realtime && !strcasecmp(v->name, "regseconds")) {
24147             ast_get_time_t(v->value, &regseconds, 0, NULL);
24148          } else if (realtime && !strcasecmp(v->name, "name")) {
24149             ast_copy_string(peer->name, v->value, sizeof(peer->name));
24150          } else if (realtime && !strcasecmp(v->name, "useragent")) {
24151             ast_string_field_set(peer, useragent, v->value);
24152          } else if (!strcasecmp(v->name, "type")) {
24153             if (!strcasecmp(v->value, "peer")) {
24154                peer->type |= SIP_TYPE_PEER;
24155             } else if (!strcasecmp(v->value, "user")) {
24156                peer->type |= SIP_TYPE_USER;
24157             } else if (!strcasecmp(v->value, "friend")) {
24158                peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
24159             }
24160          } else if (!strcasecmp(v->name, "remotesecret")) {
24161             ast_string_field_set(peer, remotesecret, v->value);
24162          } else if (!strcasecmp(v->name, "secret")) {
24163             ast_string_field_set(peer, secret, v->value);
24164          } else if (!strcasecmp(v->name, "md5secret")) {
24165             ast_string_field_set(peer, md5secret, v->value);
24166          } else if (!strcasecmp(v->name, "auth")) {
24167             peer->auth = add_realm_authentication(peer->auth, v->value, v->lineno);
24168          } else if (!strcasecmp(v->name, "callerid")) {
24169             char cid_name[80] = { '\0' }, cid_num[80] = { '\0' };
24170 
24171             ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
24172             ast_string_field_set(peer, cid_name, cid_name);
24173             ast_string_field_set(peer, cid_num, cid_num);
24174          } else if (!strcasecmp(v->name, "fullname")) {
24175             ast_string_field_set(peer, cid_name, v->value);
24176          } else if (!strcasecmp(v->name, "trunkname")) {
24177             /* This is actually for a trunk, so we don't want to override callerid */
24178             ast_string_field_set(peer, cid_name, "");
24179          } else if (!strcasecmp(v->name, "cid_number")) {
24180             ast_string_field_set(peer, cid_num, v->value);
24181          } else if (!strcasecmp(v->name, "context")) {
24182             ast_string_field_set(peer, context, v->value);
24183             ast_set_flag(&peer->flags[1], SIP_PAGE2_HAVEPEERCONTEXT);
24184          } else if (!strcasecmp(v->name, "subscribecontext")) {
24185             ast_string_field_set(peer, subscribecontext, v->value);
24186          } else if (!strcasecmp(v->name, "fromdomain")) {
24187             ast_string_field_set(peer, fromdomain, v->value);
24188          } else if (!strcasecmp(v->name, "usereqphone")) {
24189             ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
24190          } else if (!strcasecmp(v->name, "fromuser")) {
24191             ast_string_field_set(peer, fromuser, v->value);
24192          } else if (!strcasecmp(v->name, "outboundproxy")) {
24193             char *port, *next, *force, *proxyname;
24194             int forceopt = FALSE;
24195             /* Set peer channel variable */
24196             next = proxyname = ast_strdupa(v->value);
24197             if ((port = strchr(proxyname, ':'))) {
24198                *port++ = '\0';
24199                next = port;
24200             }
24201             if ((force = strchr(next, ','))) {
24202                *force++ = '\0';
24203                forceopt = strcmp(force, "force");
24204             }
24205             /* Allocate proxy object */
24206             peer->outboundproxy = proxy_allocate(proxyname, port, forceopt);
24207          } else if (!strcasecmp(v->name, "host")) {
24208             if (!strcasecmp(v->value, "dynamic")) {
24209                /* They'll register with us */
24210                if (!found || !peer->host_dynamic) {
24211                   /* Initialize stuff if this is a new peer, or if it used to
24212                    * not be dynamic before the reload. */
24213                   memset(&peer->addr.sin_addr, 0, 4);
24214                   peer->addr.sin_port = 0;
24215                }
24216                peer->host_dynamic = TRUE;
24217             } else {
24218                /* Non-dynamic.  Make sure we become that way if we're not */
24219                AST_SCHED_DEL_UNREF(sched, peer->expire,
24220                      unref_peer(peer, "removing register expire ref"));
24221                /* the port will either be set to a default value or a config specified value once all option parsing is complete */
24222                peer->addr.sin_port = 0;
24223                peer->host_dynamic = FALSE;
24224                srvlookup = v->value;
24225             }
24226          } else if (!strcasecmp(v->name, "defaultip")) {
24227             if (!ast_strlen_zero(v->value) && ast_get_ip(&peer->defaddr, v->value)) {
24228                unref_peer(peer, "unref_peer: from build_peer defaultip");
24229                return NULL;
24230             }
24231          } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
24232             int ha_error = 0;
24233             if (!ast_strlen_zero(v->value)) {
24234                peer->ha = ast_append_ha(v->name, v->value, peer->ha, &ha_error);
24235             }
24236             if (ha_error) {
24237                ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
24238             }
24239          } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
24240             int ha_error = 0;
24241             if (!ast_strlen_zero(v->value)) {
24242                peer->contactha = ast_append_ha(v->name + 7, v->value, peer->contactha, &ha_error);
24243             }
24244             if (ha_error) {
24245                ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
24246             }
24247          } else if (!strcasecmp(v->name, "port")) {
24248             peer->portinuri = 1;
24249             if (!(port = port_str2int(v->value, 0))) {
24250                if (realtime) {
24251                   /* If stored as integer, could be 0 for some DBs (notably MySQL) */
24252                   peer->portinuri = 0;
24253                } else {
24254                   ast_log(LOG_WARNING, "Invalid peer port configuration at line %d : %s\n", v->lineno, v->value);
24255                }
24256             }
24257          } else if (!strcasecmp(v->name, "callingpres")) {
24258             peer->callingpres = ast_parse_caller_presentation(v->value);
24259             if (peer->callingpres == -1) {
24260                peer->callingpres = atoi(v->value);
24261             }
24262          } else if (!strcasecmp(v->name, "username") || !strcmp(v->name, "defaultuser")) {   /* "username" is deprecated */
24263             ast_string_field_set(peer, username, v->value);
24264             if (!strcasecmp(v->name, "username")) {
24265                if (deprecation_warning) {
24266                   ast_log(LOG_NOTICE, "The 'username' field for sip peers has been deprecated in favor of the term 'defaultuser'\n");
24267                   deprecation_warning = 0;
24268                }
24269                peer->deprecated_username = 1;
24270             }
24271          } else if (!strcasecmp(v->name, "language")) {
24272             ast_string_field_set(peer, language, v->value);
24273          } else if (!strcasecmp(v->name, "regexten")) {
24274             ast_string_field_set(peer, regexten, v->value);
24275          } else if (!strcasecmp(v->name, "callbackextension")) {
24276             ast_copy_string(callback, v->value, sizeof(callback));
24277          } else if (!strcasecmp(v->name, "amaflags")) {
24278             format = ast_cdr_amaflags2int(v->value);
24279             if (format < 0) {
24280                ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
24281             } else {
24282                peer->amaflags = format;
24283             }
24284          } else if (!strcasecmp(v->name, "accountcode")) {
24285             ast_string_field_set(peer, accountcode, v->value);
24286          } else if (!strcasecmp(v->name, "mohinterpret")) {
24287             ast_string_field_set(peer, mohinterpret, v->value);
24288          } else if (!strcasecmp(v->name, "mohsuggest")) {
24289             ast_string_field_set(peer, mohsuggest, v->value);
24290          } else if (!strcasecmp(v->name, "parkinglot")) {
24291             ast_string_field_set(peer, parkinglot, v->value);
24292          } else if (!strcasecmp(v->name, "mailbox")) {
24293             add_peer_mailboxes(peer, v->value);
24294          } else if (!strcasecmp(v->name, "hasvoicemail")) {
24295             /* People expect that if 'hasvoicemail' is set, that the mailbox will
24296              * be also set, even if not explicitly specified. */
24297             if (ast_true(v->value) && AST_LIST_EMPTY(&peer->mailboxes)) {
24298                add_peer_mailboxes(peer, name);
24299             }
24300          } else if (!strcasecmp(v->name, "subscribemwi")) {
24301             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
24302          } else if (!strcasecmp(v->name, "vmexten")) {
24303             ast_string_field_set(peer, vmexten, v->value);
24304          } else if (!strcasecmp(v->name, "callgroup")) {
24305             peer->callgroup = ast_get_group(v->value);
24306          } else if (!strcasecmp(v->name, "allowtransfer")) {
24307             peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
24308          } else if (!strcasecmp(v->name, "pickupgroup")) {
24309             peer->pickupgroup = ast_get_group(v->value);
24310          } else if (!strcasecmp(v->name, "allow")) {
24311             int error =  ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, TRUE);
24312             if (error) {
24313                ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
24314             }
24315          } else if (!strcasecmp(v->name, "disallow")) {
24316             int error =  ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, FALSE);
24317             if (error) {
24318                ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
24319             }
24320          } else if (!strcasecmp(v->name, "registertrying")) {
24321             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_REGISTERTRYING);
24322          } else if (!strcasecmp(v->name, "autoframing")) {
24323             peer->autoframing = ast_true(v->value);
24324          } else if (!strcasecmp(v->name, "rtptimeout")) {
24325             if ((sscanf(v->value, "%30d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
24326                ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
24327                peer->rtptimeout = global_rtptimeout;
24328             }
24329          } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
24330             if ((sscanf(v->value, "%30d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
24331                ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
24332                peer->rtpholdtimeout = global_rtpholdtimeout;
24333             }
24334          } else if (!strcasecmp(v->name, "rtpkeepalive")) {
24335             if ((sscanf(v->value, "%30d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
24336                ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d.  Using default.\n", v->value, v->lineno);
24337                peer->rtpkeepalive = global_rtpkeepalive;
24338             }
24339          } else if (!strcasecmp(v->name, "timert1")) {
24340             if ((sscanf(v->value, "%30d", &peer->timer_t1) != 1) || (peer->timer_t1 < 0)) {
24341                ast_log(LOG_WARNING, "'%s' is not a valid T1 time at line %d.  Using default.\n", v->value, v->lineno);
24342                peer->timer_t1 = global_t1;
24343             }
24344             /* Note that Timer B is dependent upon T1 and MUST NOT be lower
24345              * than T1 * 64, according to RFC 3261, Section 17.1.1.2 */
24346             if (peer->timer_b < peer->timer_t1 * 64) {
24347                peer->timer_b = peer->timer_t1 * 64;
24348             }
24349          } else if (!strcasecmp(v->name, "timerb")) {
24350             if ((sscanf(v->value, "%30d", &peer->timer_b) != 1) || (peer->timer_b < 0)) {
24351                ast_log(LOG_WARNING, "'%s' is not a valid Timer B time at line %d.  Using default.\n", v->value, v->lineno);
24352                peer->timer_b = global_timer_b;
24353             }
24354             if (peer->timer_b < peer->timer_t1 * 64) {
24355                static int warning = 0;
24356                if (warning++ % 20 == 0) {
24357                   ast_log(LOG_WARNING, "Timer B has been set lower than recommended. (RFC 3261, 17.1.1.2)\n");
24358                }
24359             }
24360          } else if (!strcasecmp(v->name, "setvar")) {
24361             peer->chanvars = add_var(v->value, peer->chanvars);
24362          } else if (!strcasecmp(v->name, "qualifyfreq")) {
24363             int i;
24364             if (sscanf(v->value, "%30d", &i) == 1) {
24365                peer->qualifyfreq = i * 1000;
24366             } else {
24367                ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
24368                peer->qualifyfreq = global_qualifyfreq;
24369             }
24370          } else if (!strcasecmp(v->name, "maxcallbitrate")) {
24371             peer->maxcallbitrate = atoi(v->value);
24372             if (peer->maxcallbitrate < 0) {
24373                peer->maxcallbitrate = default_maxcallbitrate;
24374             }
24375          } else if (!strcasecmp(v->name, "session-timers")) {
24376             int i = (int) str2stmode(v->value);
24377             if (i < 0) {
24378                ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
24379                peer->stimer.st_mode_oper = global_st_mode;
24380             } else {
24381                peer->stimer.st_mode_oper = i;
24382             }
24383          } else if (!strcasecmp(v->name, "session-expires")) {
24384             if (sscanf(v->value, "%30d", &peer->stimer.st_max_se) != 1) {
24385                ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
24386                peer->stimer.st_max_se = global_max_se;
24387             }
24388          } else if (!strcasecmp(v->name, "session-minse")) {
24389             if (sscanf(v->value, "%30d", &peer->stimer.st_min_se) != 1) {
24390                ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
24391                peer->stimer.st_min_se = global_min_se;
24392             }
24393             if (peer->stimer.st_min_se < 90) {
24394                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);
24395                peer->stimer.st_min_se = global_min_se;
24396             }
24397          } else if (!strcasecmp(v->name, "session-refresher")) {
24398             int i = (int) str2strefresher(v->value);
24399             if (i < 0) {
24400                ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
24401                peer->stimer.st_ref = global_st_refresher;
24402             } else {
24403                peer->stimer.st_ref = i;
24404             }
24405          }
24406       }
24407 
24408       /* These apply to devstate lookups */
24409       if (realtime && !strcasecmp(v->name, "lastms")) {
24410          sscanf(v->value, "%30d", &peer->lastms);
24411       } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
24412          inet_aton(v->value, &(peer->addr.sin_addr));
24413       } else if (realtime && !strcasecmp(v->name, "fullcontact")) {
24414          if (alt_fullcontact && !alt) {
24415             /* Reset, because the alternate also has a fullcontact and we
24416              * do NOT want the field value to be doubled. It might be
24417              * tempting to skip this, but the first table might not have
24418              * fullcontact and since we're here, we know that the alternate
24419              * absolutely does. */
24420             alt_fullcontact = 0;
24421             ast_str_reset(fullcontact);
24422          }
24423          /* Reconstruct field, because realtime separates our value at the ';' */
24424          if (fullcontact->used > 0) {
24425             ast_str_append(&fullcontact, 0, ";%s", v->value);
24426          } else {
24427             ast_str_set(&fullcontact, 0, "%s", v->value);
24428          }
24429       } else if (!strcasecmp(v->name, "qualify")) {
24430          if (!strcasecmp(v->value, "no")) {
24431             peer->maxms = 0;
24432          } else if (!strcasecmp(v->value, "yes")) {
24433             peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
24434          } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
24435             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);
24436             peer->maxms = 0;
24437          }
24438          if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->maxms > 0) {
24439             /* This would otherwise cause a network storm, where the
24440              * qualify response refreshes the peer from the database,
24441              * which in turn causes another qualify to be sent, ad
24442              * infinitum. */
24443             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);
24444             peer->maxms = 0;
24445          }
24446       } else if (!strcasecmp(v->name, "callcounter")) {
24447          peer->call_limit = ast_true(v->value) ? INT_MAX : 0;
24448       } else if (!strcasecmp(v->name, "call-limit")) {
24449          peer->call_limit = atoi(v->value);
24450          if (peer->call_limit < 0) {
24451             peer->call_limit = 0;
24452          }
24453       } else if (!strcasecmp(v->name, "busylevel")) {
24454          peer->busy_level = atoi(v->value);
24455          if (peer->busy_level < 0) {
24456             peer->busy_level = 0;
24457          }
24458       }
24459    }
24460 
24461    if (!devstate_only) {
24462       struct sip_mailbox *mailbox;
24463       AST_LIST_TRAVERSE_SAFE_BEGIN(&peer->mailboxes, mailbox, entry) {
24464          if (mailbox->delme) {
24465             AST_LIST_REMOVE_CURRENT(entry);
24466             destroy_mailbox(mailbox);
24467          }
24468       }
24469       AST_LIST_TRAVERSE_SAFE_END;
24470    }
24471 
24472    if (!peer->default_outbound_transport) {
24473       /* Set default set of transports */
24474       peer->transports = default_transports;
24475       /* Set default primary transport */
24476       peer->default_outbound_transport = default_primary_transport;
24477    }
24478 
24479    /* The default transport type set during build_peer should only replace the socket.type when...
24480     * 1. Registration is not present and the socket.type and default transport types are different.
24481     * 2. The socket.type is not an acceptable transport type after rebuilding peer.
24482     * 3. The socket.type is not set yet. */
24483    if (((peer->socket.type != peer->default_outbound_transport) && (peer->expire == -1)) ||
24484       !(peer->socket.type & peer->transports) || !(peer->socket.type)) {
24485 
24486       set_socket_transport(&peer->socket, peer->default_outbound_transport);
24487    }
24488 
24489    if (port && !realtime && peer->host_dynamic) {
24490       peer->defaddr.sin_port = htons(port);
24491    } else if (port) {
24492       peer->addr.sin_port = htons(port);
24493    }
24494 
24495    if (ast_str_strlen(fullcontact)) {
24496       ast_string_field_set(peer, fullcontact, ast_str_buffer(fullcontact));
24497       peer->rt_fromcontact = TRUE;
24498       /* We have a hostname in the fullcontact, but if we don't have an
24499        * address listed on the entry (or if it's 'dynamic'), then we need to
24500        * parse the entry to obtain the IP address, so a dynamic host can be
24501        * contacted immediately after reload (as opposed to waiting for it to
24502        * register once again). But if we have an address for this peer and NAT was
24503        * specified, use that address instead. */
24504       /* XXX May need to revisit the final argument; does the realtime DB store whether
24505        * the original contact was over TLS or not? XXX */
24506       if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) || !peer->addr.sin_addr.s_addr) {
24507          __set_address_from_contact(fullcontact->str, &peer->addr, 0);
24508       }
24509    }
24510 
24511    if (srvlookup && peer->dnsmgr == NULL) {
24512       char transport[MAXHOSTNAMELEN];
24513       char _srvlookup[MAXHOSTNAMELEN];
24514       char *params;
24515 
24516       ast_copy_string(_srvlookup, srvlookup, sizeof(_srvlookup));
24517       if ((params = strchr(_srvlookup, ';'))) {
24518          *params++ = '\0';
24519       }
24520 
24521       snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(peer->socket.type), get_srv_protocol(peer->socket.type));
24522 
24523       if (ast_dnsmgr_lookup(_srvlookup, &peer->addr, &peer->dnsmgr, sip_cfg.srvlookup && !peer->portinuri ? transport : NULL)) {
24524          ast_log(LOG_ERROR, "srvlookup failed for host: %s, on peer %s, removing peer\n", _srvlookup, peer->name);
24525          unref_peer(peer, "getting rid of a peer pointer");
24526          return NULL;
24527       }
24528 
24529       ast_string_field_set(peer, tohost, srvlookup);
24530       if (global_dynamic_exclude_static) {
24531          int err = 0;
24532          global_contact_ha = ast_append_ha("deny", (char *)ast_inet_ntoa(peer->addr.sin_addr), global_contact_ha, &err);
24533          if (err) {
24534             ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
24535          }
24536       }
24537    }
24538 
24539    if (!peer->addr.sin_port) {
24540       peer->addr.sin_port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
24541    }
24542    if (!peer->defaddr.sin_port) {
24543       peer->defaddr.sin_port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
24544    }
24545    if (!peer->socket.port) {
24546       peer->socket.port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
24547    }
24548 
24549    if (!sip_cfg.ignore_regexpire && peer->host_dynamic && realtime) {
24550       time_t nowtime = time(NULL);
24551 
24552       if ((nowtime - regseconds) > 0) {
24553          destroy_association(peer);
24554          memset(&peer->addr, 0, sizeof(peer->addr));
24555          peer->lastms = -1;
24556          ast_debug(1, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
24557       }
24558    }
24559 
24560    /* Startup regular pokes */
24561    if (!devstate_only && realtime && peer->lastms > 0) {
24562       ref_peer(peer, "schedule qualify");
24563       sip_poke_peer(peer, 0);
24564    }
24565 
24566    ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
24567    ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
24568    if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
24569       sip_cfg.allowsubscribe = TRUE;   /* No global ban any more */
24570    }
24571    if (peer->host_dynamic && !peer->is_realtime) {
24572       reg_source_db(peer);
24573    }
24574 
24575    /* If they didn't request that MWI is sent *only* on subscribe, go ahead and
24576     * subscribe to it now. */
24577    if (!devstate_only && !ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
24578       !AST_LIST_EMPTY(&peer->mailboxes)) {
24579       add_peer_mwi_subs(peer);
24580       /* Send MWI from the event cache only.  This is so we can send initial
24581        * MWI if app_voicemail got loaded before chan_sip.  If it is the other
24582        * way, then we will get events when app_voicemail gets loaded. */
24583       sip_send_mwi_to_peer(peer, NULL, 1);
24584    }
24585 
24586    peer->the_mark = 0;
24587 
24588    ast_free_ha(oldha);
24589    if (!ast_strlen_zero(callback)) { /* build string from peer info */
24590       char *reg_string;
24591       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) {
24592          ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
24593       } else if (reg_string) {
24594          sip_register(reg_string, 0); /* XXX TODO: count in registry_count */
24595          ast_free(reg_string);
24596       }
24597    }
24598    return peer;
24599 }
24600 
24601 static int peer_markall_func(void *device, void *arg, int flags)
24602 {
24603    struct sip_peer *peer = device;
24604    peer->the_mark = 1;
24605    return 0;
24606 }
24607 
24608 /*! \brief Re-read SIP.conf config file
24609 \note This function reloads all config data, except for
24610    active peers (with registrations). They will only
24611    change configuration data at restart, not at reload.
24612    SIP debug and recordhistory state will not change
24613  */
24614 static int reload_config(enum channelreloadreason reason)
24615 {
24616    struct ast_config *cfg, *ucfg;
24617    struct ast_variable *v;
24618    struct sip_peer *peer;
24619    char *cat, *stringp, *context, *oldregcontext;
24620    char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
24621    struct ast_flags dummy[2];
24622    struct ast_flags config_flags = { reason == CHANNEL_MODULE_LOAD ? 0 : ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? 0 : CONFIG_FLAG_FILEUNCHANGED };
24623    int auto_sip_domains = FALSE;
24624    struct sockaddr_in old_bindaddr = bindaddr;
24625    int registry_count = 0, peer_count = 0;
24626    time_t run_start, run_end;
24627    
24628    run_start = time(0);
24629    ast_unload_realtime("sipregs");     
24630    ast_unload_realtime("sippeers");
24631    cfg = ast_config_load(config, config_flags);
24632 
24633    /* We *must* have a config file otherwise stop immediately */
24634    if (!cfg) {
24635       ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
24636       return -1;
24637    } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
24638       ucfg = ast_config_load("users.conf", config_flags);
24639       if (ucfg == CONFIG_STATUS_FILEUNCHANGED) {
24640          return 1;
24641       } else if (ucfg == CONFIG_STATUS_FILEINVALID) {
24642          ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
24643          return 1;
24644       }
24645       /* Must reread both files, because one changed */
24646       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
24647       if ((cfg = ast_config_load(config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
24648          ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
24649          ast_config_destroy(ucfg);
24650          return 1;
24651       }
24652    } else if (cfg == CONFIG_STATUS_FILEINVALID) {
24653       ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
24654       return 1;
24655    } else {
24656       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
24657       if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
24658          ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
24659          ast_config_destroy(cfg);
24660          return 1;
24661       }
24662    }
24663 
24664    /* Initialize tcp sockets */
24665    memset(&sip_tcp_desc.local_address, 0, sizeof(sip_tcp_desc.local_address));
24666    memset(&sip_tls_desc.local_address, 0, sizeof(sip_tls_desc.local_address));
24667 
24668    ast_free_ha(global_contact_ha);
24669    global_contact_ha = NULL;
24670 
24671    default_tls_cfg.enabled = FALSE;    /* Default: Disable TLS */
24672 
24673    sip_tcp_desc.local_address.sin_port = htons(STANDARD_SIP_PORT);
24674    sip_tls_desc.local_address.sin_port = htons(STANDARD_TLS_PORT);
24675 
24676    if (reason != CHANNEL_MODULE_LOAD) {
24677       ast_debug(4, "--------------- SIP reload started\n");
24678 
24679       clear_realm_authentication(authl);
24680       clear_sip_domains();
24681       authl = NULL;
24682 
24683       /* First, destroy all outstanding registry calls */
24684       /* This is needed, since otherwise active registry entries will not be destroyed */
24685       ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {  /* regl is locked */
24686 
24687             ASTOBJ_RDLOCK(iterator); /* now regl is locked, and the object is also locked */
24688             if (iterator->call) {
24689                ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
24690                /* This will also remove references to the registry */
24691                dialog_unlink_all(iterator->call, TRUE, TRUE);
24692                iterator->call = dialog_unref(iterator->call, "remove iterator->call from registry traversal");
24693             }
24694             if (iterator->expire > -1) {
24695                AST_SCHED_DEL_UNREF(sched, iterator->expire, registry_unref(iterator, "reg ptr unref from reload config"));
24696             }
24697             if (iterator->timeout > -1) {
24698                AST_SCHED_DEL_UNREF(sched, iterator->timeout, registry_unref(iterator, "reg ptr unref from reload config"));
24699             }
24700             ASTOBJ_UNLOCK(iterator);
24701             
24702       } while(0));
24703 
24704       /* Then, actually destroy users and registry */
24705       ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
24706       ast_debug(4, "--------------- Done destroying registry list\n");
24707       ao2_t_callback(peers, OBJ_NODATA, peer_markall_func, NULL, "callback to mark all peers");
24708    }
24709    
24710    /* Reset certificate handling for TLS sessions */
24711    if (reason != CHANNEL_MODULE_LOAD) {
24712       ast_free(default_tls_cfg.certfile);
24713       ast_free(default_tls_cfg.cipher);
24714       ast_free(default_tls_cfg.cafile);
24715       ast_free(default_tls_cfg.capath);
24716    }
24717    default_tls_cfg.certfile = ast_strdup(AST_CERTFILE); /*XXX Not sure if this is useful */
24718    default_tls_cfg.cipher = ast_strdup("");
24719    default_tls_cfg.cafile = ast_strdup("");
24720    default_tls_cfg.capath = ast_strdup("");
24721 
24722    
24723    /* Initialize copy of current global_regcontext for later use in removing stale contexts */
24724    ast_copy_string(oldcontexts, global_regcontext, sizeof(oldcontexts));
24725    oldregcontext = oldcontexts;
24726 
24727    /* Clear all flags before setting default values */
24728    /* Preserve debugging settings for console */
24729    sipdebug &= sip_debug_console;
24730    ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
24731    ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
24732 
24733    /* Reset IP addresses  */
24734    memset(&bindaddr, 0, sizeof(bindaddr));
24735    memset(&stunaddr, 0, sizeof(stunaddr));
24736    memset(&internip, 0, sizeof(internip));
24737 
24738    /* Free memory for local network address mask */
24739    ast_free_ha(localaddr);
24740    memset(&localaddr, 0, sizeof(localaddr));
24741    memset(&externip, 0, sizeof(externip));
24742    memset(&default_prefs, 0 , sizeof(default_prefs));
24743    memset(&sip_cfg.outboundproxy, 0, sizeof(struct sip_proxy));
24744    sip_cfg.outboundproxy.ip.sin_port = htons(STANDARD_SIP_PORT);
24745    sip_cfg.outboundproxy.ip.sin_family = AF_INET;  /*!< Type of address: IPv4 */
24746    sip_cfg.outboundproxy.force = FALSE;      /*!< Don't force proxy usage, use route: headers */
24747    default_transports = 0;          /*!< Reset default transport to zero here, default value later on */
24748    default_primary_transport = 0;         /*!< Reset default primary transport to zero here, default value later on */
24749    ourport_tcp = STANDARD_SIP_PORT;
24750    ourport_tls = STANDARD_TLS_PORT;
24751    bindaddr.sin_port = htons(STANDARD_SIP_PORT);
24752    sip_cfg.srvlookup = DEFAULT_SRVLOOKUP;
24753    global_tos_sip = DEFAULT_TOS_SIP;
24754    global_tos_audio = DEFAULT_TOS_AUDIO;
24755    global_tos_video = DEFAULT_TOS_VIDEO;
24756    global_tos_text = DEFAULT_TOS_TEXT;
24757    global_cos_sip = DEFAULT_COS_SIP;
24758    global_cos_audio = DEFAULT_COS_AUDIO;
24759    global_cos_video = DEFAULT_COS_VIDEO;
24760    global_cos_text = DEFAULT_COS_TEXT;
24761 
24762    externhost[0] = '\0';         /* External host name (for behind NAT DynDNS support) */
24763    externexpire = 0;       /* Expiration for DNS re-issuing */
24764    externrefresh = 10;
24765 
24766    /* Reset channel settings to default before re-configuring */
24767    sip_cfg.allow_external_domains = DEFAULT_ALLOW_EXT_DOM;           /* Allow external invites */
24768    global_regcontext[0] = '\0';
24769    sip_cfg.regextenonqualify = DEFAULT_REGEXTENONQUALIFY;
24770    sip_cfg.notifyringing = DEFAULT_NOTIFYRINGING;
24771    sip_cfg.notifycid = DEFAULT_NOTIFYCID;
24772    sip_cfg.notifyhold = FALSE;      /*!< Keep track of hold status for a peer */
24773    sip_cfg.directrtpsetup = FALSE;     /* Experimental feature, disabled by default */
24774    sip_cfg.alwaysauthreject = DEFAULT_ALWAYSAUTHREJECT;
24775    sip_cfg.allowsubscribe = FALSE;
24776    snprintf(global_useragent, sizeof(global_useragent), "%s %s", DEFAULT_USERAGENT, ast_get_version());
24777    snprintf(global_sdpsession, sizeof(global_sdpsession), "%s %s", DEFAULT_SDPSESSION, ast_get_version());
24778    snprintf(global_sdpowner, sizeof(global_sdpowner), "%s", DEFAULT_SDPOWNER);
24779    global_prematuremediafilter = TRUE;
24780    ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
24781    ast_copy_string(sip_cfg.realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM), sizeof(sip_cfg.realm));
24782    ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
24783    sip_cfg.compactheaders = DEFAULT_COMPACTHEADERS;
24784    global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
24785    global_regattempts_max = 0;
24786    sip_cfg.pedanticsipchecking = DEFAULT_PEDANTIC;
24787    sip_cfg.autocreatepeer = DEFAULT_AUTOCREATEPEER;
24788    global_autoframing = 0;
24789    sip_cfg.allowguest = DEFAULT_ALLOWGUEST;
24790    global_callcounter = DEFAULT_CALLCOUNTER;
24791    global_match_auth_username = FALSE;    /*!< Match auth username if available instead of From: Default off. */
24792    global_rtptimeout = 0;
24793    global_rtpholdtimeout = 0;
24794    global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
24795    sip_cfg.allowtransfer = TRANSFER_OPENFORALL; /* Merrily accept all transfers by default */
24796    sip_cfg.rtautoclear = 120;
24797    ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE);   /* Default for all devices: TRUE */
24798    ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP);     /* Default for all devices: TRUE */
24799    sip_cfg.peer_rtupdate = TRUE;
24800    global_dynamic_exclude_static = 0;  /* Exclude static peers */
24801 
24802    /* Session-Timers */
24803    global_st_mode = SESSION_TIMER_MODE_ACCEPT;    
24804    global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
24805    global_min_se  = DEFAULT_MIN_SE;
24806    global_max_se  = DEFAULT_MAX_SE;
24807 
24808    /* Peer poking settings */
24809    global_qualify_gap = DEFAULT_QUALIFY_GAP;
24810    global_qualify_peers = DEFAULT_QUALIFY_PEERS;
24811 
24812    /* Initialize some reasonable defaults at SIP reload (used both for channel and as default for devices */
24813    ast_copy_string(sip_cfg.default_context, DEFAULT_CONTEXT, sizeof(sip_cfg.default_context));
24814    sip_cfg.default_subscribecontext[0] = '\0';
24815    default_language[0] = '\0';
24816    default_fromdomain[0] = '\0';
24817    default_qualify = DEFAULT_QUALIFY;
24818    default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
24819    ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
24820    ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
24821    ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
24822    ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833);        /*!< Default DTMF setting: RFC2833 */
24823    ast_set_flag(&global_flags[0], SIP_NAT_RFC3581);         /*!< NAT support if requested by device with rport */
24824    ast_set_flag(&global_flags[0], SIP_DIRECT_MEDIA);        /*!< Allow re-invites */
24825    ast_set_flag(&global_flags[1], SIP_PAGE2_FORWARD_LOOP_DETECTED); /*!< Set up call forward on 482 Loop Detected */
24826 
24827    /* Debugging settings, always default to off */
24828    dumphistory = FALSE;
24829    recordhistory = FALSE;
24830    sipdebug &= ~sip_debug_config;
24831 
24832    /* Misc settings for the channel */
24833    global_relaxdtmf = FALSE;
24834    sip_cfg.callevents = DEFAULT_CALLEVENTS;
24835    global_authfailureevents = FALSE;
24836    global_t1 = DEFAULT_TIMER_T1;
24837    global_timer_b = 64 * DEFAULT_TIMER_T1;
24838    global_t1min = DEFAULT_T1MIN;
24839    global_qualifyfreq = DEFAULT_QUALIFYFREQ;
24840    global_t38_maxdatagram = -1;
24841    global_shrinkcallerid = 1;
24842 
24843    sip_cfg.matchexterniplocally = DEFAULT_MATCHEXTERNIPLOCALLY;
24844 
24845    /* Copy the default jb config over global_jbconf */
24846    memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
24847 
24848    ast_clear_flag(&global_flags[1], SIP_PAGE2_FAX_DETECT);
24849    ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
24850    ast_clear_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT);
24851    ast_clear_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION);
24852 
24853 
24854    /* Read the [general] config section of sip.conf (or from realtime config) */
24855    for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
24856       if (handle_common_options(&global_flags[0], &dummy[0], v))
24857          continue;
24858       if (handle_t38_options(&global_flags[0], &dummy[0], v, &global_t38_maxdatagram)) {
24859          continue;
24860       }
24861       /* handle jb conf */
24862       if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
24863          continue;
24864 
24865       if (!strcasecmp(v->name, "context")) {
24866          ast_copy_string(sip_cfg.default_context, v->value, sizeof(sip_cfg.default_context));
24867       } else if (!strcasecmp(v->name, "subscribecontext")) {
24868          ast_copy_string(sip_cfg.default_subscribecontext, v->value, sizeof(sip_cfg.default_subscribecontext));
24869       } else if (!strcasecmp(v->name, "callcounter")) {
24870          global_callcounter = ast_true(v->value) ? 1 : 0;
24871       } else if (!strcasecmp(v->name, "allowguest")) {
24872          sip_cfg.allowguest = ast_true(v->value) ? 1 : 0;
24873       } else if (!strcasecmp(v->name, "realm")) {
24874          ast_copy_string(sip_cfg.realm, v->value, sizeof(sip_cfg.realm));
24875       } else if (!strcasecmp(v->name, "useragent")) {
24876          ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
24877          ast_debug(1, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
24878       } else if (!strcasecmp(v->name, "sdpsession")) {
24879          ast_copy_string(global_sdpsession, v->value, sizeof(global_sdpsession));
24880       } else if (!strcasecmp(v->name, "sdpowner")) {
24881          /* Field cannot contain spaces */
24882          if (!strstr(v->value, " "))
24883             ast_copy_string(global_sdpowner, v->value, sizeof(global_sdpowner));
24884          else
24885             ast_log(LOG_WARNING, "'%s' must not contain spaces at line %d.  Using default.\n", v->value, v->lineno);
24886       } else if (!strcasecmp(v->name, "allowtransfer")) {
24887          sip_cfg.allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
24888       } else if (!strcasecmp(v->name, "rtcachefriends")) {
24889          ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);   
24890       } else if (!strcasecmp(v->name, "rtsavesysname")) {
24891          sip_cfg.rtsave_sysname = ast_true(v->value);
24892       } else if (!strcasecmp(v->name, "rtupdate")) {
24893          sip_cfg.peer_rtupdate = ast_true(v->value);
24894       } else if (!strcasecmp(v->name, "ignoreregexpire")) {
24895          sip_cfg.ignore_regexpire = ast_true(v->value);
24896       } else if (!strcasecmp(v->name, "timert1")) {
24897          /* Defaults to 500ms, but RFC 3261 states that it is recommended
24898           * for the value to be set higher, though a lower value is only
24899           * allowed on private networks unconnected to the Internet. */
24900          global_t1 = atoi(v->value);
24901          /* Note that timer B is dependent on the value of T1 */
24902          global_timer_b = global_t1 * 64;
24903       } else if (!strcasecmp(v->name, "t1min")) {
24904          global_t1min = atoi(v->value);
24905       } else if (!strcasecmp(v->name, "transport") && !ast_strlen_zero(v->value)) {
24906          char *val = ast_strdupa(v->value);
24907          char *trans;
24908 
24909          while ((trans = strsep(&val, ","))) {
24910             trans = ast_skip_blanks(trans);
24911 
24912             if (!strncasecmp(trans, "udp", 3)) 
24913                default_transports |= SIP_TRANSPORT_UDP;
24914             else if (!strncasecmp(trans, "tcp", 3))
24915                default_transports |= SIP_TRANSPORT_TCP;
24916             else if (!strncasecmp(trans, "tls", 3))
24917                default_transports |= SIP_TRANSPORT_TLS;
24918             else
24919                ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
24920             if (default_primary_transport == 0) {
24921                default_primary_transport = default_transports;
24922             }
24923          }
24924       } else if (!strcasecmp(v->name, "tcpenable")) {
24925          sip_tcp_desc.local_address.sin_family = ast_false(v->value) ? 0 : AF_INET;
24926          ast_debug(2, "Enabling TCP socket for listening\n");
24927       } else if (!strcasecmp(v->name, "tcpbindaddr")) {
24928          int family = sip_tcp_desc.local_address.sin_family;
24929          if (ast_parse_arg(v->value, PARSE_INADDR, &sip_tcp_desc.local_address))
24930             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n", v->name, v->value, v->lineno, config);
24931          sip_tcp_desc.local_address.sin_family = family;
24932          ast_debug(2, "Setting TCP socket address to %s\n", v->value);
24933       } else if (!strcasecmp(v->name, "tlsenable")) {
24934          default_tls_cfg.enabled = ast_true(v->value) ? TRUE : FALSE;
24935          sip_tls_desc.local_address.sin_family = AF_INET;
24936       } else if (!strcasecmp(v->name, "tlscertfile")) {
24937          ast_free(default_tls_cfg.certfile);
24938          default_tls_cfg.certfile = ast_strdup(v->value);
24939       } else if (!strcasecmp(v->name, "tlscipher")) {
24940          ast_free(default_tls_cfg.cipher);
24941          default_tls_cfg.cipher = ast_strdup(v->value);
24942       } else if (!strcasecmp(v->name, "tlscafile")) {
24943          ast_free(default_tls_cfg.cafile);
24944          default_tls_cfg.cafile = ast_strdup(v->value);
24945       } else if (!strcasecmp(v->name, "tlscapath")) {
24946          ast_free(default_tls_cfg.capath);
24947          default_tls_cfg.capath = ast_strdup(v->value);
24948       } else if (!strcasecmp(v->name, "tlsverifyclient")) {
24949          ast_set2_flag(&default_tls_cfg.flags, ast_true(v->value), AST_SSL_VERIFY_CLIENT);   
24950       } else if (!strcasecmp(v->name, "tlsdontverifyserver")) {
24951          ast_set2_flag(&default_tls_cfg.flags, ast_true(v->value), AST_SSL_DONT_VERIFY_SERVER); 
24952       } else if (!strcasecmp(v->name, "tlsbindaddr")) {
24953          if (ast_parse_arg(v->value, PARSE_INADDR, &sip_tls_desc.local_address))
24954             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n", v->name, v->value, v->lineno, config);
24955       } else if (!strcasecmp(v->name, "dynamic_exclude_static") || !strcasecmp(v->name, "dynamic_excludes_static")) {
24956          global_dynamic_exclude_static = ast_true(v->value);
24957       } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
24958          int ha_error = 0;
24959          global_contact_ha = ast_append_ha(v->name + 7, v->value, global_contact_ha, &ha_error);
24960          if (ha_error) {
24961             ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
24962          }
24963       } else if (!strcasecmp(v->name, "rtautoclear")) {
24964          int i = atoi(v->value);
24965          if (i > 0)
24966             sip_cfg.rtautoclear = i;
24967          else
24968             i = 0;
24969          ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
24970       } else if (!strcasecmp(v->name, "usereqphone")) {
24971          ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);   
24972       } else if (!strcasecmp(v->name, "prematuremedia")) {
24973          global_prematuremediafilter = ast_true(v->value);
24974       } else if (!strcasecmp(v->name, "relaxdtmf")) {
24975          global_relaxdtmf = ast_true(v->value);
24976       } else if (!strcasecmp(v->name, "vmexten")) {
24977          ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
24978       } else if (!strcasecmp(v->name, "rtptimeout")) {
24979          if ((sscanf(v->value, "%30d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
24980             ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
24981             global_rtptimeout = 0;
24982          }
24983       } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
24984          if ((sscanf(v->value, "%30d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
24985             ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
24986             global_rtpholdtimeout = 0;
24987          }
24988       } else if (!strcasecmp(v->name, "rtpkeepalive")) {
24989          if ((sscanf(v->value, "%30d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
24990             ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d.  Using default.\n", v->value, v->lineno);
24991             global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
24992          }
24993       } else if (!strcasecmp(v->name, "compactheaders")) {
24994          sip_cfg.compactheaders = ast_true(v->value);
24995       } else if (!strcasecmp(v->name, "notifymimetype")) {
24996          ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
24997       } else if (!strcasecmp(v->name, "directrtpsetup")) {
24998          sip_cfg.directrtpsetup = ast_true(v->value);
24999       } else if (!strcasecmp(v->name, "notifyringing")) {
25000          sip_cfg.notifyringing = ast_true(v->value);
25001       } else if (!strcasecmp(v->name, "notifyhold")) {
25002          sip_cfg.notifyhold = ast_true(v->value);
25003       } else if (!strcasecmp(v->name, "notifycid")) {
25004          if (!strcasecmp(v->value, "ignore-context")) {
25005             sip_cfg.notifycid = IGNORE_CONTEXT;
25006          } else {
25007             sip_cfg.notifycid = ast_true(v->value);
25008          }
25009       } else if (!strcasecmp(v->name, "alwaysauthreject")) {
25010          sip_cfg.alwaysauthreject = ast_true(v->value);
25011       } else if (!strcasecmp(v->name, "mohinterpret")) {
25012          ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
25013       } else if (!strcasecmp(v->name, "mohsuggest")) {
25014          ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
25015       } else if (!strcasecmp(v->name, "language")) {
25016          ast_copy_string(default_language, v->value, sizeof(default_language));
25017       } else if (!strcasecmp(v->name, "regcontext")) {
25018          ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
25019          stringp = newcontexts;
25020          /* Let's remove any contexts that are no longer defined in regcontext */
25021          cleanup_stale_contexts(stringp, oldregcontext);
25022          /* Create contexts if they don't exist already */
25023          while ((context = strsep(&stringp, "&"))) {
25024             ast_copy_string(used_context, context, sizeof(used_context));
25025             ast_context_find_or_create(NULL, NULL, context, "SIP");
25026          }
25027          ast_copy_string(global_regcontext, v->value, sizeof(global_regcontext));
25028       } else if (!strcasecmp(v->name, "regextenonqualify")) {
25029          sip_cfg.regextenonqualify = ast_true(v->value);
25030       } else if (!strcasecmp(v->name, "callerid")) {
25031          ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
25032       } else if (!strcasecmp(v->name, "fromdomain")) {
25033          ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
25034       } else if (!strcasecmp(v->name, "outboundproxy")) {
25035          int portnum;
25036          char *tok, *proxyname;
25037 
25038          if (ast_strlen_zero(v->value)) {
25039             ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf.", v->lineno);
25040             continue;
25041          }
25042 
25043          tok = ast_skip_blanks(strtok(ast_strdupa(v->value), ","));
25044 
25045          sip_parse_host(tok, v->lineno, &proxyname, &portnum, &sip_cfg.outboundproxy.transport);
25046 
25047          sip_cfg.outboundproxy.ip.sin_port = htons(portnum);
25048    
25049          if ((tok = strtok(NULL, ","))) {
25050             sip_cfg.outboundproxy.force = !strncasecmp(ast_skip_blanks(tok), "force", 5);
25051          } else {
25052             sip_cfg.outboundproxy.force = FALSE;
25053          }
25054 
25055          if (ast_strlen_zero(proxyname)) {
25056             ast_log(LOG_WARNING, "you must specify a name for the outboundproxy on line %d of sip.conf.", v->lineno);
25057             sip_cfg.outboundproxy.name[0] = '\0';
25058             continue;
25059          }
25060 
25061          ast_copy_string(sip_cfg.outboundproxy.name, proxyname, sizeof(sip_cfg.outboundproxy.name));
25062 
25063          proxy_update(&sip_cfg.outboundproxy);
25064       } else if (!strcasecmp(v->name, "autocreatepeer")) {
25065          sip_cfg.autocreatepeer = ast_true(v->value);
25066       } else if (!strcasecmp(v->name, "match_auth_username")) {
25067          global_match_auth_username = ast_true(v->value);
25068       } else if (!strcasecmp(v->name, "srvlookup")) {
25069          sip_cfg.srvlookup = ast_true(v->value);
25070       } else if (!strcasecmp(v->name, "pedantic")) {
25071          sip_cfg.pedanticsipchecking = ast_true(v->value);
25072       } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
25073          max_expiry = atoi(v->value);
25074          if (max_expiry < 1)
25075             max_expiry = DEFAULT_MAX_EXPIRY;
25076       } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
25077          min_expiry = atoi(v->value);
25078          if (min_expiry < 1)
25079             min_expiry = DEFAULT_MIN_EXPIRY;
25080       } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
25081          default_expiry = atoi(v->value);
25082          if (default_expiry < 1)
25083             default_expiry = DEFAULT_DEFAULT_EXPIRY;
25084       } else if (!strcasecmp(v->name, "mwiexpiry") || !strcasecmp(v->name, "mwiexpirey")) {
25085          mwi_expiry = atoi(v->value);
25086          if (mwi_expiry < 1)
25087             mwi_expiry = DEFAULT_MWI_EXPIRY;
25088       } else if (!strcasecmp(v->name, "sipdebug")) {
25089          if (ast_true(v->value))
25090             sipdebug |= sip_debug_config;
25091       } else if (!strcasecmp(v->name, "dumphistory")) {
25092          dumphistory = ast_true(v->value);
25093       } else if (!strcasecmp(v->name, "recordhistory")) {
25094          recordhistory = ast_true(v->value);
25095       } else if (!strcasecmp(v->name, "registertimeout")) {
25096          global_reg_timeout = atoi(v->value);
25097          if (global_reg_timeout < 1)
25098             global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
25099       } else if (!strcasecmp(v->name, "registerattempts")) {
25100          global_regattempts_max = atoi(v->value);
25101       } else if (!strcasecmp(v->name, "stunaddr")) {
25102          stunaddr.sin_port = htons(3478);
25103          if (ast_parse_arg(v->value, PARSE_INADDR, &stunaddr))
25104             ast_log(LOG_WARNING, "Invalid STUN server address: %s\n", v->value);
25105          externexpire = time(NULL);
25106       } else if (!strcasecmp(v->name, "bindaddr") || !strcasecmp(v->name, "udpbindaddr")) {
25107          if (ast_parse_arg(v->value, PARSE_INADDR, &bindaddr))
25108             ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
25109       } else if (!strcasecmp(v->name, "localnet")) {
25110          struct ast_ha *na;
25111          int ha_error = 0;
25112 
25113          if (!(na = ast_append_ha("d", v->value, localaddr, &ha_error)))
25114             ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
25115          else
25116             localaddr = na;
25117          if (ha_error)
25118             ast_log(LOG_ERROR, "Bad localnet configuration value line %d : %s\n", v->lineno, v->value);
25119       } else if (!strcasecmp(v->name, "externip")) {
25120          if (ast_parse_arg(v->value, PARSE_INADDR, &externip))
25121             ast_log(LOG_WARNING, "Invalid address for externip keyword: %s\n", v->value);
25122          externexpire = 0;
25123          /* If no port was specified use the value of bindport */
25124          if (!externip.sin_port)
25125             externip.sin_port = bindaddr.sin_port;
25126       } else if (!strcasecmp(v->name, "externhost")) {
25127          ast_copy_string(externhost, v->value, sizeof(externhost));
25128          if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
25129             ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
25130          externexpire = time(NULL);
25131          /* If no port was specified use the value of bindport */
25132          if (!externip.sin_port)
25133             externip.sin_port = bindaddr.sin_port;
25134       } else if (!strcasecmp(v->name, "externrefresh")) {
25135          if (sscanf(v->value, "%30d", &externrefresh) != 1) {
25136             ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
25137             externrefresh = 10;
25138          }
25139       } else if (!strcasecmp(v->name, "allow")) {
25140          int error =  ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, TRUE);
25141          if (error)
25142             ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
25143       } else if (!strcasecmp(v->name, "disallow")) {
25144          int error =  ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, FALSE);
25145          if (error)
25146             ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
25147       } else if (!strcasecmp(v->name, "autoframing")) {
25148          global_autoframing = ast_true(v->value);
25149       } else if (!strcasecmp(v->name, "allowexternaldomains")) {
25150          sip_cfg.allow_external_domains = ast_true(v->value);
25151       } else if (!strcasecmp(v->name, "autodomain")) {
25152          auto_sip_domains = ast_true(v->value);
25153       } else if (!strcasecmp(v->name, "domain")) {
25154          char *domain = ast_strdupa(v->value);
25155          char *cntx = strchr(domain, ',');
25156 
25157          if (cntx)
25158             *cntx++ = '\0';
25159 
25160          if (ast_strlen_zero(cntx))
25161             ast_debug(1, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
25162          if (ast_strlen_zero(domain))
25163             ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
25164          else
25165             add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, cntx ? ast_strip(cntx) : "");
25166       } else if (!strcasecmp(v->name, "register")) {
25167          if (sip_register(v->value, v->lineno) == 0)
25168             registry_count++;
25169       } else if (!strcasecmp(v->name, "mwi")) {
25170          sip_subscribe_mwi(v->value, v->lineno);
25171       } else if (!strcasecmp(v->name, "tos_sip")) {
25172          if (ast_str2tos(v->value, &global_tos_sip))
25173             ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, refer to QoS documentation\n", v->lineno);
25174       } else if (!strcasecmp(v->name, "tos_audio")) {
25175          if (ast_str2tos(v->value, &global_tos_audio))
25176             ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, refer to QoS documentation\n", v->lineno);
25177       } else if (!strcasecmp(v->name, "tos_video")) {
25178          if (ast_str2tos(v->value, &global_tos_video))
25179             ast_log(LOG_WARNING, "Invalid tos_video value at line %d, refer to QoS documentation\n", v->lineno);
25180       } else if (!strcasecmp(v->name, "tos_text")) {
25181          if (ast_str2tos(v->value, &global_tos_text))
25182             ast_log(LOG_WARNING, "Invalid tos_text value at line %d, refer to QoS documentation\n", v->lineno);
25183       } else if (!strcasecmp(v->name, "cos_sip")) {
25184          if (ast_str2cos(v->value, &global_cos_sip))
25185             ast_log(LOG_WARNING, "Invalid cos_sip value at line %d, refer to QoS documentation\n", v->lineno);
25186       } else if (!strcasecmp(v->name, "cos_audio")) {
25187          if (ast_str2cos(v->value, &global_cos_audio))
25188             ast_log(LOG_WARNING, "Invalid cos_audio value at line %d, refer to QoS documentation\n", v->lineno);
25189       } else if (!strcasecmp(v->name, "cos_video")) {
25190          if (ast_str2cos(v->value, &global_cos_video))
25191             ast_log(LOG_WARNING, "Invalid cos_video value at line %d, refer to QoS documentation\n", v->lineno);
25192       } else if (!strcasecmp(v->name, "cos_text")) {
25193          if (ast_str2cos(v->value, &global_cos_text))
25194             ast_log(LOG_WARNING, "Invalid cos_text value at line %d, refer to QoS documentation\n", v->lineno);
25195       } else if (!strcasecmp(v->name, "bindport")) {
25196          int i;
25197          if (sscanf(v->value, "%5d", &i) == 1) {
25198             bindaddr.sin_port = htons(i);
25199          } else {
25200             ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
25201          }
25202       } else if (!strcasecmp(v->name, "qualify")) {
25203          if (!strcasecmp(v->value, "no")) {
25204             default_qualify = 0;
25205          } else if (!strcasecmp(v->value, "yes")) {
25206             default_qualify = DEFAULT_MAXMS;
25207          } else if (sscanf(v->value, "%30d", &default_qualify) != 1) {
25208             ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
25209             default_qualify = 0;
25210          }
25211       } else if (!strcasecmp(v->name, "qualifyfreq")) {
25212          int i;
25213          if (sscanf(v->value, "%30d", &i) == 1)
25214             global_qualifyfreq = i * 1000;
25215          else {
25216             ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
25217             global_qualifyfreq = DEFAULT_QUALIFYFREQ;
25218          }
25219       } else if (!strcasecmp(v->name, "callevents")) {
25220          sip_cfg.callevents = ast_true(v->value);
25221       } else if (!strcasecmp(v->name, "authfailureevents")) {
25222          global_authfailureevents = ast_true(v->value);
25223       } else if (!strcasecmp(v->name, "maxcallbitrate")) {
25224          default_maxcallbitrate = atoi(v->value);
25225          if (default_maxcallbitrate < 0)
25226             default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
25227       } else if (!strcasecmp(v->name, "matchexterniplocally")) {
25228          sip_cfg.matchexterniplocally = ast_true(v->value);
25229       } else if (!strcasecmp(v->name, "session-timers")) {
25230          int i = (int) str2stmode(v->value); 
25231          if (i < 0) {
25232             ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
25233             global_st_mode = SESSION_TIMER_MODE_ACCEPT;
25234          } else {
25235             global_st_mode = i;
25236          }
25237       } else if (!strcasecmp(v->name, "session-expires")) {
25238          if (sscanf(v->value, "%30d", &global_max_se) != 1) {
25239             ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
25240             global_max_se = DEFAULT_MAX_SE;
25241          } 
25242       } else if (!strcasecmp(v->name, "session-minse")) {
25243          if (sscanf(v->value, "%30d", &global_min_se) != 1) {
25244             ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
25245             global_min_se = DEFAULT_MIN_SE;
25246          } 
25247          if (global_min_se < 90) {
25248             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);
25249             global_min_se = DEFAULT_MIN_SE;
25250          } 
25251       } else if (!strcasecmp(v->name, "session-refresher")) {
25252          int i = (int) str2strefresher(v->value); 
25253          if (i < 0) {
25254             ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
25255             global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
25256          } else {
25257             global_st_refresher = i;
25258          }
25259       } else if (!strcasecmp(v->name, "qualifygap")) {
25260          if (sscanf(v->value, "%30d", &global_qualify_gap) != 1) {
25261             ast_log(LOG_WARNING, "Invalid qualifygap '%s' at line %d of %s\n", v->value, v->lineno, config);
25262             global_qualify_gap = DEFAULT_QUALIFY_GAP;
25263          }
25264       } else if (!strcasecmp(v->name, "qualifypeers")) {
25265          if (sscanf(v->value, "%30d", &global_qualify_peers) != 1) {
25266             ast_log(LOG_WARNING, "Invalid pokepeers '%s' at line %d of %s\n", v->value, v->lineno, config);
25267             global_qualify_peers = DEFAULT_QUALIFY_PEERS;
25268          }
25269       } else if (!strcasecmp(v->name, "shrinkcallerid")) {
25270          if (ast_true(v->value)) {
25271             global_shrinkcallerid = 1;
25272          } else if (ast_false(v->value)) {
25273             global_shrinkcallerid = 0;
25274          } else {
25275             ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
25276          }
25277       }
25278    }
25279 
25280    if (!sip_cfg.allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
25281       ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
25282       sip_cfg.allow_external_domains = 1;
25283    }
25284    /* If not configured, set default transports */
25285    if (default_transports == 0) {
25286       default_transports = default_primary_transport = SIP_TRANSPORT_UDP;
25287    }
25288    
25289    /* Build list of authentication to various SIP realms, i.e. service providers */
25290    for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
25291       /* Format for authentication is auth = username:password@realm */
25292       if (!strcasecmp(v->name, "auth"))
25293          authl = add_realm_authentication(authl, v->value, v->lineno);
25294    }
25295 
25296    /* Set UDP address and open socket */
25297    bindaddr.sin_family = AF_INET;
25298    internip = bindaddr;
25299    if (ast_find_ourip(&internip.sin_addr, bindaddr)) {
25300       ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
25301       ast_config_destroy(cfg);
25302       return 0;
25303    }
25304 
25305    ast_mutex_lock(&netlock);
25306    if ((sipsock > -1) && (memcmp(&old_bindaddr, &bindaddr, sizeof(struct sockaddr_in)))) {
25307       close(sipsock);
25308       sipsock = -1;
25309    }
25310    if (sipsock < 0) {
25311       sipsock = socket(AF_INET, SOCK_DGRAM, 0);
25312       if (sipsock < 0) {
25313          ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
25314          ast_config_destroy(cfg);
25315          ast_mutex_unlock(&netlock);
25316          return -1;
25317       } else {
25318          /* Allow SIP clients on the same host to access us: */
25319          const int reuseFlag = 1;
25320 
25321          setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
25322                (const char*)&reuseFlag,
25323                sizeof reuseFlag);
25324 
25325          ast_enable_packet_fragmentation(sipsock);
25326 
25327          if (bind(sipsock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
25328             ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
25329             ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
25330             strerror(errno));
25331             close(sipsock);
25332             sipsock = -1;
25333          } else {
25334             ast_verb(2, "SIP Listening on %s:%d\n",
25335                   ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
25336             ast_netsock_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
25337          }
25338       }
25339    } else {
25340       ast_netsock_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
25341    }
25342    if (stunaddr.sin_addr.s_addr != 0) {
25343       ast_debug(1, "stun to %s:%d\n",
25344          ast_inet_ntoa(stunaddr.sin_addr) , ntohs(stunaddr.sin_port));
25345       ast_stun_request(sipsock, &stunaddr,
25346          NULL, &externip);
25347       ast_debug(1, "STUN sees us at %s:%d\n", 
25348          ast_inet_ntoa(externip.sin_addr) , ntohs(externip.sin_port));
25349    }
25350    ast_mutex_unlock(&netlock);
25351 
25352    /* Start TCP server */
25353    ast_tcptls_server_start(&sip_tcp_desc);
25354    if (sip_tcp_desc.accept_fd == -1 &&  sip_tcp_desc.local_address.sin_family == AF_INET) {
25355       /* TCP server start failed. Tell the admin */
25356       ast_log(LOG_ERROR, "SIP TCP Server start failed. Not listening on TCP socket.\n");
25357       sip_tcp_desc.local_address.sin_family = 0;
25358    } else {
25359       ast_debug(2, "SIP TCP server started\n");
25360    }
25361 
25362    /* Start TLS server if needed */
25363    memcpy(sip_tls_desc.tls_cfg, &default_tls_cfg, sizeof(default_tls_cfg));
25364 
25365    if (ast_ssl_setup(sip_tls_desc.tls_cfg)) {
25366       ast_tcptls_server_start(&sip_tls_desc);
25367       if (default_tls_cfg.enabled && sip_tls_desc.accept_fd == -1) {
25368          ast_log(LOG_ERROR, "TLS Server start failed. Not listening on TLS socket.\n");
25369          sip_tls_desc.tls_cfg = NULL;
25370       }
25371    } else if (sip_tls_desc.tls_cfg->enabled) {
25372       sip_tls_desc.tls_cfg = NULL;
25373       ast_log(LOG_WARNING, "SIP TLS server did not load because of errors.\n");
25374    }
25375 
25376    if (ucfg) {
25377       struct ast_variable *gen;
25378       int genhassip, genregistersip;
25379       const char *hassip, *registersip;
25380       
25381       genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
25382       genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
25383       gen = ast_variable_browse(ucfg, "general");
25384       cat = ast_category_browse(ucfg, NULL);
25385       while (cat) {
25386          if (strcasecmp(cat, "general")) {
25387             hassip = ast_variable_retrieve(ucfg, cat, "hassip");
25388             registersip = ast_variable_retrieve(ucfg, cat, "registersip");
25389             if (ast_true(hassip) || (!hassip && genhassip)) {
25390                peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0, 0);
25391                if (peer) {
25392                   /* user.conf entries are always of type friend */
25393                   peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
25394                   ao2_t_link(peers, peer, "link peer into peer table");
25395                   if ((peer->type & SIP_TYPE_PEER) && peer->addr.sin_addr.s_addr) {
25396                      ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
25397                   }
25398                   
25399                   unref_peer(peer, "unref_peer: from reload_config");
25400                   peer_count++;
25401                }
25402             }
25403             if (ast_true(registersip) || (!registersip && genregistersip)) {
25404                char tmp[256];
25405                const char *host = ast_variable_retrieve(ucfg, cat, "host");
25406                const char *username = ast_variable_retrieve(ucfg, cat, "username");
25407                const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
25408                const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
25409                const char *authuser = ast_variable_retrieve(ucfg, cat, "authuser");
25410                if (!host)
25411                   host = ast_variable_retrieve(ucfg, "general", "host");
25412                if (!username)
25413                   username = ast_variable_retrieve(ucfg, "general", "username");
25414                if (!secret)
25415                   secret = ast_variable_retrieve(ucfg, "general", "secret");
25416                if (!contact)
25417                   contact = "s";
25418                if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
25419                   if (!ast_strlen_zero(secret)) {
25420                      if (!ast_strlen_zero(authuser)) {
25421                         snprintf(tmp, sizeof(tmp), "%s?%s:%s:%s@%s/%s", cat, username, secret, authuser, host, contact);
25422                      } else {
25423                         snprintf(tmp, sizeof(tmp), "%s?%s:%s@%s/%s", cat, username, secret, host, contact);
25424                      }
25425                   } else if (!ast_strlen_zero(authuser)) {
25426                      snprintf(tmp, sizeof(tmp), "%s?%s::%s@%s/%s", cat, username, authuser, host, contact);
25427                   } else {
25428                      snprintf(tmp, sizeof(tmp), "%s?%s@%s/%s", cat, username, host, contact);
25429                   }
25430                   if (sip_register(tmp, 0) == 0)
25431                      registry_count++;
25432                }
25433             }
25434          }
25435          cat = ast_category_browse(ucfg, cat);
25436       }
25437       ast_config_destroy(ucfg);
25438    }
25439 
25440    /* Load peers, users and friends */
25441    cat = NULL;
25442    while ( (cat = ast_category_browse(cfg, cat)) ) {
25443       const char *utype;
25444       if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
25445          continue;
25446       utype = ast_variable_retrieve(cfg, cat, "type");
25447       if (!utype) {
25448          ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
25449          continue;
25450       } else {
25451          if (!strcasecmp(utype, "user")) {
25452             ;
25453          } else if (!strcasecmp(utype, "friend")) {
25454             ;
25455          } else if (!strcasecmp(utype, "peer")) {
25456             ;
25457          } else {
25458             ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
25459             continue;
25460          }
25461          peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0, 0);
25462          if (peer) {
25463             ao2_t_link(peers, peer, "link peer into peers table");
25464             if ((peer->type & SIP_TYPE_PEER) && peer->addr.sin_addr.s_addr) {
25465                ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
25466             }
25467             unref_peer(peer, "unref the result of the build_peer call. Now, the links from the tables are the only ones left.");
25468             peer_count++;
25469          }
25470       }
25471    }
25472 
25473    /* Add default domains - host name, IP address and IP:port
25474     * Only do this if user added any sip domain with "localdomains" 
25475     * In order to *not* break backwards compatibility 
25476     *    Some phones address us at IP only, some with additional port number 
25477     */
25478    if (auto_sip_domains) {
25479       char temp[MAXHOSTNAMELEN];
25480 
25481       /* First our default IP address */
25482       if (bindaddr.sin_addr.s_addr) {
25483          add_sip_domain(ast_inet_ntoa(bindaddr.sin_addr), SIP_DOMAIN_AUTO, NULL);
25484       } else if (internip.sin_addr.s_addr) {
25485       /* Our internal IP address, if configured */
25486          add_sip_domain(ast_inet_ntoa(internip.sin_addr), SIP_DOMAIN_AUTO, NULL);
25487       } else {
25488          ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
25489       }
25490 
25491       /* If TCP is running on a different IP than UDP, then add it too */
25492       if (sip_tcp_desc.local_address.sin_addr.s_addr && !inaddrcmp(&bindaddr, &sip_tcp_desc.local_address))
25493          add_sip_domain(ast_inet_ntoa(sip_tcp_desc.local_address.sin_addr), SIP_DOMAIN_AUTO, NULL);
25494 
25495       /* If TLS is running on a differen IP than UDP and TCP, then add that too */
25496       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))
25497          add_sip_domain(ast_inet_ntoa(sip_tls_desc.local_address.sin_addr), SIP_DOMAIN_AUTO, NULL);
25498 
25499       /* Our extern IP address, if configured */
25500       if (externip.sin_addr.s_addr)
25501          add_sip_domain(ast_inet_ntoa(externip.sin_addr), SIP_DOMAIN_AUTO, NULL);
25502 
25503       /* Extern host name (NAT traversal support) */
25504       if (!ast_strlen_zero(externhost))
25505          add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
25506       
25507       /* Our host name */
25508       if (!gethostname(temp, sizeof(temp)))
25509          add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
25510    }
25511 
25512    /* Release configuration from memory */
25513    ast_config_destroy(cfg);
25514 
25515    /* Load the list of manual NOTIFY types to support */
25516    if (notify_types)
25517       ast_config_destroy(notify_types);
25518    if ((notify_types = ast_config_load(notify_config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
25519       ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed.\n", notify_config);
25520       notify_types = NULL;
25521    }
25522 
25523    /* Done, tell the manager */
25524    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);
25525    run_end = time(0);
25526    ast_debug(4, "SIP reload_config done...Runtime= %d sec\n", (int)(run_end-run_start));
25527 
25528    return 0;
25529 }
25530 
25531 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
25532 {
25533    struct sip_pvt *p;
25534    struct ast_udptl *udptl = NULL;
25535    
25536    p = chan->tech_pvt;
25537    if (!p)
25538       return NULL;
25539    
25540    sip_pvt_lock(p);
25541    if (p->udptl && ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
25542       udptl = p->udptl;
25543    sip_pvt_unlock(p);
25544    return udptl;
25545 }
25546 
25547 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
25548 {
25549    struct sip_pvt *p;
25550    
25551    p = chan->tech_pvt;
25552    if (!p)
25553       return -1;
25554    sip_pvt_lock(p);
25555    if (udptl)
25556       ast_udptl_get_peer(udptl, &p->udptlredirip);
25557    else
25558       memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
25559    if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
25560       if (!p->pendinginvite) {
25561          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);
25562          transmit_reinvite_with_sdp(p, TRUE, FALSE);
25563       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
25564          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);
25565          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
25566       }
25567    }
25568    /* Reset lastrtprx timer */
25569    p->lastrtprx = p->lastrtptx = time(NULL);
25570    sip_pvt_unlock(p);
25571    return 0;
25572 }
25573 
25574 /*! \brief Returns null if we can't reinvite audio (part of RTP interface) */
25575 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
25576 {
25577    struct sip_pvt *p = NULL;
25578    enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
25579 
25580    if (!(p = chan->tech_pvt))
25581       return AST_RTP_GET_FAILED;
25582 
25583    sip_pvt_lock(p);
25584    if (!(p->rtp)) {
25585       sip_pvt_unlock(p);
25586       return AST_RTP_GET_FAILED;
25587    }
25588 
25589    *rtp = p->rtp;
25590 
25591    if (ast_rtp_getnat(*rtp) && !ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT))
25592       res = AST_RTP_TRY_PARTIAL;
25593    else if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
25594       res = AST_RTP_TRY_NATIVE;
25595    else if (ast_test_flag(&global_jbconf, AST_JB_FORCED))
25596       res = AST_RTP_GET_FAILED;
25597 
25598    sip_pvt_unlock(p);
25599 
25600    return res;
25601 }
25602 
25603 /*! \brief Returns null if we can't reinvite video (part of RTP interface) */
25604 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
25605 {
25606    struct sip_pvt *p = NULL;
25607    enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
25608    
25609    if (!(p = chan->tech_pvt))
25610       return AST_RTP_GET_FAILED;
25611 
25612    sip_pvt_lock(p);
25613    if (!(p->vrtp)) {
25614       sip_pvt_unlock(p);
25615       return AST_RTP_GET_FAILED;
25616    }
25617 
25618    *rtp = p->vrtp;
25619 
25620    if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
25621       res = AST_RTP_TRY_NATIVE;
25622 
25623    sip_pvt_unlock(p);
25624 
25625    return res;
25626 }
25627 
25628 /*! \brief Returns null if we can't reinvite text (part of RTP interface) */
25629 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
25630 {
25631    struct sip_pvt *p = NULL;
25632    enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
25633    
25634    if (!(p = chan->tech_pvt))
25635       return AST_RTP_GET_FAILED;
25636 
25637    sip_pvt_lock(p);
25638    if (!(p->trtp)) {
25639       sip_pvt_unlock(p);
25640       return AST_RTP_GET_FAILED;
25641    }
25642 
25643    *rtp = p->trtp;
25644 
25645    if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
25646       res = AST_RTP_TRY_NATIVE;
25647 
25648    sip_pvt_unlock(p);
25649 
25650    return res;
25651 }
25652 
25653 /*! \brief Set the RTP peer for this call */
25654 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)
25655 {
25656    struct sip_pvt *p;
25657    int changed = 0;
25658 
25659    p = chan->tech_pvt;
25660    if (!p) 
25661       return -1;
25662 
25663    /* Disable early RTP bridge  */
25664    if (!ast_bridged_channel(chan) && !sip_cfg.directrtpsetup)  /* We are in early state */
25665       return 0;
25666 
25667    sip_pvt_lock(p);
25668    if (p->alreadygone) {
25669       /* If we're destroyed, don't bother */
25670       sip_pvt_unlock(p);
25671       return 0;
25672    }
25673 
25674    /* if this peer cannot handle reinvites of the media stream to devices
25675       that are known to be behind a NAT, then stop the process now
25676    */
25677         if (nat_active && !ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
25678                 sip_pvt_unlock(p);
25679                 return 0;
25680         }
25681 
25682    if (rtp) {
25683       changed |= ast_rtp_get_peer(rtp, &p->redirip);
25684    } else if (p->redirip.sin_addr.s_addr || ntohs(p->redirip.sin_port) != 0) {
25685       memset(&p->redirip, 0, sizeof(p->redirip));
25686       changed = 1;
25687    }
25688    if (vrtp) {
25689       changed |= ast_rtp_get_peer(vrtp, &p->vredirip);
25690    } else if (p->vredirip.sin_addr.s_addr || ntohs(p->vredirip.sin_port) != 0) {
25691       memset(&p->vredirip, 0, sizeof(p->vredirip));
25692       changed = 1;
25693    }
25694    if (trtp) {
25695       changed |= ast_rtp_get_peer(trtp, &p->tredirip);
25696    } else if (p->tredirip.sin_addr.s_addr || ntohs(p->tredirip.sin_port) != 0) {
25697       memset(&p->tredirip, 0, sizeof(p->tredirip));
25698       changed = 1;
25699    }
25700    if (codecs && (p->redircodecs != codecs)) {
25701       p->redircodecs = codecs;
25702       changed = 1;
25703    }
25704    if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
25705       if (chan->_state != AST_STATE_UP) { /* We are in early state */
25706          if (p->do_history)
25707             append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
25708          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));
25709       } else if (!p->pendinginvite) {     /* We are up, and have no outstanding invite */
25710          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));
25711          transmit_reinvite_with_sdp(p, FALSE, FALSE);
25712       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
25713          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));
25714          /* We have a pending Invite. Send re-invite when we're done with the invite */
25715          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);   
25716       }
25717    }
25718    /* Reset lastrtprx timer */
25719    p->lastrtprx = p->lastrtptx = time(NULL);
25720    sip_pvt_unlock(p);
25721    return 0;
25722 }
25723 
25724 static char *app_dtmfmode = "SIPDtmfMode";
25725 static char *app_sipaddheader = "SIPAddHeader";
25726 static char *app_sipremoveheader = "SIPRemoveHeader";
25727 
25728 /*! \brief Set the DTMFmode for an outbound SIP call (application) */
25729 static int sip_dtmfmode(struct ast_channel *chan, void *data)
25730 {
25731    struct sip_pvt *p;
25732    char *mode = data;
25733 
25734    if (!data) {
25735       ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
25736       return 0;
25737    }
25738    ast_channel_lock(chan);
25739    if (!IS_SIP_TECH(chan->tech)) {
25740       ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
25741       ast_channel_unlock(chan);
25742       return 0;
25743    }
25744    p = chan->tech_pvt;
25745    if (!p) {
25746       ast_channel_unlock(chan);
25747       return 0;
25748    }
25749    sip_pvt_lock(p);
25750    if (!strcasecmp(mode, "info")) {
25751       ast_clear_flag(&p->flags[0], SIP_DTMF);
25752       ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
25753       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
25754    } else if (!strcasecmp(mode, "shortinfo")) {
25755       ast_clear_flag(&p->flags[0], SIP_DTMF);
25756       ast_set_flag(&p->flags[0], SIP_DTMF_SHORTINFO);
25757       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
25758    } else if (!strcasecmp(mode, "rfc2833")) {
25759       ast_clear_flag(&p->flags[0], SIP_DTMF);
25760       ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
25761       p->jointnoncodeccapability |= AST_RTP_DTMF;
25762    } else if (!strcasecmp(mode, "inband")) { 
25763       ast_clear_flag(&p->flags[0], SIP_DTMF);
25764       ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
25765       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
25766    } else
25767       ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n", mode);
25768    if (p->rtp)
25769       ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
25770    if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
25771       if (!p->dsp) {
25772          p->dsp = ast_dsp_new();
25773          ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
25774       }
25775    } else {
25776       if (p->dsp) {
25777          ast_dsp_free(p->dsp);
25778          p->dsp = NULL;
25779       }
25780    }
25781    sip_pvt_unlock(p);
25782    ast_channel_unlock(chan);
25783    return 0;
25784 }
25785 
25786 /*! \brief Add a SIP header to an outbound INVITE */
25787 static int sip_addheader(struct ast_channel *chan, void *data)
25788 {
25789    int no = 0;
25790    int ok = FALSE;
25791    char varbuf[30];
25792    char *inbuf = data, *subbuf;
25793    
25794    if (ast_strlen_zero(inbuf)) {
25795       ast_log(LOG_WARNING, "This application requires the argument: Header\n");
25796       return 0;
25797    }
25798    ast_channel_lock(chan);
25799 
25800    /* Check for headers */
25801    while (!ok && no <= 50) {
25802       no++;
25803       snprintf(varbuf, sizeof(varbuf), "__SIPADDHEADER%.2d", no);
25804 
25805       /* Compare without the leading underscores */
25806       if ((pbx_builtin_getvar_helper(chan, (const char *) varbuf + 2) == (const char *) NULL)) {
25807          ok = TRUE;
25808       }
25809    }
25810    if (ok) {
25811       size_t len = strlen(inbuf);
25812       subbuf = alloca(len + 1);
25813       ast_get_encoded_str(inbuf, subbuf, len + 1);
25814       pbx_builtin_setvar_helper(chan, varbuf, subbuf);
25815       if (sipdebug) {
25816          ast_debug(1, "SIP Header added \"%s\" as %s\n", inbuf, varbuf);
25817       }
25818    } else {
25819       ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
25820    }
25821    ast_channel_unlock(chan);
25822    return 0;
25823 }
25824 
25825 /*! \brief Remove SIP headers added previously with SipAddHeader application */
25826 static int sip_removeheader(struct ast_channel *chan, void *data)
25827 {
25828    struct ast_var_t *newvariable;
25829    struct varshead *headp;
25830    int removeall = 0;
25831    char *inbuf = (char *) data;
25832 
25833    if (ast_strlen_zero(inbuf)) {
25834       removeall = 1;
25835    }
25836    ast_channel_lock(chan);
25837  
25838    headp=&chan->varshead;
25839    AST_LIST_TRAVERSE_SAFE_BEGIN (headp, newvariable, entries) {
25840       if (strncasecmp(ast_var_name(newvariable), "SIPADDHEADER", strlen("SIPADDHEADER")) == 0) {
25841          if (removeall || (!strncasecmp(ast_var_value(newvariable),inbuf,strlen(inbuf)))) {
25842             if (sipdebug)
25843                ast_log(LOG_DEBUG,"removing SIP Header \"%s\" as %s\n",
25844                   ast_var_value(newvariable),
25845                   ast_var_name(newvariable));
25846             AST_LIST_REMOVE_CURRENT(entries);
25847             ast_var_delete(newvariable);
25848          }
25849       }
25850    }
25851    AST_LIST_TRAVERSE_SAFE_END;
25852  
25853    ast_channel_unlock(chan);
25854    return 0;
25855 }
25856 
25857 /*! \brief Transfer call before connect with a 302 redirect
25858 \note Called by the transfer() dialplan application through the sip_transfer()
25859    pbx interface function if the call is in ringing state 
25860 \todo Fix this function so that we wait for reply to the REFER and
25861    react to errors, denials or other issues the other end might have.
25862  */
25863 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
25864 {
25865    char *cdest;
25866    char *extension, *host, *port;
25867    char tmp[80];
25868 
25869    cdest = ast_strdupa(dest);
25870    
25871    extension = strsep(&cdest, "@");
25872    host = strsep(&cdest, ":");
25873    port = strsep(&cdest, ":");
25874    if (ast_strlen_zero(extension)) {
25875       ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
25876       return 0;
25877    }
25878 
25879    /* we'll issue the redirect message here */
25880    if (!host) {
25881       char *localtmp;
25882 
25883       ast_copy_string(tmp, get_header(&p->initreq, "To"), sizeof(tmp));
25884       if (ast_strlen_zero(tmp)) {
25885          ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
25886          return 0;
25887       }
25888       if ( ( (localtmp = strcasestr(tmp, "sip:")) || (localtmp = strcasestr(tmp, "sips:")) ) 
25889          && (localtmp = strchr(localtmp, '@'))) {
25890          char lhost[80], lport[80];
25891 
25892          memset(lhost, 0, sizeof(lhost));
25893          memset(lport, 0, sizeof(lport));
25894          localtmp++;
25895          /* This is okey because lhost and lport are as big as tmp */
25896          sscanf(localtmp, "%80[^<>:; ]:%80[^<>:; ]", lhost, lport);
25897          if (ast_strlen_zero(lhost)) {
25898             ast_log(LOG_ERROR, "Can't find the host address\n");
25899             return 0;
25900          }
25901          host = ast_strdupa(lhost);
25902          if (!ast_strlen_zero(lport)) {
25903             port = ast_strdupa(lport);
25904          }
25905       }
25906    }
25907 
25908    ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s%s%s>", extension, host, port ? ":" : "", port ? port : "");
25909    transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
25910 
25911    sip_scheddestroy(p, SIP_TRANS_TIMEOUT);   /* Make sure we stop send this reply. */
25912    sip_alreadygone(p);
25913    /* hangup here */
25914    return 0;
25915 }
25916 
25917 /*! \brief Return SIP UA's codec (part of the RTP interface) */
25918 static int sip_get_codec(struct ast_channel *chan)
25919 {
25920    struct sip_pvt *p = chan->tech_pvt;
25921    return p->jointcapability ? p->jointcapability : p->capability;   
25922 }
25923 
25924 /*! \brief Send a poke to all known peers */
25925 static void sip_poke_all_peers(void)
25926 {
25927    int ms = 0, num = 0;
25928    struct ao2_iterator i;
25929    struct sip_peer *peer;
25930 
25931    if (!speerobjs)   /* No peers, just give up */
25932       return;
25933 
25934    i = ao2_iterator_init(peers, 0);
25935    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
25936       ao2_lock(peer);
25937       if (num == global_qualify_peers) {
25938          ms += global_qualify_gap;
25939          num = 0;
25940       } else {
25941          num++;
25942       }
25943       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ms, sip_poke_peer_s, peer,
25944             unref_peer(_data, "removing poke peer ref"),
25945             unref_peer(peer, "removing poke peer ref"),
25946             ref_peer(peer, "adding poke peer ref"));
25947       ao2_unlock(peer);
25948       unref_peer(peer, "toss iterator peer ptr");
25949    }
25950    ao2_iterator_destroy(&i);
25951 }
25952 
25953 /*! \brief Send all known registrations */
25954 static void sip_send_all_registers(void)
25955 {
25956    int ms;
25957    int regspacing;
25958    if (!regobjs)
25959       return;
25960    regspacing = default_expiry * 1000/regobjs;
25961    if (regspacing > 100)
25962       regspacing = 100;
25963    ms = regspacing;
25964    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
25965       ASTOBJ_WRLOCK(iterator);
25966       ms += regspacing;
25967       AST_SCHED_REPLACE_UNREF(iterator->expire, sched, ms, sip_reregister, iterator, 
25968                         registry_unref(_data, "REPLACE sched del decs the refcount"),
25969                         registry_unref(iterator, "REPLACE sched add failure decs the refcount"),
25970                         registry_addref(iterator, "REPLACE sched add incs the refcount"));
25971       ASTOBJ_UNLOCK(iterator);
25972    } while (0)
25973    );
25974 }
25975 
25976 /*! \brief Send all MWI subscriptions */
25977 static void sip_send_all_mwi_subscriptions(void)
25978 {
25979    ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
25980       ASTOBJ_WRLOCK(iterator);
25981       AST_SCHED_DEL(sched, iterator->resub);
25982       if ((iterator->resub = ast_sched_add(sched, 1, sip_subscribe_mwi_do, ASTOBJ_REF(iterator))) < 0) {
25983          ASTOBJ_UNREF(iterator, sip_subscribe_mwi_destroy);
25984       }
25985       ASTOBJ_UNLOCK(iterator);
25986    } while (0));
25987 }
25988 
25989 /*! \brief Reload module */
25990 static int sip_do_reload(enum channelreloadreason reason)
25991 {
25992    time_t start_poke, end_poke;
25993    
25994    reload_config(reason);
25995    ast_sched_dump(sched);
25996 
25997    start_poke = time(0);
25998    /* Prune peers who still are supposed to be deleted */
25999    unlink_marked_peers_from_tables();
26000 
26001    ast_debug(4, "--------------- Done destroying pruned peers\n");
26002 
26003    /* Send qualify (OPTIONS) to all peers */
26004    sip_poke_all_peers();
26005 
26006    /* Register with all services */
26007    sip_send_all_registers();
26008 
26009    sip_send_all_mwi_subscriptions();
26010 
26011    end_poke = time(0);
26012    
26013    ast_debug(4, "do_reload finished. peer poke/prune reg contact time = %d sec.\n", (int)(end_poke-start_poke));
26014 
26015    ast_debug(4, "--------------- SIP reload done\n");
26016 
26017    return 0;
26018 }
26019 
26020 /*! \brief Force reload of module from cli */
26021 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
26022 {
26023    
26024    switch (cmd) {
26025    case CLI_INIT:
26026       e->command = "sip reload";
26027       e->usage =
26028          "Usage: sip reload\n"
26029          "       Reloads SIP configuration from sip.conf\n";
26030       return NULL;
26031    case CLI_GENERATE:
26032       return NULL;
26033    }
26034 
26035    ast_mutex_lock(&sip_reload_lock);
26036    if (sip_reloading) 
26037       ast_verbose("Previous SIP reload not yet done\n");
26038    else {
26039       sip_reloading = TRUE;
26040       sip_reloadreason = (a && a->fd) ? CHANNEL_CLI_RELOAD : CHANNEL_MODULE_RELOAD;
26041    }
26042    ast_mutex_unlock(&sip_reload_lock);
26043    restart_monitor();
26044 
26045    return CLI_SUCCESS;
26046 }
26047 
26048 /*! \brief  Part of Asterisk module interface */
26049 static int reload(void)
26050 {
26051    if (sip_reload(0, 0, NULL))
26052       return 0;
26053    return 1;
26054 }
26055 
26056 /*! \brief SIP Cli commands definition */
26057 static struct ast_cli_entry cli_sip[] = {
26058    AST_CLI_DEFINE(sip_show_channels, "List active SIP channels or subscriptions"),
26059    AST_CLI_DEFINE(sip_show_channelstats, "List statistics for active SIP channels"),
26060    AST_CLI_DEFINE(sip_show_domains, "List our local SIP domains"),
26061    AST_CLI_DEFINE(sip_show_inuse, "List all inuse/limits"),
26062    AST_CLI_DEFINE(sip_show_objects, "List all SIP object allocations"),
26063    AST_CLI_DEFINE(sip_show_peers, "List defined SIP peers"),
26064    AST_CLI_DEFINE(sip_show_registry, "List SIP registration status"),
26065    AST_CLI_DEFINE(sip_unregister, "Unregister (force expiration) a SIP peer from the registry"),
26066    AST_CLI_DEFINE(sip_show_settings, "Show SIP global settings"),
26067    AST_CLI_DEFINE(sip_show_mwi, "Show MWI subscriptions"),
26068    AST_CLI_DEFINE(sip_cli_notify, "Send a notify packet to a SIP peer"),
26069    AST_CLI_DEFINE(sip_show_channel, "Show detailed SIP channel info"),
26070    AST_CLI_DEFINE(sip_show_history, "Show SIP dialog history"),
26071    AST_CLI_DEFINE(sip_show_peer, "Show details on specific SIP peer"),
26072    AST_CLI_DEFINE(sip_show_users, "List defined SIP users"),
26073    AST_CLI_DEFINE(sip_show_user, "Show details on specific SIP user"),
26074    AST_CLI_DEFINE(sip_qualify_peer, "Send an OPTIONS packet to a peer"),
26075    AST_CLI_DEFINE(sip_show_sched, "Present a report on the status of the sched queue"),
26076    AST_CLI_DEFINE(sip_prune_realtime, "Prune cached Realtime users/peers"),
26077    AST_CLI_DEFINE(sip_do_debug, "Enable/Disable SIP debugging"),
26078    AST_CLI_DEFINE(sip_set_history, "Enable/Disable SIP history"),
26079    AST_CLI_DEFINE(sip_reload, "Reload SIP configuration"),
26080    AST_CLI_DEFINE(sip_show_tcp, "List TCP Connections")
26081 };
26082 
26083 /*! \brief PBX load module - initialization */
26084 static int load_module(void)
26085 {
26086    ast_verbose("SIP channel loading...\n");
26087    /* the fact that ao2_containers can't resize automatically is a major worry! */
26088    /* if the number of objects gets above MAX_XXX_BUCKETS, things will slow down */
26089    peers = ao2_t_container_alloc(HASH_PEER_SIZE, peer_hash_cb, peer_cmp_cb, "allocate peers");
26090    peers_by_ip = ao2_t_container_alloc(HASH_PEER_SIZE, peer_iphash_cb, peer_ipcmp_cb, "allocate peers_by_ip");
26091    dialogs = ao2_t_container_alloc(HASH_DIALOG_SIZE, dialog_hash_cb, dialog_cmp_cb, "allocate dialogs");
26092    threadt = ao2_t_container_alloc(HASH_DIALOG_SIZE, threadt_hash_cb, threadt_cmp_cb, "allocate threadt table");
26093    
26094    ASTOBJ_CONTAINER_INIT(&regl); /* Registry object list -- not searched for anything */
26095    ASTOBJ_CONTAINER_INIT(&submwil); /* MWI subscription object list */
26096 
26097    if (!(sched = sched_context_create())) {
26098       ast_log(LOG_ERROR, "Unable to create scheduler context\n");
26099       return AST_MODULE_LOAD_FAILURE;
26100    }
26101 
26102    if (!(io = io_context_create())) {
26103       ast_log(LOG_ERROR, "Unable to create I/O context\n");
26104       sched_context_destroy(sched);
26105       return AST_MODULE_LOAD_FAILURE;
26106    }
26107 
26108    sip_reloadreason = CHANNEL_MODULE_LOAD;
26109 
26110    if(reload_config(sip_reloadreason)) /* Load the configuration from sip.conf */
26111       return AST_MODULE_LOAD_DECLINE;
26112 
26113    /* Prepare the version that does not require DTMF BEGIN frames.
26114     * We need to use tricks such as memcpy and casts because the variable
26115     * has const fields.
26116     */
26117    memcpy(&sip_tech_info, &sip_tech, sizeof(sip_tech));
26118    memset((void *) &sip_tech_info.send_digit_begin, 0, sizeof(sip_tech_info.send_digit_begin));
26119 
26120    /* Make sure we can register our sip channel type */
26121    if (ast_channel_register(&sip_tech)) {
26122       ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
26123       io_context_destroy(io);
26124       sched_context_destroy(sched);
26125       return AST_MODULE_LOAD_FAILURE;
26126    }
26127 
26128    /* Register all CLI functions for SIP */
26129    ast_cli_register_multiple(cli_sip, ARRAY_LEN(cli_sip));
26130 
26131    /* Tell the RTP subdriver that we're here */
26132    ast_rtp_proto_register(&sip_rtp);
26133 
26134    /* Tell the UDPTL subdriver that we're here */
26135    ast_udptl_proto_register(&sip_udptl);
26136 
26137    /* Register dialplan applications */
26138    ast_register_application_xml(app_dtmfmode, sip_dtmfmode);
26139    ast_register_application_xml(app_sipaddheader, sip_addheader);
26140    ast_register_application_xml(app_sipremoveheader, sip_removeheader);
26141 
26142    /* Register dialplan functions */
26143    ast_custom_function_register(&sip_header_function);
26144    ast_custom_function_register(&sippeer_function);
26145    ast_custom_function_register(&sipchaninfo_function);
26146    ast_custom_function_register(&checksipdomain_function);
26147 
26148    /* Register manager commands */
26149    ast_manager_register2("SIPpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peers,
26150          "List SIP peers (text format)", mandescr_show_peers);
26151    ast_manager_register2("SIPshowpeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peer,
26152          "Show SIP peer (text format)", mandescr_show_peer);
26153    ast_manager_register2("SIPqualifypeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_qualify_peer,
26154          "Show SIP peer (text format)", mandescr_show_peer);   /*! \todo Fix this XXX This must be all wrong XXXX */
26155    ast_manager_register2("SIPshowregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_show_registry,
26156          "Show SIP registrations (text format)", mandescr_show_registry);
26157    ast_manager_register2("SIPnotify", EVENT_FLAG_SYSTEM, manager_sipnotify,
26158          "Send a SIP notify", mandescr_sipnotify);
26159    sip_poke_all_peers();   
26160    sip_send_all_registers();
26161    sip_send_all_mwi_subscriptions();
26162 
26163    /* And start the monitor for the first time */
26164    restart_monitor();
26165 
26166    ast_realtime_require_field(ast_check_realtime("sipregs") ? "sipregs" : "sippeers",
26167       "name", RQ_CHAR, 10,
26168       "ipaddr", RQ_CHAR, 15,
26169       "port", RQ_UINTEGER2, 5,
26170       "regseconds", RQ_INTEGER4, 11,
26171       "defaultuser", RQ_CHAR, 10,
26172       "fullcontact", RQ_CHAR, 35,
26173       "regserver", RQ_CHAR, 20,
26174       "useragent", RQ_CHAR, 20,
26175       "lastms", RQ_INTEGER4, 11,
26176       SENTINEL);
26177 
26178    return AST_MODULE_LOAD_SUCCESS;
26179 }
26180 
26181 /*! \brief PBX unload module API */
26182 static int unload_module(void)
26183 {
26184    struct sip_pvt *p;
26185    struct sip_threadinfo *th;
26186    struct ast_context *con;
26187    struct ao2_iterator i;
26188 
26189    ast_sched_dump(sched);
26190    
26191    /* First, take us out of the channel type list */
26192    ast_channel_unregister(&sip_tech);
26193 
26194    /* Unregister dial plan functions */
26195    ast_custom_function_unregister(&sipchaninfo_function);
26196    ast_custom_function_unregister(&sippeer_function);
26197    ast_custom_function_unregister(&sip_header_function);
26198    ast_custom_function_unregister(&checksipdomain_function);
26199 
26200    /* Unregister dial plan applications */
26201    ast_unregister_application(app_dtmfmode);
26202    ast_unregister_application(app_sipaddheader);
26203    ast_unregister_application(app_sipremoveheader);
26204 
26205    /* Unregister CLI commands */
26206    ast_cli_unregister_multiple(cli_sip, ARRAY_LEN(cli_sip));
26207 
26208    /* Disconnect from the RTP subsystem */
26209    ast_rtp_proto_unregister(&sip_rtp);
26210 
26211    /* Disconnect from UDPTL */
26212    ast_udptl_proto_unregister(&sip_udptl);
26213 
26214    /* Unregister AMI actions */
26215    ast_manager_unregister("SIPpeers");
26216    ast_manager_unregister("SIPshowpeer");
26217    ast_manager_unregister("SIPqualifypeer");
26218    ast_manager_unregister("SIPshowregistry");
26219    ast_manager_unregister("SIPnotify");
26220    
26221    /* Kill TCP/TLS server threads */
26222    if (sip_tcp_desc.master)
26223       ast_tcptls_server_stop(&sip_tcp_desc);
26224    if (sip_tls_desc.master)
26225       ast_tcptls_server_stop(&sip_tls_desc);
26226 
26227    /* Kill all existing TCP/TLS threads */
26228    i = ao2_iterator_init(threadt, 0);
26229    while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
26230       pthread_t thread = th->threadid;
26231       th->stop = 1;
26232       pthread_kill(thread, SIGURG);
26233       pthread_join(thread, NULL);
26234       ao2_t_ref(th, -1, "decrement ref from iterator");
26235    }
26236    ao2_iterator_destroy(&i);
26237 
26238    /* Hangup all dialogs if they have an owner */
26239    i = ao2_iterator_init(dialogs, 0);
26240    while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
26241       if (p->owner)
26242          ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
26243       ao2_t_ref(p, -1, "toss dialog ptr from iterator_next");
26244    }
26245    ao2_iterator_destroy(&i);
26246 
26247    ast_mutex_lock(&monlock);
26248    if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
26249       pthread_cancel(monitor_thread);
26250       pthread_kill(monitor_thread, SIGURG);
26251       pthread_join(monitor_thread, NULL);
26252    }
26253    monitor_thread = AST_PTHREADT_STOP;
26254    ast_mutex_unlock(&monlock);
26255 
26256    /* Destroy all the dialogs and free their memory */
26257    i = ao2_iterator_init(dialogs, 0);
26258    while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
26259       dialog_unlink_all(p, TRUE, TRUE);
26260       ao2_t_ref(p, -1, "throw away iterator result"); 
26261    }
26262    ao2_iterator_destroy(&i);
26263 
26264    /* Free memory for local network address mask */
26265    ast_free_ha(localaddr);
26266 
26267    clear_realm_authentication(authl);
26268 
26269 
26270    if (default_tls_cfg.certfile)
26271       ast_free(default_tls_cfg.certfile);
26272    if (default_tls_cfg.cipher)
26273       ast_free(default_tls_cfg.cipher);
26274    if (default_tls_cfg.cafile)
26275       ast_free(default_tls_cfg.cafile);
26276    if (default_tls_cfg.capath)
26277       ast_free(default_tls_cfg.capath);
26278 
26279    ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
26280    ASTOBJ_CONTAINER_DESTROY(&regl);
26281    ASTOBJ_CONTAINER_DESTROYALL(&submwil, sip_subscribe_mwi_destroy);
26282    ASTOBJ_CONTAINER_DESTROY(&submwil);
26283 
26284    ao2_t_ref(peers, -1, "unref the peers table");
26285    ao2_t_ref(peers_by_ip, -1, "unref the peers_by_ip table");
26286    ao2_t_ref(dialogs, -1, "unref the dialogs table");
26287    ao2_t_ref(threadt, -1, "unref the thread table");
26288 
26289    clear_sip_domains();
26290    ast_free_ha(global_contact_ha);
26291    close(sipsock);
26292    sched_context_destroy(sched);
26293    con = ast_context_find(used_context);
26294    if (con)
26295       ast_context_destroy(con, "SIP");
26296    ast_unload_realtime("sipregs");
26297    ast_unload_realtime("sippeers");
26298 
26299    return 0;
26300 }
26301 
26302 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Session Initiation Protocol (SIP)",
26303       .load = load_module,
26304       .unload = unload_module,
26305       .reload = reload,
26306           );

Generated on Wed Mar 2 18:53:23 2011 for Asterisk - the Open Source PBX by  doxygen 1.5.9