Wed Mar 3 22:36:22 2010

Asterisk developer's documentation


chan_sip.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2006, Digium, Inc.
00005  *
00006  * Mark Spencer <markster@digium.com>
00007  *
00008  * See http://www.asterisk.org for more information about
00009  * the Asterisk project. Please do not directly contact
00010  * any of the maintainers of this project for assistance;
00011  * the project provides a web site, mailing lists and IRC
00012  * channels for your use.
00013  *
00014  * This program is free software, distributed under the terms of
00015  * the GNU General Public License Version 2. See the LICENSE file
00016  * at the top of the source tree.
00017  */
00018 
00019 /*!
00020  * \file
00021  * \brief Implementation of Session Initiation Protocol
00022  *
00023  * \author Mark Spencer <markster@digium.com>
00024  *
00025  * See Also:
00026  * \arg \ref AstCREDITS
00027  *
00028  * Implementation of RFC 3261 - without S/MIME, and experimental TCP and TLS support
00029  * Configuration file \link Config_sip sip.conf \endlink
00030  *
00031  * ********** IMPORTANT *
00032  * \note TCP/TLS support is EXPERIMENTAL and WILL CHANGE. This applies to configuration
00033  * settings, dialplan commands and dialplans apps/functions
00034  * 
00035  *
00036  * TODO:s
00037  * \todo Better support of forking
00038  * \todo VIA branch tag transaction checking
00039  * \todo Transaction support
00040  * \todo We need to test TCP sessions with SIP proxies and in regards
00041  *       to the SIP outbound specs.
00042  * \todo Fix TCP/TLS handling in dialplan, SRV records, transfers and much more
00043  * \todo Save TCP/TLS sessions in registry
00044  * \todo Add TCP/TLS information to function SIPPEER and SIPCHANINFO
00045  *
00046  * \ingroup channel_drivers
00047  *
00048  * \par Overview of the handling of SIP sessions
00049  * The SIP channel handles several types of SIP sessions, or dialogs,
00050  * not all of them being "telephone calls".
00051  * - Incoming calls that will be sent to the PBX core
00052  * - Outgoing calls, generated by the PBX
00053  * - SIP subscriptions and notifications of states and voicemail messages
00054  * - SIP registrations, both inbound and outbound
00055  * - SIP peer management (peerpoke, OPTIONS)
00056  * - SIP text messages
00057  *
00058  * In the SIP channel, there's a list of active SIP dialogs, which includes
00059  * all of these when they are active. "sip show channels" in the CLI will
00060  * show most of these, excluding subscriptions which are shown by
00061  * "sip show subscriptions"
00062  *
00063  * \par incoming packets
00064  * Incoming packets are received in the monitoring thread, then handled by
00065  * sipsock_read(). This function parses the packet and matches an existing
00066  * dialog or starts a new SIP dialog.
00067  * 
00068  * sipsock_read sends the packet to handle_incoming(), that parses a bit more.
00069  * If it is a response to an outbound request, the packet is sent to handle_response().
00070  * If it is a request, handle_incoming() sends it to one of a list of functions
00071  * depending on the request type - INVITE, OPTIONS, REFER, BYE, CANCEL etc
00072  * sipsock_read locks the ast_channel if it exists (an active call) and
00073  * unlocks it after we have processed the SIP message.
00074  *
00075  * A new INVITE is sent to handle_request_invite(), that will end up
00076  * starting a new channel in the PBX, the new channel after that executing
00077  * in a separate channel thread. This is an incoming "call".
00078  * When the call is answered, either by a bridged channel or the PBX itself
00079  * the sip_answer() function is called.
00080  *
00081  * The actual media - Video or Audio - is mostly handled by the RTP subsystem
00082  * in rtp.c 
00083  * 
00084  * \par Outbound calls
00085  * Outbound calls are set up by the PBX through the sip_request_call()
00086  * function. After that, they are activated by sip_call().
00087  * 
00088  * \par Hanging up
00089  * The PBX issues a hangup on both incoming and outgoing calls through
00090  * the sip_hangup() function
00091  */
00092 
00093 /*** MODULEINFO
00094         <depend>chan_local</depend>
00095  ***/
00096 
00097 /*!  \page sip_session_timers SIP Session Timers in Asterisk Chan_sip
00098 
00099    The SIP Session-Timers is an extension of the SIP protocol that allows end-points and proxies to
00100    refresh a session periodically. The sessions are kept alive by sending a RE-INVITE or UPDATE
00101    request at a negotiated interval. If a session refresh fails then all the entities that support Session-
00102    Timers clear their internal session state. In addition, UAs generate a BYE request in order to clear
00103    the state in the proxies and the remote UA (this is done for the benefit of SIP entities in the path
00104    that do not support Session-Timers).
00105 
00106    The Session-Timers can be configured on a system-wide, per-user, or per-peer basis. The peruser/
00107    per-peer settings override the global settings. The following new parameters have been
00108    added to the sip.conf file.
00109       session-timers=["accept", "originate", "refuse"]
00110       session-expires=[integer]
00111       session-minse=[integer]
00112       session-refresher=["uas", "uac"]
00113 
00114    The session-timers parameter in sip.conf defines the mode of operation of SIP session-timers feature in
00115    Asterisk. The Asterisk can be configured in one of the following three modes:
00116 
00117    1. Accept :: In the "accept" mode, the Asterisk server honors session-timers requests
00118       made by remote end-points. A remote end-point can request Asterisk to engage
00119       session-timers by either sending it an INVITE request with a "Supported: timer"
00120       header in it or by responding to Asterisk's INVITE with a 200 OK that contains
00121       Session-Expires: header in it. In this mode, the Asterisk server does not 
00122       request session-timers from remote end-points. This is the default mode.
00123    2. Originate :: In the "originate" mode, the Asterisk server requests the remote 
00124       end-points to activate session-timers in addition to honoring such requests
00125       made by the remote end-pints. In order to get as much protection as possible
00126       against hanging SIP channels due to network or end-point failures, Asterisk
00127       resends periodic re-INVITEs even if a remote end-point does not support
00128       the session-timers feature.
00129    3. Refuse :: In the "refuse" mode, Asterisk acts as if it does not support session-
00130       timers for inbound or outbound requests. If a remote end-point requests
00131       session-timers in a dialog, then Asterisk ignores that request unless it's
00132       noted as a requirement (Require: header), in which case the INVITE is 
00133       rejected with a 420 Bad Extension response.
00134 
00135 */
00136 
00137 #include "asterisk.h"
00138 
00139 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 227696 $")
00140 
00141 #include <ctype.h>
00142 #include <sys/ioctl.h>
00143 #include <fcntl.h>
00144 #include <signal.h>
00145 #include <sys/signal.h>
00146 #include <regex.h>
00147 #include <time.h>
00148 
00149 #include "asterisk/network.h"
00150 #include "asterisk/paths.h"   /* need ast_config_AST_SYSTEM_NAME */
00151 
00152 #include "asterisk/lock.h"
00153 #include "asterisk/channel.h"
00154 #include "asterisk/config.h"
00155 #include "asterisk/module.h"
00156 #include "asterisk/pbx.h"
00157 #include "asterisk/sched.h"
00158 #include "asterisk/io.h"
00159 #include "asterisk/rtp.h"
00160 #include "asterisk/udptl.h"
00161 #include "asterisk/acl.h"
00162 #include "asterisk/manager.h"
00163 #include "asterisk/callerid.h"
00164 #include "asterisk/cli.h"
00165 #include "asterisk/app.h"
00166 #include "asterisk/musiconhold.h"
00167 #include "asterisk/dsp.h"
00168 #include "asterisk/features.h"
00169 #include "asterisk/srv.h"
00170 #include "asterisk/astdb.h"
00171 #include "asterisk/causes.h"
00172 #include "asterisk/utils.h"
00173 #include "asterisk/file.h"
00174 #include "asterisk/astobj.h"
00175 /* 
00176    Uncomment the define below,  if you are having refcount related memory leaks.
00177    With this uncommented, this module will generate a file, /tmp/refs, which contains
00178    a history of the ao2_ref() calls. To be useful, all calls to ao2_* functions should
00179    be modified to ao2_t_* calls, and include a tag describing what is happening with 
00180    enough detail, to make pairing up a reference count increment with its corresponding decrement.
00181    The refcounter program in utils/ can be invaluable in highlighting objects that are not
00182    balanced, along with the complete history for that object.
00183    In normal operation, the macros defined will throw away the tags, so they do not 
00184    affect the speed of the program at all. They can be considered to be documentation.
00185 */
00186 /* #define  REF_DEBUG 1 */
00187 #include "asterisk/astobj2.h"
00188 #include "asterisk/dnsmgr.h"
00189 #include "asterisk/devicestate.h"
00190 #include "asterisk/linkedlists.h"
00191 #include "asterisk/stringfields.h"
00192 #include "asterisk/monitor.h"
00193 #include "asterisk/netsock.h"
00194 #include "asterisk/localtime.h"
00195 #include "asterisk/abstract_jb.h"
00196 #include "asterisk/threadstorage.h"
00197 #include "asterisk/translate.h"
00198 #include "asterisk/ast_version.h"
00199 #include "asterisk/event.h"
00200 #include "asterisk/tcptls.h"
00201 
00202 #ifndef FALSE
00203 #define FALSE    0
00204 #endif
00205 
00206 #ifndef TRUE
00207 #define TRUE     1
00208 #endif
00209 
00210 #define  SIPBUFSIZE     512
00211 
00212 /* Arguments for find_peer */
00213 #define FINDUSERS (1 << 0)
00214 #define FINDPEERS (1 << 1)
00215 #define FINDALLDEVICES (FINDUSERS | FINDPEERS)
00216 
00217 #define XMIT_ERROR      -2
00218 
00219 #define SIP_RESERVED ";/?:@&=+$,# "
00220 
00221 /* #define VOCAL_DATA_HACK */
00222 
00223 #define DEFAULT_DEFAULT_EXPIRY  120
00224 #define DEFAULT_MIN_EXPIRY      60
00225 #define DEFAULT_MAX_EXPIRY      3600
00226 #define DEFAULT_REGISTRATION_TIMEOUT 20
00227 #define DEFAULT_MAX_FORWARDS    "70"
00228 
00229 /* guard limit must be larger than guard secs */
00230 /* guard min must be < 1000, and should be >= 250 */
00231 #define EXPIRY_GUARD_SECS       15                /*!< How long before expiry do we reregister */
00232 #define EXPIRY_GUARD_LIMIT      30                /*!< Below here, we use EXPIRY_GUARD_PCT instead of 
00233                                                     EXPIRY_GUARD_SECS */
00234 #define EXPIRY_GUARD_MIN        500                /*!< This is the minimum guard time applied. If 
00235                                                    GUARD_PCT turns out to be lower than this, it 
00236                                                    will use this time instead.
00237                                                    This is in milliseconds. */
00238 #define EXPIRY_GUARD_PCT        0.20                /*!< Percentage of expires timeout to use when 
00239                                                     below EXPIRY_GUARD_LIMIT */
00240 #define DEFAULT_EXPIRY 900                          /*!< Expire slowly */
00241 
00242 static int min_expiry = DEFAULT_MIN_EXPIRY;        /*!< Minimum accepted registration time */
00243 static int max_expiry = DEFAULT_MAX_EXPIRY;        /*!< Maximum accepted registration time */
00244 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
00245 
00246 #ifndef MAX
00247 #define MAX(a,b) ((a) > (b) ? (a) : (b))
00248 #endif
00249 
00250 #define CALLERID_UNKNOWN             "Anonymous"
00251 #define FROMDOMAIN_INVALID           "anonymous.invalid"
00252 
00253 #define DEFAULT_MAXMS                2000             /*!< Qualification: Must be faster than 2 seconds by default */
00254 #define DEFAULT_QUALIFYFREQ          60 * 1000        /*!< Qualification: How often to check for the host to be up */
00255 #define DEFAULT_FREQ_NOTOK           10 * 1000        /*!< Qualification: How often to check, if the host is down... */
00256 
00257 #define DEFAULT_RETRANS              1000             /*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
00258 #define MAX_RETRANS                  6                /*!< Try only 6 times for retransmissions, a total of 7 transmissions */
00259 #define SIP_TIMER_T1                 500              /* SIP timer T1 (according to RFC 3261) */
00260 #define SIP_TRANS_TIMEOUT            64 * SIP_TIMER_T1/*!< SIP request timeout (rfc 3261) 64*T1 
00261                                                       \todo Use known T1 for timeout (peerpoke)
00262                                                       */
00263 #define DEFAULT_TRANS_TIMEOUT        -1               /* Use default SIP transaction timeout */
00264 #define MAX_AUTHTRIES                3                /*!< Try authentication three times, then fail */
00265 
00266 #define SIP_MAX_HEADERS              64               /*!< Max amount of SIP headers to read */
00267 #define SIP_MAX_LINES                64               /*!< Max amount of lines in SIP attachment (like SDP) */
00268 #define SIP_MAX_PACKET               4096             /*!< Also from RFC 3261 (2543), should sub headers tho */
00269 #define SIP_MIN_PACKET               1024             /*!< Initialize size of memory to allocate for packets */
00270 
00271 #define INITIAL_CSEQ                 101              /*!< our initial sip sequence number */
00272 
00273 #define DEFAULT_MAX_SE               1800             /*!< Session-Timer Default Session-Expires period (RFC 4028) */
00274 #define DEFAULT_MIN_SE               90               /*!< Session-Timer Default Min-SE period (RFC 4028) */
00275 
00276 #define SDP_MAX_RTPMAP_CODECS        32               /*!< Maximum number of codecs allowed in received SDP */
00277 
00278 /*! \brief Global jitterbuffer configuration - by default, jb is disabled */
00279 static struct ast_jb_conf default_jbconf =
00280 {
00281    .flags = 0,
00282    .max_size = -1,
00283    .resync_threshold = -1,
00284    .impl = ""
00285 };
00286 static struct ast_jb_conf global_jbconf;  /*!< Global jitterbuffer configuration */
00287 
00288 static const char config[] = "sip.conf";  /*!< Main configuration file */
00289 static const char notify_config[] = "sip_notify.conf";   /*!< Configuration file for sending Notify with CLI commands to reconfigure or reboot phones */
00290 
00291 #define RTP    1
00292 #define NO_RTP 0
00293 
00294 /*! \brief Authorization scheme for call transfers 
00295 \note Not a bitfield flag, since there are plans for other modes,
00296    like "only allow transfers for authenticated devices" */
00297 enum transfermodes {
00298    TRANSFER_OPENFORALL,            /*!< Allow all SIP transfers */
00299    TRANSFER_CLOSED,                /*!< Allow no SIP transfers */
00300 };
00301 
00302 
00303 /*! \brief The result of a lot of functions */
00304 enum sip_result {
00305    AST_SUCCESS = 0,     /*! FALSE means success, funny enough */
00306    AST_FAILURE = -1,    
00307 };
00308 
00309 /*! \brief States for the INVITE transaction, not the dialog 
00310    \note this is for the INVITE that sets up the dialog
00311 */
00312 enum invitestates {
00313    INV_NONE = 0,          /*!< No state at all, maybe not an INVITE dialog */
00314    INV_CALLING = 1,  /*!< Invite sent, no answer */
00315    INV_PROCEEDING = 2,  /*!< We got/sent 1xx message */
00316    INV_EARLY_MEDIA = 3,    /*!< We got 18x message with to-tag back */
00317    INV_COMPLETED = 4,   /*!< Got final response with error. Wait for ACK, then CONFIRMED */
00318    INV_CONFIRMED = 5,   /*!< Confirmed response - we've got an ack (Incoming calls only) */
00319    INV_TERMINATED = 6,  /*!< Transaction done - either successful (AST_STATE_UP) or failed, but done 
00320                  The only way out of this is a BYE from one side */
00321    INV_CANCELLED = 7,   /*!< Transaction cancelled by client or server in non-terminated state */
00322 };
00323 
00324 /*! \brief Readable descriptions of device states.
00325        \note Should be aligned to above table as index */
00326 static const struct invstate2stringtable {
00327    const enum invitestates state;
00328    const char *desc;
00329 } invitestate2string[] = {
00330    {INV_NONE,              "None"  },
00331    {INV_CALLING,           "Calling (Trying)"},
00332    {INV_PROCEEDING,        "Proceeding "},
00333    {INV_EARLY_MEDIA,       "Early media"},
00334    {INV_COMPLETED,         "Completed (done)"},
00335    {INV_CONFIRMED,         "Confirmed (up)"},
00336    {INV_TERMINATED,        "Done"},
00337    {INV_CANCELLED,         "Cancelled"}
00338 };
00339 
00340 /*! \brief When sending a SIP message, we can send with a few options, depending on
00341    type of SIP request. UNRELIABLE is moslty used for responses to repeated requests,
00342    where the original response would be sent RELIABLE in an INVITE transaction */
00343 enum xmittype {
00344    XMIT_CRITICAL = 2,              /*!< Transmit critical SIP message reliably, with re-transmits.
00345                                               If it fails, it's critical and will cause a teardown of the session */
00346    XMIT_RELIABLE = 1,              /*!< Transmit SIP message reliably, with re-transmits */
00347    XMIT_UNRELIABLE = 0,            /*!< Transmit SIP message without bothering with re-transmits */
00348 };
00349 
00350 enum parse_register_result {
00351    PARSE_REGISTER_FAILED,
00352    PARSE_REGISTER_UPDATE,
00353    PARSE_REGISTER_QUERY,
00354 };
00355 
00356 /*! \brief Type of subscription, based on the packages we do support */
00357 enum subscriptiontype { 
00358    NONE = 0,
00359    XPIDF_XML,
00360    DIALOG_INFO_XML,
00361    CPIM_PIDF_XML,
00362    PIDF_XML,
00363    MWI_NOTIFICATION
00364 };
00365 
00366 /*! \brief Subscription types that we support. We support
00367    - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
00368    - SIMPLE presence used for device status
00369    - Voicemail notification subscriptions
00370 */
00371 static const struct cfsubscription_types {
00372    enum subscriptiontype type;
00373    const char * const event;
00374    const char * const mediatype;
00375    const char * const text;
00376 } subscription_types[] = {
00377    { NONE,        "-",        "unknown",               "unknown" },
00378    /* RFC 4235: SIP Dialog event package */
00379    { DIALOG_INFO_XML, "dialog",   "application/dialog-info+xml", "dialog-info+xml" },
00380    { CPIM_PIDF_XML,   "presence", "application/cpim-pidf+xml",   "cpim-pidf+xml" },  /* RFC 3863 */
00381    { PIDF_XML,        "presence", "application/pidf+xml",        "pidf+xml" },       /* RFC 3863 */
00382    { XPIDF_XML,       "presence", "application/xpidf+xml",       "xpidf+xml" },       /* Pre-RFC 3863 with MS additions */
00383    { MWI_NOTIFICATION,  "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
00384 };
00385 
00386 
00387 /*! \brief Authentication types - proxy or www authentication 
00388    \note Endpoints, like Asterisk, should always use WWW authentication to
00389    allow multiple authentications in the same call - to the proxy and
00390    to the end point.
00391 */
00392 enum sip_auth_type {
00393    PROXY_AUTH = 407,
00394    WWW_AUTH = 401,
00395 };
00396 
00397 /*! \brief Authentication result from check_auth* functions */
00398 enum check_auth_result {
00399    AUTH_DONT_KNOW = -100,  /*!< no result, need to check further */
00400       /* XXX maybe this is the same as AUTH_NOT_FOUND */
00401 
00402    AUTH_SUCCESSFUL = 0,
00403    AUTH_CHALLENGE_SENT = 1,
00404    AUTH_SECRET_FAILED = -1,
00405    AUTH_USERNAME_MISMATCH = -2,
00406    AUTH_NOT_FOUND = -3, /*!< returned by register_verify */
00407    AUTH_FAKE_AUTH = -4,
00408    AUTH_UNKNOWN_DOMAIN = -5,
00409    AUTH_PEER_NOT_DYNAMIC = -6,
00410    AUTH_ACL_FAILED = -7,
00411    AUTH_BAD_TRANSPORT = -8,
00412 };
00413 
00414 /*! \brief States for outbound registrations (with register= lines in sip.conf */
00415 enum sipregistrystate {
00416    REG_STATE_UNREGISTERED = 0,   /*!< We are not registered 
00417        *  \note Initial state. We should have a timeout scheduled for the initial
00418        * (or next) registration transmission, calling sip_reregister
00419        */
00420 
00421    REG_STATE_REGSENT,   /*!< Registration request sent 
00422        * \note sent initial request, waiting for an ack or a timeout to
00423        * retransmit the initial request.
00424       */
00425 
00426    REG_STATE_AUTHSENT,  /*!< We have tried to authenticate 
00427        * \note entered after transmit_register with auth info,
00428        * waiting for an ack.
00429        */
00430 
00431    REG_STATE_REGISTERED,   /*!< Registered and done */
00432 
00433    REG_STATE_REJECTED,  /*!< Registration rejected *
00434        * \note only used when the remote party has an expire larger than
00435        * our max-expire. This is a final state from which we do not
00436        * recover (not sure how correctly).
00437        */
00438 
00439    REG_STATE_TIMEOUT,   /*!< Registration timed out *
00440       * \note XXX unused */
00441 
00442    REG_STATE_NOAUTH, /*!< We have no accepted credentials
00443        * \note fatal - no chance to proceed */
00444 
00445    REG_STATE_FAILED, /*!< Registration failed after several tries
00446        * \note fatal - no chance to proceed */
00447 };
00448 
00449 /*! \brief Modes in which Asterisk can be configured to run SIP Session-Timers */
00450 enum st_mode {
00451         SESSION_TIMER_MODE_INVALID = 0, /*!< Invalid value */ 
00452         SESSION_TIMER_MODE_ACCEPT,      /*!< Honor inbound Session-Timer requests */
00453         SESSION_TIMER_MODE_ORIGINATE,   /*!< Originate outbound and honor inbound requests */
00454         SESSION_TIMER_MODE_REFUSE       /*!< Ignore inbound Session-Timers requests */
00455 };
00456 
00457 /*! \brief The entity playing the refresher role for Session-Timers */
00458 enum st_refresher {
00459         SESSION_TIMER_REFRESHER_AUTO,    /*!< Negotiated                      */
00460         SESSION_TIMER_REFRESHER_UAC,     /*!< Session is refreshed by the UAC */
00461         SESSION_TIMER_REFRESHER_UAS      /*!< Session is refreshed by the UAS */
00462 };
00463 
00464 /*! \brief Define some implemented SIP transports 
00465    \note Asterisk does not support SCTP or UDP/DTLS 
00466 */
00467 enum sip_transport {
00468    SIP_TRANSPORT_UDP = 1,     /*!< Unreliable transport for SIP, needs retransmissions */
00469    SIP_TRANSPORT_TCP = 1 << 1,   /*!< Reliable, but unsecure */
00470    SIP_TRANSPORT_TLS = 1 << 2,   /*!< TCP/TLS - reliable and secure transport for signalling */
00471 };
00472 
00473 /*! \brief definition of a sip proxy server
00474  *
00475  * For outbound proxies, this is allocated in the SIP peer dynamically or
00476  * statically as the global_outboundproxy. The pointer in a SIP message is just
00477  * a pointer and should *not* be de-allocated.
00478  */
00479 struct sip_proxy {
00480    char name[MAXHOSTNAMELEN];      /*!< DNS name of domain/host or IP */
00481    struct sockaddr_in ip;          /*!< Currently used IP address and port */
00482    time_t last_dnsupdate;          /*!< When this was resolved */
00483    enum sip_transport transport;
00484    int force;                      /*!< If it's an outbound proxy, Force use of this outbound proxy for all outbound requests */
00485    /* Room for a SRV record chain based on the name */
00486 };
00487 
00488 /*! \brief argument for the 'show channels|subscriptions' callback. */
00489 struct __show_chan_arg { 
00490    int fd;
00491    int subscriptions;
00492    int numchans;   /* return value */
00493 };
00494 
00495 
00496 /*! \brief States whether a SIP message can create a dialog in Asterisk. */
00497 enum can_create_dialog {
00498    CAN_NOT_CREATE_DIALOG,
00499    CAN_CREATE_DIALOG,
00500    CAN_CREATE_DIALOG_UNSUPPORTED_METHOD,
00501 };
00502 
00503 /*! \brief SIP Request methods known by Asterisk 
00504 
00505    \note Do _NOT_ make any changes to this enum, or the array following it;
00506    if you think you are doing the right thing, you are probably
00507    not doing the right thing. If you think there are changes
00508    needed, get someone else to review them first _before_
00509    submitting a patch. If these two lists do not match properly
00510    bad things will happen.
00511 */
00512 
00513 enum sipmethod {
00514    SIP_UNKNOWN,      /*!< Unknown response */
00515    SIP_RESPONSE,     /*!< Not request, response to outbound request */
00516    SIP_REGISTER,     /*!< Registration to the mothership, tell us where you are located */
00517    SIP_OPTIONS,      /*!< Check capabilities of a device, used for "ping" too */
00518    SIP_NOTIFY,    /*!< Status update, Part of the event package standard, result of a SUBSCRIBE or a REFER */
00519    SIP_INVITE,    /*!< Set up a session */
00520    SIP_ACK,    /*!< End of a three-way handshake started with INVITE. */
00521    SIP_PRACK,     /*!< Reliable pre-call signalling. Not supported in Asterisk. */
00522    SIP_BYE,    /*!< End of a session */
00523    SIP_REFER,     /*!< Refer to another URI (transfer) */
00524    SIP_SUBSCRIBE,    /*!< Subscribe for updates (voicemail, session status, device status, presence) */
00525    SIP_MESSAGE,      /*!< Text messaging */
00526    SIP_UPDATE,    /*!< Update a dialog. We can send UPDATE; but not accept it */
00527    SIP_INFO,      /*!< Information updates during a session */
00528    SIP_CANCEL,    /*!< Cancel an INVITE */
00529    SIP_PUBLISH,      /*!< Not supported in Asterisk */
00530    SIP_PING,      /*!< Not supported at all, no standard but still implemented out there */
00531 };
00532 
00533 /*! \brief The core structure to setup dialogs. We parse incoming messages by using
00534    structure and then route the messages according to the type.
00535 
00536       \note Note that sip_methods[i].id == i must hold or the code breaks */
00537 static const struct  cfsip_methods { 
00538    enum sipmethod id;
00539    int need_rtp;     /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
00540    char * const text;
00541    enum can_create_dialog can_create;
00542 } sip_methods[] = {
00543    { SIP_UNKNOWN,  RTP,    "-UNKNOWN-",   CAN_CREATE_DIALOG },
00544    { SIP_RESPONSE,    NO_RTP, "SIP/2.0",  CAN_NOT_CREATE_DIALOG },
00545    { SIP_REGISTER,    NO_RTP, "REGISTER",    CAN_CREATE_DIALOG },
00546    { SIP_OPTIONS,  NO_RTP, "OPTIONS",  CAN_CREATE_DIALOG },
00547    { SIP_NOTIFY,   NO_RTP, "NOTIFY",   CAN_CREATE_DIALOG },
00548    { SIP_INVITE,   RTP,    "INVITE",   CAN_CREATE_DIALOG },
00549    { SIP_ACK,   NO_RTP, "ACK",   CAN_NOT_CREATE_DIALOG },
00550    { SIP_PRACK,    NO_RTP, "PRACK",    CAN_NOT_CREATE_DIALOG },
00551    { SIP_BYE,   NO_RTP, "BYE",   CAN_NOT_CREATE_DIALOG },
00552    { SIP_REFER,    NO_RTP, "REFER",    CAN_CREATE_DIALOG },
00553    { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",  CAN_CREATE_DIALOG },
00554    { SIP_MESSAGE,  NO_RTP, "MESSAGE",  CAN_CREATE_DIALOG },
00555    { SIP_UPDATE,   NO_RTP, "UPDATE",   CAN_NOT_CREATE_DIALOG },
00556    { SIP_INFO,  NO_RTP, "INFO",  CAN_NOT_CREATE_DIALOG },
00557    { SIP_CANCEL,   NO_RTP, "CANCEL",   CAN_NOT_CREATE_DIALOG },
00558    { SIP_PUBLISH,  NO_RTP, "PUBLISH",  CAN_CREATE_DIALOG_UNSUPPORTED_METHOD },
00559    { SIP_PING,  NO_RTP, "PING",  CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
00560 };
00561 
00562 /*!  Define SIP option tags, used in Require: and Supported: headers 
00563    We need to be aware of these properties in the phones to use 
00564    the replace: header. We should not do that without knowing
00565    that the other end supports it... 
00566    This is nothing we can configure, we learn by the dialog
00567    Supported: header on the REGISTER (peer) or the INVITE
00568    (other devices)
00569    We are not using many of these today, but will in the future.
00570    This is documented in RFC 3261
00571 */
00572 #define SUPPORTED    1
00573 #define NOT_SUPPORTED      0
00574 
00575 /* SIP options */
00576 #define SIP_OPT_REPLACES   (1 << 0)
00577 #define SIP_OPT_100REL     (1 << 1)
00578 #define SIP_OPT_TIMER      (1 << 2)
00579 #define SIP_OPT_EARLY_SESSION (1 << 3)
00580 #define SIP_OPT_JOIN    (1 << 4)
00581 #define SIP_OPT_PATH    (1 << 5)
00582 #define SIP_OPT_PREF    (1 << 6)
00583 #define SIP_OPT_PRECONDITION  (1 << 7)
00584 #define SIP_OPT_PRIVACY    (1 << 8)
00585 #define SIP_OPT_SDP_ANAT   (1 << 9)
00586 #define SIP_OPT_SEC_AGREE  (1 << 10)
00587 #define SIP_OPT_EVENTLIST  (1 << 11)
00588 #define SIP_OPT_GRUU    (1 << 12)
00589 #define SIP_OPT_TARGET_DIALOG (1 << 13)
00590 #define SIP_OPT_NOREFERSUB (1 << 14)
00591 #define SIP_OPT_HISTINFO   (1 << 15)
00592 #define SIP_OPT_RESPRIORITY   (1 << 16)
00593 #define SIP_OPT_FROMCHANGE (1 << 17)
00594 #define SIP_OPT_RECLISTINV (1 << 18)
00595 #define SIP_OPT_RECLISTSUB (1 << 19)
00596 #define SIP_OPT_UNKNOWN    (1 << 20)
00597 
00598 
00599 /*! \brief List of well-known SIP options. If we get this in a require,
00600    we should check the list and answer accordingly. */
00601 static const struct cfsip_options {
00602    int id;        /*!< Bitmap ID */
00603    int supported;    /*!< Supported by Asterisk ? */
00604    char * const text;   /*!< Text id, as in standard */
00605 } sip_options[] = {  /* XXX used in 3 places */
00606    /* RFC3262: PRACK 100% reliability */
00607    { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" }, 
00608    /* RFC3959: SIP Early session support */
00609    { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED,   "early-session" },
00610    /* SIMPLE events:  RFC4662 */
00611    { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
00612    /* RFC 4916- Connected line ID updates */
00613    { SIP_OPT_FROMCHANGE,   NOT_SUPPORTED, "from-change" },
00614    /* GRUU: Globally Routable User Agent URI's */
00615    { SIP_OPT_GRUU,      NOT_SUPPORTED, "gruu" },
00616    /* RFC4244 History info */
00617    { SIP_OPT_HISTINFO,  NOT_SUPPORTED, "histinfo" },
00618    /* RFC3911: SIP Join header support */
00619    { SIP_OPT_JOIN,      NOT_SUPPORTED, "join" },
00620    /* Disable the REFER subscription, RFC 4488 */
00621    { SIP_OPT_NOREFERSUB,   NOT_SUPPORTED, "norefersub" },
00622    /* RFC3327: Path support */
00623    { SIP_OPT_PATH,      NOT_SUPPORTED, "path" },
00624    /* RFC3840: Callee preferences */
00625    { SIP_OPT_PREF,      NOT_SUPPORTED, "pref" },
00626    /* RFC3312: Precondition support */
00627    { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
00628    /* RFC3323: Privacy with proxies*/
00629    { SIP_OPT_PRIVACY,   NOT_SUPPORTED, "privacy" },
00630    /* RFC-ietf-sip-uri-list-conferencing-02.txt conference invite lists */
00631    { SIP_OPT_RECLISTINV,   NOT_SUPPORTED, "recipient-list-invite" },
00632    /* RFC-ietf-sip-uri-list-subscribe-02.txt - subscription lists */
00633    { SIP_OPT_RECLISTSUB,   NOT_SUPPORTED, "recipient-list-subscribe" },
00634    /* RFC3891: Replaces: header for transfer */
00635    { SIP_OPT_REPLACES,  SUPPORTED,  "replaces" },  
00636    /* One version of Polycom firmware has the wrong label */
00637    { SIP_OPT_REPLACES,  SUPPORTED,  "replace" },   
00638    /* RFC4412 Resource priorities */
00639    { SIP_OPT_RESPRIORITY,  NOT_SUPPORTED, "resource-priority" },
00640    /* RFC3329: Security agreement mechanism */
00641    { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
00642    /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
00643    { SIP_OPT_SDP_ANAT,  NOT_SUPPORTED, "sdp-anat" },
00644    /* RFC4028: SIP Session-Timers */
00645    { SIP_OPT_TIMER,  SUPPORTED,  "timer" },
00646    /* RFC4538: Target-dialog */
00647    { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "tdialog" },
00648 };
00649 
00650 
00651 /*! \brief SIP Methods we support 
00652    \todo This string should be set dynamically. We only support REFER and SUBSCRIBE is we have
00653    allowsubscribe and allowrefer on in sip.conf.
00654 */
00655 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY, INFO"
00656 
00657 /*! \brief SIP Extensions we support 
00658    \note This should be generated based on the previous array
00659       in combination with settings.
00660    \todo We should not have "timer" if it's disabled in the configuration file.
00661 */
00662 #define SUPPORTED_EXTENSIONS "replaces, timer" 
00663 
00664 /*! \brief Standard SIP unsecure port for UDP and TCP from RFC 3261. DO NOT CHANGE THIS */
00665 #define STANDARD_SIP_PORT  5060
00666 /*! \brief Standard SIP TLS port for sips: from RFC 3261. DO NOT CHANGE THIS */
00667 #define STANDARD_TLS_PORT  5061
00668 
00669 /*! \note in many SIP headers, absence of a port number implies port 5060,
00670  * and this is why we cannot change the above constant.
00671  * There is a limited number of places in asterisk where we could,
00672  * in principle, use a different "default" port number, but
00673  * we do not support this feature at the moment.
00674  * You can run Asterisk with SIP on a different port with a configuration
00675  * option. If you change this value, the signalling will be incorrect.
00676  */
00677 
00678 /*! \name DefaultValues Default values, set and reset in reload_config before reading configuration 
00679 
00680    These are default values in the source. There are other recommended values in the
00681    sip.conf.sample for new installations. These may differ to keep backwards compatibility,
00682    yet encouraging new behaviour on new installations 
00683  */
00684 /*@{*/ 
00685 #define DEFAULT_CONTEXT    "default"
00686 #define DEFAULT_MOHINTERPRET    "default"
00687 #define DEFAULT_MOHSUGGEST      ""
00688 #define DEFAULT_VMEXTEN    "asterisk"
00689 #define DEFAULT_CALLERID   "asterisk"
00690 #define DEFAULT_NOTIFYMIME    "application/simple-message-summary"
00691 #define DEFAULT_ALLOWGUEST TRUE
00692 #define DEFAULT_CALLCOUNTER   FALSE
00693 #define DEFAULT_SRVLOOKUP  TRUE     /*!< Recommended setting is ON */
00694 #define DEFAULT_COMPACTHEADERS   FALSE
00695 #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. */
00696 #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. */
00697 #define DEFAULT_TOS_VIDEO       0               /*!< Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions. */
00698 #define DEFAULT_TOS_TEXT        0               /*!< Text packets should be marked as XXXX XXXX, but the default is 0 to be compatible with previous versions. */
00699 #define DEFAULT_COS_SIP         4      /*!< Level 2 class of service for SIP signalling */
00700 #define DEFAULT_COS_AUDIO       5      /*!< Level 2 class of service for audio media  */
00701 #define DEFAULT_COS_VIDEO       6      /*!< Level 2 class of service for video media */
00702 #define DEFAULT_COS_TEXT        5      /*!< Level 2 class of service for text media (T.140) */
00703 #define DEFAULT_ALLOW_EXT_DOM TRUE     /*!< Allow external domains */
00704 #define DEFAULT_REALM      "asterisk"  /*!< Realm for HTTP digest authentication */
00705 #define DEFAULT_NOTIFYRINGING TRUE
00706 #define DEFAULT_PEDANTIC   FALSE
00707 #define DEFAULT_AUTOCREATEPEER   FALSE
00708 #define DEFAULT_QUALIFY    FALSE
00709 #define DEFAULT_REGEXTENONQUALIFY FALSE
00710 #define DEFAULT_T1MIN      100      /*!< 100 MS for minimal roundtrip time */
00711 #define DEFAULT_MAX_CALL_BITRATE (384)    /*!< Max bitrate for video */
00712 #ifndef DEFAULT_USERAGENT
00713 #define DEFAULT_USERAGENT "Asterisk PBX"  /*!< Default Useragent: header unless re-defined in sip.conf */
00714 #define DEFAULT_SDPSESSION "Asterisk PBX" /*!< Default SDP session name, (s=) header unless re-defined in sip.conf */
00715 #define DEFAULT_SDPOWNER "root"        /*!< Default SDP username field in (o=) header unless re-defined in sip.conf */
00716 #endif
00717 /*@}*/ 
00718 
00719 /*! \name DefaultSettings
00720    Default setttings are used as a channel setting and as a default when
00721    configuring devices 
00722 */
00723 /*@{*/ 
00724 static char default_context[AST_MAX_CONTEXT];
00725 static char default_subscribecontext[AST_MAX_CONTEXT];
00726 static char default_language[MAX_LANGUAGE];
00727 static char default_callerid[AST_MAX_EXTENSION];
00728 static char default_fromdomain[AST_MAX_EXTENSION];
00729 static char default_notifymime[AST_MAX_EXTENSION];
00730 static int default_qualify;      /*!< Default Qualify= setting */
00731 static char default_vmexten[AST_MAX_EXTENSION];
00732 static char default_mohinterpret[MAX_MUSICCLASS];  /*!< Global setting for moh class to use when put on hold */
00733 static char default_mohsuggest[MAX_MUSICCLASS];    /*!< Global setting for moh class to suggest when putting 
00734                                                     *   a bridged channel on hold */
00735 static char default_parkinglot[AST_MAX_CONTEXT]; /*!< Parkinglot */
00736 static int default_maxcallbitrate;  /*!< Maximum bitrate for call */
00737 static struct ast_codec_pref default_prefs;     /*!< Default codec prefs */
00738 
00739 /*! \brief a place to store all global settings for the sip channel driver */
00740 struct sip_settings {
00741    int peer_rtupdate;   /*!< G: Update database with registration data for peer? */
00742    int rtsave_sysname;  /*!< G: Save system name at registration? */
00743    int ignore_regexpire;   /*!< G: Ignore expiration of peer  */
00744 };
00745 
00746 static struct sip_settings sip_cfg;
00747 /*@}*/ 
00748 
00749 /*! \name GlobalSettings
00750    Global settings apply to the channel (often settings you can change in the general section
00751    of sip.conf
00752 */
00753 /*@{*/ 
00754 static int global_directrtpsetup;   /*!< Enable support for Direct RTP setup (no re-invites) */
00755 static int global_rtautoclear;      /*!< Realtime ?? */
00756 static int global_notifyringing; /*!< Send notifications on ringing */
00757 static int global_notifyhold;    /*!< Send notifications on hold */
00758 static int global_alwaysauthreject; /*!< Send 401 Unauthorized for all failing requests */
00759 static int global_srvlookup;     /*!< SRV Lookup on or off. Default is on */
00760 static int pedanticsipchecking;     /*!< Extra checking ?  Default off */
00761 static int autocreatepeer;    /*!< Auto creation of peers at registration? Default off. */
00762 static int global_match_auth_username;    /*!< Match auth username if available instead of From: Default off. */
00763 static int global_relaxdtmf;     /*!< Relax DTMF */
00764 static int global_rtptimeout;    /*!< Time out call if no RTP */
00765 static int global_rtpholdtimeout;   /*!< Time out call if no RTP during hold */
00766 static int global_rtpkeepalive;     /*!< Send RTP keepalives */
00767 static int global_reg_timeout;   
00768 static int global_regattempts_max;  /*!< Registration attempts before giving up */
00769 static int global_allowguest;    /*!< allow unauthenticated peers to connect? */
00770 static int global_callcounter;      /*!< Enable call counters for all devices. This is currently enabled by setting the peer
00771                   call-limit to 999. When we remove the call-limit from the code, we can make it
00772                   with just a boolean flag in the device structure */
00773 static int global_allowsubscribe;   /*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE 
00774                    the global setting is in globals_flags[1] */
00775 static unsigned int global_tos_sip;    /*!< IP type of service for SIP packets */
00776 static unsigned int global_tos_audio;     /*!< IP type of service for audio RTP packets */
00777 static unsigned int global_tos_video;     /*!< IP type of service for video RTP packets */
00778 static unsigned int global_tos_text;      /*!< IP type of service for text RTP packets */
00779 static unsigned int global_cos_sip;    /*!< 802.1p class of service for SIP packets */
00780 static unsigned int global_cos_audio;     /*!< 802.1p class of service for audio RTP packets */
00781 static unsigned int global_cos_video;     /*!< 802.1p class of service for video RTP packets */
00782 static unsigned int global_cos_text;      /*!< 802.1p class of service for text RTP packets */
00783 static int compactheaders;    /*!< send compact sip headers */
00784 static int recordhistory;     /*!< Record SIP history. Off by default */
00785 static int dumphistory;       /*!< Dump history to verbose before destroying SIP dialog */
00786 static char global_realm[MAXHOSTNAMELEN];       /*!< Default realm */
00787 static char global_regcontext[AST_MAX_CONTEXT];    /*!< Context for auto-extensions */
00788 static char global_useragent[AST_MAX_EXTENSION];   /*!< Useragent for the SIP channel */
00789 static char global_sdpsession[AST_MAX_EXTENSION];  /*!< SDP session name for the SIP channel */
00790 static char global_sdpowner[AST_MAX_EXTENSION]; /*!< SDP owner name for the SIP channel */
00791 static int allow_external_domains;  /*!< Accept calls to external SIP domains? */
00792 static int global_callevents;    /*!< Whether we send manager events or not */
00793 static int global_authfailureevents;      /*!< Whether we send authentication failure manager events or not. Default no. */
00794 static int global_t1;         /*!< T1 time */
00795 static int global_t1min;      /*!< T1 roundtrip time minimum */
00796 static int global_timer_b;             /*!< Timer B - RFC 3261 Section 17.1.1.2 */
00797 static int global_regextenonqualify;      /*!< Whether to add/remove regexten when qualifying peers */
00798 static int global_autoframing;            /*!< Turn autoframing on or off. */
00799 static enum transfermodes global_allowtransfer; /*!< SIP Refer restriction scheme */
00800 static struct sip_proxy global_outboundproxy;   /*!< Outbound proxy */
00801 static int global_matchexterniplocally;      /*!< Match externip/externhost setting against localnet setting */
00802 static int global_qualifyfreq;         /*!< Qualify frequency */
00803 
00804 
00805 /*! \brief Codecs that we support by default: */
00806 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
00807 
00808 static enum st_mode global_st_mode;           /*!< Mode of operation for Session-Timers           */
00809 static enum st_refresher global_st_refresher; /*!< Session-Timer refresher                        */
00810 static int global_min_se;                     /*!< Lowest threshold for session refresh interval  */
00811 static int global_max_se;                     /*!< Highest threshold for session refresh interval */
00812 
00813 /*@}*/ 
00814 
00815 /*! \brief Global list of addresses dynamic peers are not allowed to use */
00816 static struct ast_ha *global_contact_ha = NULL;
00817 static int global_dynamic_exclude_static = 0;
00818 
00819 /*! \name Object counters @{
00820  * \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
00821  * should be used to modify these values. */
00822 static int speerobjs = 0;                /*!< Static peers */
00823 static int rpeerobjs = 0;                /*!< Realtime peers */
00824 static int apeerobjs = 0;                /*!< Autocreated peer objects */
00825 static int regobjs = 0;                  /*!< Registry objects */
00826 /* }@ */
00827 
00828 static struct ast_flags global_flags[2] = {{0}};        /*!< global SIP_ flags */
00829 static char used_context[AST_MAX_CONTEXT];      /*!< name of automatically created context for unloading */
00830 
00831 
00832 AST_MUTEX_DEFINE_STATIC(netlock);
00833 
00834 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
00835    when it's doing something critical. */
00836 AST_MUTEX_DEFINE_STATIC(monlock);
00837 
00838 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
00839 
00840 /*! \brief This is the thread for the monitor which checks for input on the channels
00841    which are not currently in use.  */
00842 static pthread_t monitor_thread = AST_PTHREADT_NULL;
00843 
00844 static int sip_reloading = FALSE;                       /*!< Flag for avoiding multiple reloads at the same time */
00845 static enum channelreloadreason sip_reloadreason;       /*!< Reason for last reload/load of configuration */
00846 
00847 static struct sched_context *sched;     /*!< The scheduling context */
00848 static struct io_context *io;           /*!< The IO context */
00849 static int *sipsock_read_id;            /*!< ID of IO entry for sipsock FD */
00850 
00851 #define DEC_CALL_LIMIT  0
00852 #define INC_CALL_LIMIT  1
00853 #define DEC_CALL_RINGING 2
00854 #define INC_CALL_RINGING 3
00855 
00856 /*! \brief The SIP socket definition */
00857 struct sip_socket {
00858    enum sip_transport type;   /*!< UDP, TCP or TLS */
00859    int fd;           /*!< Filed descriptor, the actual socket */
00860    uint16_t port;
00861    struct ast_tcptls_session_instance *tcptls_session;   /* If tcp or tls, a socket manager */
00862 };
00863 
00864 /*! \brief sip_request: The data grabbed from the UDP socket
00865  *
00866  * \verbatim
00867  * Incoming messages: we first store the data from the socket in data[],
00868  * adding a trailing \0 to make string parsing routines happy.
00869  * Then call parse_request() and req.method = find_sip_method();
00870  * to initialize the other fields. The \r\n at the end of each line is   
00871  * replaced by \0, so that data[] is not a conforming SIP message anymore.
00872  * After this processing, rlPart1 is set to non-NULL to remember
00873  * that we can run get_header() on this kind of packet.
00874  *
00875  * parse_request() splits the first line as follows:
00876  * Requests have in the first line      method uri SIP/2.0
00877  *      rlPart1 = method; rlPart2 = uri;
00878  * Responses have in the first line     SIP/2.0 NNN description
00879  *      rlPart1 = SIP/2.0; rlPart2 = NNN + description;
00880  *
00881  * For outgoing packets, we initialize the fields with init_req() or init_resp()
00882  * (which fills the first line to "METHOD uri SIP/2.0" or "SIP/2.0 code text"),
00883  * and then fill the rest with add_header() and add_line().
00884  * The \r\n at the end of the line are still there, so the get_header()
00885  * and similar functions don't work on these packets. 
00886  * \endverbatim
00887  */
00888 struct sip_request {
00889    ptrdiff_t rlPart1;           /*!< Offset of the SIP Method Name or "SIP/2.0" protocol version */
00890    ptrdiff_t rlPart2;           /*!< Offset of the Request URI or Response Status */
00891    int len;                /*!< bytes used in data[], excluding trailing null terminator. Rarely used. */
00892    int headers;            /*!< # of SIP Headers */
00893    int method;             /*!< Method of this request */
00894    int lines;              /*!< Body Content */
00895    unsigned int sdp_start; /*!< the line number where the SDP begins */
00896    unsigned int sdp_end;   /*!< the line number where the SDP ends */
00897    char debug;    /*!< print extra debugging if non zero */
00898    char has_to_tag;  /*!< non-zero if packet has To: tag */
00899    char ignore;      /*!< if non-zero This is a re-transmit, ignore it */
00900    /* Array of offsets into the request string of each SIP header*/
00901    ptrdiff_t header[SIP_MAX_HEADERS];
00902    /* Array of offsets into the request string of each SDP line*/
00903    ptrdiff_t line[SIP_MAX_LINES];
00904    struct ast_str *data;   
00905    /* XXX Do we need to unref socket.ser when the request goes away? */
00906    struct sip_socket socket;  /*!< The socket used for this request */
00907    AST_LIST_ENTRY(sip_request) next;
00908 };
00909 
00910 /* \brief given a sip_request and an offset, return the char * that resides there
00911  *
00912  * It used to be that rlPart1, rlPart2, and the header and line arrays were character
00913  * pointers. They are now offsets into the ast_str portion of the sip_request structure.
00914  * To avoid adding a bunch of redundant pointer arithmetic to the code, this macro is
00915  * provided to retrieve the string at a particular offset within the request's buffer
00916  */
00917 #define REQ_OFFSET_TO_STR(req,offset) ((req)->data->str + ((req)->offset))
00918 
00919 /*! \brief structure used in transfers */
00920 struct sip_dual {
00921    struct ast_channel *chan1; /*!< First channel involved */
00922    struct ast_channel *chan2; /*!< Second channel involved */
00923    struct sip_request req;    /*!< Request that caused the transfer (REFER) */
00924    int seqno;        /*!< Sequence number */
00925 };
00926 
00927 struct sip_pkt;
00928 
00929 /*! \brief Parameters to the transmit_invite function */
00930 struct sip_invite_param {
00931    int addsipheaders;      /*!< Add extra SIP headers */
00932    const char *uri_options;   /*!< URI options to add to the URI */
00933    const char *vxml_url;      /*!< VXML url for Cisco phones */
00934    char *auth;       /*!< Authentication */
00935    char *authheader;    /*!< Auth header */
00936    enum sip_auth_type auth_type; /*!< Authentication type */
00937    const char *replaces;      /*!< Replaces header for call transfers */
00938    int transfer;        /*!< Flag - is this Invite part of a SIP transfer? (invite/replaces) */
00939 };
00940 
00941 /*! \brief Structure to save routing information for a SIP session */
00942 struct sip_route {
00943    struct sip_route *next;
00944    char hop[0];
00945 };
00946 
00947 /*! \brief Modes for SIP domain handling in the PBX */
00948 enum domain_mode {
00949    SIP_DOMAIN_AUTO,     /*!< This domain is auto-configured */
00950    SIP_DOMAIN_CONFIG,      /*!< This domain is from configuration */
00951 };
00952 
00953 /*! \brief Domain data structure. 
00954    \note In the future, we will connect this to a configuration tree specific
00955    for this domain
00956 */
00957 struct domain {
00958    char domain[MAXHOSTNAMELEN];     /*!< SIP domain we are responsible for */
00959    char context[AST_MAX_EXTENSION]; /*!< Incoming context for this domain */
00960    enum domain_mode mode;        /*!< How did we find this domain? */
00961    AST_LIST_ENTRY(domain) list;     /*!< List mechanics */
00962 };
00963 
00964 static AST_LIST_HEAD_STATIC(domain_list, domain);  /*!< The SIP domain list */
00965 
00966 
00967 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
00968 struct sip_history {
00969    AST_LIST_ENTRY(sip_history) list;
00970    char event[0]; /* actually more, depending on needs */
00971 };
00972 
00973 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
00974 
00975 /*! \brief sip_auth: Credentials for authentication to other SIP services */
00976 struct sip_auth {
00977    char realm[AST_MAX_EXTENSION];  /*!< Realm in which these credentials are valid */
00978    char username[256];             /*!< Username */
00979    char secret[256];               /*!< Secret */
00980    char md5secret[256];            /*!< MD5Secret */
00981    struct sip_auth *next;          /*!< Next auth structure in list */
00982 };
00983 
00984 /*! \name SIPflags
00985    Various flags for the flags field in the pvt structure 
00986    Trying to sort these up (one or more of the following):
00987    D: Dialog
00988    P: Peer/user
00989    G: Global flag
00990    When flags are used by multiple structures, it is important that
00991    they have a common layout so it is easy to copy them.
00992 */
00993 /*@{*/ 
00994 #define SIP_OUTGOING    (1 << 0) /*!< D: Direction of the last transaction in this dialog */
00995 #define SIP_RINGING     (1 << 2) /*!< D: Have sent 180 ringing */
00996 #define SIP_PROGRESS_SENT  (1 << 3) /*!< D: Have sent 183 message progress */
00997 #define SIP_NEEDREINVITE   (1 << 4) /*!< D: Do we need to send another reinvite? */
00998 #define SIP_PENDINGBYE     (1 << 5) /*!< D: Need to send bye after we ack? */
00999 #define SIP_GOTREFER    (1 << 6) /*!< D: Got a refer? */
01000 #define SIP_CALL_LIMIT     (1 << 7) /*!< D: Call limit enforced for this call */
01001 #define SIP_INC_COUNT      (1 << 8) /*!< D: Did this dialog increment the counter of in-use calls? */
01002 #define SIP_INC_RINGING    (1 << 9) /*!< D: Did this connection increment the counter of in-use calls? */
01003 #define SIP_DEFER_BYE_ON_TRANSFER   (1 << 10)   /*!< D: Do not hangup at first ast_hangup */
01004 
01005 #define SIP_PROMISCREDIR   (1 << 11)   /*!< DP: Promiscuous redirection */
01006 #define SIP_TRUSTRPID      (1 << 12)   /*!< DP: Trust RPID headers? */
01007 #define SIP_USEREQPHONE    (1 << 13)   /*!< DP: Add user=phone to numeric URI. Default off */
01008 #define SIP_USECLIENTCODE  (1 << 14)   /*!< DP: Trust X-ClientCode info message */
01009 
01010 /* DTMF flags - see str2dtmfmode() and dtmfmode2str() */
01011 #define SIP_DTMF     (7 << 15)   /*!< DP: DTMF Support: five settings, uses three bits */
01012 #define SIP_DTMF_RFC2833   (0 << 15)   /*!< DP: DTMF Support: RTP DTMF - "rfc2833" */
01013 #define SIP_DTMF_INBAND    (1 << 15)   /*!< DP: DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
01014 #define SIP_DTMF_INFO      (2 << 15)   /*!< DP: DTMF Support: SIP Info messages - "info" */
01015 #define SIP_DTMF_AUTO      (3 << 15)   /*!< DP: DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
01016 #define SIP_DTMF_SHORTINFO      (4 << 15)       /*!< DP: DTMF Support: SIP Info messages - "info" - short variant */
01017 
01018 /* NAT settings - see nat2str() */
01019 #define SIP_NAT         (3 << 18)   /*!< DP: four settings, uses two bits */
01020 #define SIP_NAT_NEVER      (0 << 18)   /*!< DP: No nat support */
01021 #define SIP_NAT_RFC3581    (1 << 18)   /*!< DP: NAT RFC3581 */
01022 #define SIP_NAT_ROUTE      (2 << 18)   /*!< DP: NAT Only ROUTE */
01023 #define SIP_NAT_ALWAYS     (3 << 18)   /*!< DP: NAT Both ROUTE and RFC3581 */
01024 
01025 /* re-INVITE related settings */
01026 #define SIP_REINVITE    (7 << 20)   /*!< DP: four settings, uses three bits */
01027 #define SIP_REINVITE_NONE  (0 << 20)   /*!< DP: no reinvite allowed */
01028 #define SIP_CAN_REINVITE   (1 << 20)   /*!< DP: allow peers to be reinvited to send media directly p2p */
01029 #define SIP_CAN_REINVITE_NAT  (2 << 20)   /*!< DP: allow media reinvite when new peer is behind NAT */
01030 #define SIP_REINVITE_UPDATE   (4 << 20)   /*!< DP: use UPDATE (RFC3311) when reinviting this peer */
01031 
01032 /* "insecure" settings - see insecure2str() */
01033 #define SIP_INSECURE    (3 << 23)   /*!< DP: three settings, uses two bits */
01034 #define SIP_INSECURE_NONE  (0 << 23)   /*!< DP: secure mode */
01035 #define SIP_INSECURE_PORT  (1 << 23)   /*!< DP: don't require matching port for incoming requests */
01036 #define SIP_INSECURE_INVITE   (1 << 24)   /*!< DP: don't require authentication for incoming INVITEs */
01037 
01038 /* Sending PROGRESS in-band settings */
01039 #define SIP_PROG_INBAND    (3 << 25)   /*!< DP: three settings, uses two bits */
01040 #define SIP_PROG_INBAND_NEVER (0 << 25)
01041 #define SIP_PROG_INBAND_NO (1 << 25)
01042 #define SIP_PROG_INBAND_YES   (2 << 25)
01043 
01044 #define SIP_SENDRPID    (1 << 29)   /*!< DP: Remote Party-ID Support */
01045 #define SIP_G726_NONSTANDARD  (1 << 31)   /*!< DP: Use non-standard packing for G726-32 data */
01046 
01047 /*! \brief Flags to copy from peer/user to dialog */
01048 #define SIP_FLAGS_TO_COPY \
01049    (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
01050     SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
01051     SIP_USEREQPHONE | SIP_INSECURE)
01052 /*@}*/ 
01053 
01054 /*! \name SIPflags2
01055    a second page of flags (for flags[1] */
01056 /*@{*/ 
01057 /* realtime flags */
01058 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0) /*!< GP: Should we keep RT objects in memory for extended time? */
01059 #define SIP_PAGE2_RTAUTOCLEAR    (1 << 2) /*!< GP: Should we clean memory from peers after expiry? */
01060 /* Space for addition of other realtime flags in the future */
01061 #define SIP_PAGE2_STATECHANGEQUEUE  (1 << 9) /*!< D: Unsent state pending change exists */
01062 
01063 #define SIP_PAGE2_RPORT_PRESENT         (1 << 10)       /*!< Was rport received in the Via header? */
01064 #define SIP_PAGE2_VIDEOSUPPORT      (1 << 14)   /*!< DP: Video supported if offered? */
01065 #define SIP_PAGE2_TEXTSUPPORT    (1 << 15)   /*!< GDP: Global text enable */
01066 #define SIP_PAGE2_ALLOWSUBSCRIBE (1 << 16)   /*!< GP: Allow subscriptions from this peer? */
01067 #define SIP_PAGE2_ALLOWOVERLAP      (1 << 17)   /*!< DP: Allow overlap dialing ? */
01068 #define SIP_PAGE2_SUBSCRIBEMWIONLY  (1 << 18)   /*!< GP: Only issue MWI notification if subscribed to */
01069 #define SIP_PAGE2_IGNORESDPVERSION  (1 << 19)   /*!< GDP: Ignore the SDP session version number we receive and treat all sessions as new */
01070 
01071 #define SIP_PAGE2_T38SUPPORT             (7 << 20) /*!< GDP: T.38 Fax Support */
01072 #define SIP_PAGE2_T38SUPPORT_UDPTL          (1 << 20) /*!< GDP: T.38 Fax Support (no error correction) */
01073 #define SIP_PAGE2_T38SUPPORT_UDPTL_FEC         (2 << 20) /*!< GDP: T.38 Fax Support (FEC error correction) */
01074 #define SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY   (4 << 20)   /*!< GDP: T.38 Fax Support (redundancy error correction) */
01075 
01076 #define SIP_PAGE2_CALL_ONHOLD    (3 << 23)   /*!< D: Call hold states: */
01077 #define SIP_PAGE2_CALL_ONHOLD_ACTIVE    (1 << 23)       /*!< D: Active hold */
01078 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR   (2 << 23)   /*!< D: One directional hold */
01079 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE (3 << 23)   /*!< D: Inactive hold */
01080 
01081 #define SIP_PAGE2_RFC2833_COMPENSATE    (1 << 25)  /*!< DP: Compensate for buggy RFC2833 implementations */
01082 #define SIP_PAGE2_BUGGY_MWI      (1 << 26)   /*!< DP: Buggy CISCO MWI fix */
01083 #define SIP_PAGE2_DIALOG_ESTABLISHED    (1 << 27)       /*!< 29: Has a dialog been established? */
01084 #define SIP_PAGE2_REGISTERTRYING        (1 << 29)       /*!< DP: Send 100 Trying on REGISTER attempts */
01085 #define SIP_PAGE2_UDPTL_DESTINATION     (1 << 30)       /*!< DP: Use source IP of RTP as destination if NAT is enabled */
01086 #define SIP_PAGE2_VIDEOSUPPORT_ALWAYS  (1 << 31)       /*!< DP: Always set up video, even if endpoints don't support it */
01087 
01088 #define SIP_PAGE2_FLAGS_TO_COPY \
01089    (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_IGNORESDPVERSION | \
01090    SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | \
01091    SIP_PAGE2_BUGGY_MWI | SIP_PAGE2_TEXTSUPPORT | \
01092    SIP_PAGE2_UDPTL_DESTINATION | SIP_PAGE2_VIDEOSUPPORT_ALWAYS)
01093 
01094 /*@}*/ 
01095 
01096 /*! \brief debugging state
01097  * We store separately the debugging requests from the config file
01098  * and requests from the CLI. Debugging is enabled if either is set
01099  * (which means that if sipdebug is set in the config file, we can
01100  * only turn it off by reloading the config).
01101  */
01102 enum sip_debug_e {
01103    sip_debug_none = 0,
01104    sip_debug_config = 1,
01105    sip_debug_console = 2,
01106 };
01107 
01108 static enum sip_debug_e sipdebug;
01109 
01110 /*! \brief extra debugging for 'text' related events.
01111  * At the moment this is set together with sip_debug_console.
01112  * \note It should either go away or be implemented properly.
01113  */
01114 static int sipdebug_text;
01115 
01116 /*! \brief T38 States for a call */
01117 enum t38state {
01118    T38_DISABLED = 0,                /*!< Not enabled */
01119    T38_LOCAL_REINVITE,              /*!< Offered from local - REINVITE */
01120    T38_PEER_REINVITE,               /*!< Offered from peer - REINVITE */
01121    T38_ENABLED                      /*!< Negotiated (enabled) */
01122 };
01123 
01124 /*! \brief T.38 channel settings (at some point we need to make this alloc'ed */
01125 struct t38properties {
01126    enum t38state state;    /*!< T.38 state */
01127    struct ast_control_t38_parameters our_parms;
01128    struct ast_control_t38_parameters their_parms;
01129 };
01130 
01131 /*! \brief Parameters to know status of transfer */
01132 enum referstatus {
01133    REFER_IDLE,                    /*!< No REFER is in progress */
01134    REFER_SENT,                    /*!< Sent REFER to transferee */
01135    REFER_RECEIVED,                /*!< Received REFER from transferrer */
01136    REFER_CONFIRMED,               /*!< Refer confirmed with a 100 TRYING (unused) */
01137    REFER_ACCEPTED,                /*!< Accepted by transferee */
01138    REFER_RINGING,                 /*!< Target Ringing */
01139    REFER_200OK,                   /*!< Answered by transfer target */
01140    REFER_FAILED,                  /*!< REFER declined - go on */
01141    REFER_NOAUTH                   /*!< We had no auth for REFER */
01142 };
01143 
01144 /*! \brief generic struct to map between strings and integers.
01145  * Fill it with x-s pairs, terminate with an entry with s = NULL;
01146  * Then you can call map_x_s(...) to map an integer to a string,
01147  * and map_s_x() for the string -> integer mapping.
01148  */
01149 struct _map_x_s {
01150    int x;
01151    const char *s;
01152 };              
01153 
01154 static const struct _map_x_s referstatusstrings[] = {
01155    { REFER_IDLE,     "<none>" },
01156    { REFER_SENT,     "Request sent" },
01157    { REFER_RECEIVED, "Request received" },
01158    { REFER_CONFIRMED,   "Confirmed" },
01159    { REFER_ACCEPTED, "Accepted" },
01160    { REFER_RINGING,  "Target ringing" },
01161    { REFER_200OK,    "Done" },
01162    { REFER_FAILED,      "Failed" },
01163    { REFER_NOAUTH,      "Failed - auth failure" },
01164    { -1,       NULL} /* terminator */
01165 };
01166 
01167 /*! \brief Structure to handle SIP transfers. Dynamically allocated when needed
01168    \note OEJ: Should be moved to string fields */
01169 struct sip_refer {
01170    char refer_to[AST_MAX_EXTENSION];      /*!< Place to store REFER-TO extension */
01171    char refer_to_domain[AST_MAX_EXTENSION];  /*!< Place to store REFER-TO domain */
01172    char refer_to_urioption[AST_MAX_EXTENSION];  /*!< Place to store REFER-TO uri options */
01173    char refer_to_context[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO context */
01174    char referred_by[AST_MAX_EXTENSION];      /*!< Place to store REFERRED-BY extension */
01175    char referred_by_name[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
01176    char refer_contact[AST_MAX_EXTENSION];    /*!< Place to store Contact info from a REFER extension */
01177    char replaces_callid[SIPBUFSIZE];         /*!< Replace info: callid */
01178    char replaces_callid_totag[SIPBUFSIZE/2];    /*!< Replace info: to-tag */
01179    char replaces_callid_fromtag[SIPBUFSIZE/2];     /*!< Replace info: from-tag */
01180    struct sip_pvt *refer_call;         /*!< Call we are referring. This is just a reference to a
01181                       * dialog owned by someone else, so we should not destroy
01182                       * it when the sip_refer object goes.
01183                       */
01184    int attendedtransfer;            /*!< Attended or blind transfer? */
01185    int localtransfer;            /*!< Transfer to local domain? */
01186    enum referstatus status;         /*!< REFER status */
01187 };
01188 
01189 
01190 /*! \brief Structure that encapsulates all attributes related to running 
01191  *   SIP Session-Timers feature on a per dialog basis.
01192  */
01193 struct sip_st_dlg {
01194    int st_active;                          /*!< Session-Timers on/off */ 
01195    int st_interval;                        /*!< Session-Timers negotiated session refresh interval */
01196    int st_schedid;                         /*!< Session-Timers ast_sched scheduler id */
01197    enum st_refresher st_ref;               /*!< Session-Timers session refresher */
01198    int st_expirys;                         /*!< Session-Timers number of expirys */
01199    int st_active_peer_ua;                  /*!< Session-Timers on/off in peer UA */
01200    int st_cached_min_se;                   /*!< Session-Timers cached Min-SE */
01201    int st_cached_max_se;                   /*!< Session-Timers cached Session-Expires */
01202    enum st_mode st_cached_mode;            /*!< Session-Timers cached M.O. */
01203    enum st_refresher st_cached_ref;        /*!< Session-Timers cached refresher */
01204 };
01205 
01206 
01207 /*! \brief Structure that encapsulates all attributes related to configuration 
01208  *   of SIP Session-Timers feature on a per user/peer basis.
01209  */
01210 struct sip_st_cfg {
01211    enum st_mode st_mode_oper;      /*!< Mode of operation for Session-Timers           */
01212    enum st_refresher st_ref;       /*!< Session-Timer refresher                        */
01213    int st_min_se;                  /*!< Lowest threshold for session refresh interval  */
01214    int st_max_se;                  /*!< Highest threshold for session refresh interval */
01215 };
01216 
01217 struct offered_media {
01218    int offered;
01219    char text[128];
01220 };
01221 
01222 /*! \brief Structure used for each SIP dialog, ie. a call, a registration, a subscribe.
01223  * Created and initialized by sip_alloc(), the descriptor goes into the list of
01224  * descriptors (dialoglist).
01225  */
01226 struct sip_pvt {
01227    struct sip_pvt *next;         /*!< Next dialog in chain */
01228    enum invitestates invitestate;      /*!< Track state of SIP_INVITEs */
01229    int method;          /*!< SIP method that opened this dialog */
01230    AST_DECLARE_STRING_FIELDS(
01231       AST_STRING_FIELD(callid);  /*!< Global CallID */
01232       AST_STRING_FIELD(randdata);   /*!< Random data */
01233       AST_STRING_FIELD(accountcode);   /*!< Account code */
01234       AST_STRING_FIELD(realm);   /*!< Authorization realm */
01235       AST_STRING_FIELD(nonce);   /*!< Authorization nonce */
01236       AST_STRING_FIELD(opaque);  /*!< Opaque nonsense */
01237       AST_STRING_FIELD(qop);     /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
01238       AST_STRING_FIELD(domain);  /*!< Authorization domain */
01239       AST_STRING_FIELD(from);    /*!< The From: header */
01240       AST_STRING_FIELD(useragent);  /*!< User agent in SIP request */
01241       AST_STRING_FIELD(exten);   /*!< Extension where to start */
01242       AST_STRING_FIELD(context); /*!< Context for this call */
01243       AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
01244       AST_STRING_FIELD(subscribeuri); /*!< Subscribecontext */
01245       AST_STRING_FIELD(fromdomain); /*!< Domain to show in the from field */
01246       AST_STRING_FIELD(fromuser);   /*!< User to show in the user field */
01247       AST_STRING_FIELD(fromname);   /*!< Name to show in the user field */
01248       AST_STRING_FIELD(tohost);  /*!< Host we should put in the "to" field */
01249       AST_STRING_FIELD(todnid);  /*!< DNID of this call (overrides host) */
01250       AST_STRING_FIELD(language);   /*!< Default language for this call */
01251       AST_STRING_FIELD(mohinterpret);  /*!< MOH class to use when put on hold */
01252       AST_STRING_FIELD(mohsuggest); /*!< MOH class to suggest when putting a peer on hold */
01253       AST_STRING_FIELD(rdnis);   /*!< Referring DNIS */
01254       AST_STRING_FIELD(redircause); /*!< Referring cause */
01255       AST_STRING_FIELD(theirtag);   /*!< Their tag */
01256       AST_STRING_FIELD(username);   /*!< [user] name */
01257       AST_STRING_FIELD(peername);   /*!< [peer] name, not set if [user] */
01258       AST_STRING_FIELD(authname);   /*!< Who we use for authentication */
01259       AST_STRING_FIELD(uri);     /*!< Original requested URI */
01260       AST_STRING_FIELD(okcontacturi);  /*!< URI from the 200 OK on INVITE */
01261       AST_STRING_FIELD(peersecret); /*!< Password */
01262       AST_STRING_FIELD(peermd5secret);
01263       AST_STRING_FIELD(cid_num); /*!< Caller*ID number */
01264       AST_STRING_FIELD(cid_name);   /*!< Caller*ID name */
01265       AST_STRING_FIELD(fullcontact);   /*!< The Contact: that the UA registers with us */
01266          /* we only store the part in <brackets> in this field. */
01267       AST_STRING_FIELD(our_contact);   /*!< Our contact header */
01268       AST_STRING_FIELD(rpid);    /*!< Our RPID header */
01269       AST_STRING_FIELD(rpid_from);  /*!< Our RPID From header */
01270       AST_STRING_FIELD(url);     /*!< URL to be sent with next message to peer */
01271       AST_STRING_FIELD(parkinglot);    /*!< Parkinglot */
01272    );
01273    char via[128];                          /*!< Via: header */
01274    struct sip_socket socket;     /*!< The socket used for this dialog */
01275    unsigned int ocseq;        /*!< Current outgoing seqno */
01276    unsigned int icseq;        /*!< Current incoming seqno */
01277    ast_group_t callgroup;        /*!< Call group */
01278    ast_group_t pickupgroup;      /*!< Pickup group */
01279    int lastinvite;            /*!< Last Cseq of invite */
01280    struct ast_flags flags[2];    /*!< SIP_ flags */
01281 
01282    /* boolean or small integers that don't belong in flags */
01283    char do_history;        /*!< Set if we want to record history */
01284    char alreadygone;       /*!< already destroyed by our peer */
01285    char needdestroy;       /*!< need to be destroyed by the monitor thread */
01286    char outgoing_call;        /*!< this is an outgoing call */
01287    char answered_elsewhere;      /*!< This call is cancelled due to answer on another channel */
01288    char novideo;           /*!< Didn't get video in invite, don't offer */
01289    char notext;            /*!< Text not supported  (?) */
01290 
01291    int timer_t1;           /*!< SIP timer T1, ms rtt */
01292    int timer_b;                            /*!< SIP timer B, ms */
01293    unsigned int sipoptions;      /*!< Supported SIP options on the other end */
01294    unsigned int reqsipoptions;      /*!< Required SIP options on the other end */
01295    struct ast_codec_pref prefs;     /*!< codec prefs */
01296    int capability;            /*!< Special capability (codec) */
01297    int jointcapability;       /*!< Supported capability at both ends (codecs) */
01298    int peercapability;        /*!< Supported peer capability */
01299    int prefcodec;          /*!< Preferred codec (outbound only) */
01300    int noncodeccapability;       /*!< DTMF RFC2833 telephony-event */
01301    int jointnoncodeccapability;            /*!< Joint Non codec capability */
01302    int redircodecs;        /*!< Redirect codecs */
01303    int maxcallbitrate;        /*!< Maximum Call Bitrate for Video Calls */ 
01304    struct sip_proxy *outboundproxy; /*!< Outbound proxy for this dialog. Use ref_proxy to set this instead of setting it directly */
01305    struct t38properties t38;     /*!< T38 settings */
01306    struct sockaddr_in udptlredirip; /*!< Where our T.38 UDPTL should be going if not to us */
01307    struct ast_udptl *udptl;      /*!< T.38 UDPTL session */
01308    int callingpres;        /*!< Calling presentation */
01309    int authtries;          /*!< Times we've tried to authenticate */
01310    int expiry;          /*!< How long we take to expire */
01311    long branch;            /*!< The branch identifier of this session */
01312    long invite_branch;        /*!< The branch used when we sent the initial INVITE */
01313    char tag[11];           /*!< Our tag for this session */
01314    int sessionid;          /*!< SDP Session ID */
01315    int sessionversion;        /*!< SDP Session Version */
01316    int64_t sessionversion_remote;      /*!< Remote UA's SDP Session Version */
01317    int session_modify;        /*!< Session modification request true/false  */
01318    struct sockaddr_in sa;        /*!< Our peer */
01319    struct sockaddr_in redirip;      /*!< Where our RTP should be going if not to us */
01320    struct sockaddr_in vredirip;     /*!< Where our Video RTP should be going if not to us */
01321    struct sockaddr_in tredirip;     /*!< Where our Text RTP should be going if not to us */
01322    time_t lastrtprx;       /*!< Last RTP received */
01323    time_t lastrtptx;       /*!< Last RTP sent */
01324    int rtptimeout;            /*!< RTP timeout time */
01325    struct sockaddr_in recv;      /*!< Received as */
01326    struct sockaddr_in ourip;     /*!< Our IP (as seen from the outside) */
01327    struct ast_channel *owner;    /*!< Who owns us (if we have an owner) */
01328    struct sip_route *route;      /*!< Head of linked list of routing steps (fm Record-Route) */
01329    int route_persistant;         /*!< Is this the "real" route? */
01330    struct ast_variable *notify_headers;    /*!< Custom notify type */
01331    struct sip_auth *peerauth;    /*!< Realm authentication */
01332    int noncecount;            /*!< Nonce-count */
01333    unsigned int stalenonce:1; /*!< Marks the current nonce as responded too */
01334    char lastmsg[256];         /*!< Last Message sent/received */
01335    int amaflags;           /*!< AMA Flags */
01336    int pendinginvite;         /*!< Any pending INVITE or state NOTIFY (in subscribe pvt's) ? (seqno of this) */
01337    int glareinvite;        /*!< A invite received while a pending invite is already present is stored here.  Its seqno is the
01338                   value. Since this glare invite's seqno is not the same as the pending invite's, it must be 
01339                   held in order to properly process acknowledgements for our 491 response. */
01340    struct sip_request initreq;      /*!< Latest request that opened a new transaction
01341                      within this dialog.
01342                      NOT the request that opened the dialog */
01343 
01344    int initid;          /*!< Auto-congest ID if appropriate (scheduler) */
01345    int waitid;          /*!< Wait ID for scheduler after 491 or other delays */
01346    int autokillid;            /*!< Auto-kill ID (scheduler) */
01347    int t38id;                              /*!< T.38 Response ID */
01348    enum transfermodes allowtransfer;   /*!< REFER: restriction scheme */
01349    struct sip_refer *refer;      /*!< REFER: SIP transfer data structure */
01350    enum subscriptiontype subscribed;   /*!< SUBSCRIBE: Is this dialog a subscription?  */
01351    int stateid;            /*!< SUBSCRIBE: ID for devicestate subscriptions */
01352    int laststate;          /*!< SUBSCRIBE: Last known extension state */
01353    int dialogver;          /*!< SUBSCRIBE: Version for subscription dialog-info */
01354 
01355    struct ast_dsp *vad;       /*!< Inband DTMF Detection dsp */
01356 
01357    struct sip_peer *relatedpeer;    /*!< If this dialog is related to a peer, which one 
01358                      Used in peerpoke, mwi subscriptions */
01359    struct sip_registry *registry;      /*!< If this is a REGISTER dialog, to which registry */
01360    struct ast_rtp *rtp;       /*!< RTP Session */
01361    struct ast_rtp *vrtp;         /*!< Video RTP session */
01362    struct ast_rtp *trtp;         /*!< Text RTP session */
01363    struct sip_pkt *packets;      /*!< Packets scheduled for re-transmission */
01364    struct sip_history_head *history;   /*!< History of this SIP dialog */
01365    size_t history_entries;       /*!< Number of entires in the history */
01366    struct ast_variable *chanvars;      /*!< Channel variables to set for inbound call */
01367    AST_LIST_HEAD_NOLOCK(request_queue, sip_request) request_queue; /*!< Requests that arrived but could not be processed immediately */
01368    int request_queue_sched_id;      /*!< Scheduler ID of any scheduled action to process queued requests */
01369    struct sip_invite_param *options;   /*!< Options for INVITE */
01370    int autoframing;        /*!< The number of Asters we group in a Pyroflax
01371                      before strolling to the Grokyzpå
01372                      (A bit unsure of this, please correct if
01373                      you know more) */
01374    struct sip_st_dlg *stimer;    /*!< SIP Session-Timers */              
01375    int red;             /*!< T.140 RTP Redundancy */
01376    int hangupcause;        /*!< Storage of hangupcause copied from our owner before we disconnect from the AST channel (only used at hangup) */
01377    /*! When receiving an SDP offer, it is important to take note of what media types were offered.
01378     * By doing this, even if we don't want to answer a particular media stream with something meaningful, we can
01379     * still put an m= line in our answer with the port set to 0.
01380     *
01381     * The reason for the length being 4 is that in this branch of Asterisk, the only media types supported are 
01382     * image, audio, text, and video. Therefore we need to keep track of which types of media were offered.
01383     *
01384     * Note that if we wanted to be 100% correct, we would keep a list of all media streams offered. That way we could respond
01385     * even to unknown media types, and we could respond to multiple streams of the same type. Such large-scale changes
01386     * are not a good idea for released branches, though, so we're compromising by just making sure that for the common cases:
01387     * audio and video, audio and T.38, and audio and text, we give the appropriate response to both media streams.
01388     *
01389     * The large-scale changes would be a good idea for implementing during an SDP rewrite.
01390     */
01391    struct offered_media offered_media[4];
01392 }; 
01393 
01394 /*! Max entires in the history list for a sip_pvt */
01395 #define MAX_HISTORY_ENTRIES 50
01396 
01397 /*! \brief
01398  * Here we implement the container for dialogs (sip_pvt), defining
01399  * generic wrapper functions to ease the transition from the current
01400  * implementation (a single linked list) to a different container.
01401  * In addition to a reference to the container, we need functions to lock/unlock
01402  * the container and individual items, and functions to add/remove
01403  * references to the individual items.
01404  */
01405 struct ao2_container *dialogs;
01406 
01407 #define sip_pvt_lock(x) ao2_lock(x)
01408 #define sip_pvt_trylock(x) ao2_trylock(x)
01409 #define sip_pvt_unlock(x) ao2_unlock(x)
01410 
01411 /*! \brief
01412  * when we create or delete references, make sure to use these
01413  * functions so we keep track of the refcounts.
01414  * To simplify the code, we allow a NULL to be passed to dialog_unref().
01415  */
01416 #ifdef REF_DEBUG
01417 #define dialog_ref(arg1,arg2) dialog_ref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
01418 #define dialog_unref(arg1,arg2) dialog_unref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
01419 
01420 static struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
01421 {
01422    if (p)
01423       _ao2_ref_debug(p, 1, tag, file, line, func);
01424    else
01425       ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
01426    return p;
01427 }
01428 
01429 static struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
01430 {
01431    if (p)
01432       _ao2_ref_debug(p, -1, tag, file, line, func);
01433    return NULL;
01434 }
01435 #else
01436 static struct sip_pvt *dialog_ref(struct sip_pvt *p, char *tag)
01437 {
01438    if (p)
01439       ao2_ref(p, 1);
01440    else
01441       ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
01442    return p;
01443 }
01444 
01445 static struct sip_pvt *dialog_unref(struct sip_pvt *p, char *tag)
01446 {
01447    if (p)
01448       ao2_ref(p, -1);
01449    return NULL;
01450 }
01451 #endif
01452 
01453 /*! \brief sip packet - raw format for outbound packets that are sent or scheduled for transmission
01454  * Packets are linked in a list, whose head is in the struct sip_pvt they belong to.
01455  * Each packet holds a reference to the parent struct sip_pvt.
01456  * This structure is allocated in __sip_reliable_xmit() and only for packets that
01457  * require retransmissions.
01458  */
01459 struct sip_pkt {
01460    struct sip_pkt *next;         /*!< Next packet in linked list */
01461    int retrans;            /*!< Retransmission number */
01462    int method;          /*!< SIP method for this packet */
01463    int seqno;           /*!< Sequence number */
01464    char is_resp;           /*!< 1 if this is a response packet (e.g. 200 OK), 0 if it is a request */
01465    char is_fatal;          /*!< non-zero if there is a fatal error */
01466    int response_code;      /*!< If this is a response, the response code */
01467    struct sip_pvt *owner;        /*!< Owner AST call */
01468    int retransid;          /*!< Retransmission ID */
01469    int timer_a;            /*!< SIP timer A, retransmission timer */
01470    int timer_t1;           /*!< SIP Timer T1, estimated RTT or 500 ms */
01471    int packetlen;          /*!< Length of packet */
01472    struct ast_str *data;
01473 }; 
01474 
01475 /*!
01476  * \brief A peer's mailbox
01477  *
01478  * We could use STRINGFIELDS here, but for only two strings, it seems like
01479  * too much effort ...
01480  */
01481 struct sip_mailbox {
01482    char *mailbox;
01483    char *context;
01484    /*! Associated MWI subscription */
01485    struct ast_event_sub *event_sub;
01486    AST_LIST_ENTRY(sip_mailbox) entry;
01487 };
01488 
01489 enum sip_peer_type {
01490    SIP_TYPE_PEER = (1 << 0),
01491    SIP_TYPE_USER = (1 << 1),
01492 };
01493 
01494 /*! \brief Structure for SIP peer data, we place calls to peers if registered  or fixed IP address (host) 
01495 */
01496 /* XXX field 'name' must be first otherwise sip_addrcmp() will fail, as will astobj2 hashing of the structure */
01497 struct sip_peer {
01498    char name[80];       /*!< peer->name is the unique name of this object */
01499    struct sip_socket socket;  /*!< Socket used for this peer */
01500    enum sip_transport default_outbound_transport;    /*!< Peer Registration may change the default outbound transport. */
01501    unsigned int transports:3; /*!< Transports (enum sip_transport) that are acceptable for this peer */
01502    char secret[80];     /*!< Password */
01503    char md5secret[80];     /*!< Password in MD5 */
01504    struct sip_auth *auth;     /*!< Realm authentication list */
01505    char context[AST_MAX_CONTEXT];   /*!< Default context for incoming calls */
01506    char subscribecontext[AST_MAX_CONTEXT];   /*!< Default context for subscriptions */
01507    char username[80];      /*!< Temporary username until registration */ 
01508    char accountcode[AST_MAX_ACCOUNT_CODE];   /*!< Account code */
01509    int amaflags;        /*!< AMA Flags (for billing) */
01510    char tohost[MAXHOSTNAMELEN];  /*!< If not dynamic, IP address */
01511    char regexten[AST_MAX_EXTENSION]; /*!< Extension to register (if regcontext is used) */
01512    char fromuser[80];      /*!< From: user when calling this peer */
01513    char fromdomain[MAXHOSTNAMELEN]; /*!< From: domain when calling this peer */
01514    char fullcontact[256];     /*!< Contact registered with us (not in sip.conf) */
01515    char cid_num[80];    /*!< Caller ID num */
01516    char cid_name[80];      /*!< Caller ID name */
01517    int callingpres;     /*!< Calling id presentation */
01518    int inUse;        /*!< Number of calls in use */
01519    int inRinging;       /*!< Number of calls ringing */
01520    int onHold;                     /*!< Peer has someone on hold */
01521    int call_limit;         /*!< Limit of concurrent calls */
01522    int busy_level;         /*!< Level of active channels where we signal busy */
01523    enum transfermodes allowtransfer;   /*! SIP Refer restriction scheme */
01524    char vmexten[AST_MAX_EXTENSION]; /*!< Dialplan extension for MWI notify message*/
01525    char language[MAX_LANGUAGE];  /*!<  Default language for prompts */
01526    char mohinterpret[MAX_MUSICCLASS];/*!<  Music on Hold class */
01527    char mohsuggest[MAX_MUSICCLASS];/*!<  Music on Hold class */
01528    char parkinglot[AST_MAX_CONTEXT];/*!<  Parkinglot */
01529    char useragent[256];    /*!<  User agent in SIP request (saved from registration) */
01530    struct ast_codec_pref prefs;  /*!<  codec prefs */
01531    int lastmsgssent;
01532    unsigned int sipoptions;   /*!<  Supported SIP options */
01533    struct ast_flags flags[2]; /*!<  SIP_ flags */
01534 
01535    /*! Mailboxes that this peer cares about */
01536    AST_LIST_HEAD_NOLOCK(, sip_mailbox) mailboxes;
01537 
01538    /* things that don't belong in flags */
01539    char is_realtime;    /*!< this is a 'realtime' peer */
01540    char rt_fromcontact;    /*!< P: copy fromcontact from realtime */
01541    char host_dynamic;      /*!< P: Dynamic Peers register with Asterisk */
01542    char selfdestruct;      /*!< P: Automatic peers need to destruct themselves */
01543    char the_mark;       /*!< moved out of ASTOBJ into struct proper; That which bears the_mark should be deleted! */
01544 
01545    int expire;       /*!<  When to expire this peer registration */
01546    int capability;         /*!<  Codec capability */
01547    int rtptimeout;         /*!<  RTP timeout */
01548    int rtpholdtimeout;     /*!<  RTP Hold Timeout */
01549    int rtpkeepalive;    /*!<  Send RTP packets for keepalive */
01550    ast_group_t callgroup;     /*!<  Call group */
01551    ast_group_t pickupgroup;   /*!<  Pickup group */
01552    struct sip_proxy *outboundproxy; /*!< Outbound proxy for this peer */
01553    struct ast_dnsmgr_entry *dnsmgr;/*!<  DNS refresh manager for peer */
01554    struct sockaddr_in addr;   /*!<  IP address of peer */
01555    int maxcallbitrate;     /*!< Maximum Bitrate for a video call */
01556 
01557    /* Qualification */
01558    struct sip_pvt *call;      /*!<  Call pointer */
01559    int pokeexpire;         /*!<  When to expire poke (qualify= checking) */
01560    int lastms;       /*!<  How long last response took (in ms), or -1 for no response */
01561    int maxms;        /*!<  Max ms we will accept for the host to be up, 0 to not monitor */
01562    int qualifyfreq;     /*!<  Qualification: How often to check for the host to be up */
01563    struct timeval ps;      /*!<  Time for sending SIP OPTION in sip_pke_peer() */
01564    struct sockaddr_in defaddr;   /*!<  Default IP address, used until registration */
01565    struct ast_ha *ha;      /*!<  Access control list */
01566    struct ast_ha *contactha;       /*!<  Restrict what IPs are allowed in the Contact header (for registration) */
01567    struct ast_variable *chanvars;   /*!<  Variables to set for channel created by user */
01568    struct sip_pvt *mwipvt;    /*!<  Subscription for MWI */
01569    int autoframing;
01570    struct sip_st_cfg stimer;  /*!<  SIP Session-Timers */
01571    int timer_t1;        /*!<  The maximum T1 value for the peer */
01572    int timer_b;         /*!<  The maximum timer B (transaction timeouts) */
01573    int deprecated_username; /*!< If it's a realtime peer, are they using the deprecated "username" instead of "defaultuser" */
01574    enum sip_peer_type type; /*!< Distinguish between "user" and "peer" types. This is used solely for CLI and manager commands */
01575 };
01576 
01577 
01578 /*! 
01579  * \brief Registrations with other SIP proxies
01580  *
01581  * Created by sip_register(), the entry is linked in the 'regl' list,
01582  * and never deleted (other than at 'sip reload' or module unload times).
01583  * The entry always has a pending timeout, either waiting for an ACK to
01584  * the REGISTER message (in which case we have to retransmit the request),
01585  * or waiting for the next REGISTER message to be sent (either the initial one,
01586  * or once the previously completed registration one expires).
01587  * The registration can be in one of many states, though at the moment
01588  * the handling is a bit mixed.
01589  */
01590 struct sip_registry {
01591    ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
01592    AST_DECLARE_STRING_FIELDS(
01593       AST_STRING_FIELD(callid);  /*!< Global Call-ID */
01594       AST_STRING_FIELD(realm);   /*!< Authorization realm */
01595       AST_STRING_FIELD(nonce);   /*!< Authorization nonce */
01596       AST_STRING_FIELD(opaque);  /*!< Opaque nonsense */
01597       AST_STRING_FIELD(qop);     /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
01598       AST_STRING_FIELD(domain);  /*!< Authorization domain */
01599       AST_STRING_FIELD(username);   /*!< Who we are registering as */
01600       AST_STRING_FIELD(authuser);   /*!< Who we *authenticate* as */
01601       AST_STRING_FIELD(hostname);   /*!< Domain or host we register to */
01602       AST_STRING_FIELD(secret);  /*!< Password in clear text */   
01603       AST_STRING_FIELD(md5secret);  /*!< Password in md5 */
01604       AST_STRING_FIELD(callback);   /*!< Contact extension */
01605       AST_STRING_FIELD(random);
01606       AST_STRING_FIELD(peername);   /*!< Peer registering to */
01607    );
01608    enum sip_transport transport; /*!< Transport for this registration UDP, TCP or TLS */
01609    int portno;       /*!<  Optional port override */
01610    int expire;       /*!< Sched ID of expiration */
01611    int expiry;       /*!< Value to use for the Expires header */
01612    int regattempts;     /*!< Number of attempts (since the last success) */
01613    int timeout;         /*!< sched id of sip_reg_timeout */
01614    int refresh;         /*!< How often to refresh */
01615    struct sip_pvt *call;      /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
01616    enum sipregistrystate regstate;  /*!< Registration state (see above) */
01617    struct timeval regtime;    /*!< Last successful registration time */
01618    int callid_valid;    /*!< 0 means we haven't chosen callid for this registry yet. */
01619    unsigned int ocseq;     /*!< Sequence number we got to for REGISTERs for this registry */
01620    struct ast_dnsmgr_entry *dnsmgr; /*!<  DNS refresh manager for register */
01621    struct sockaddr_in us;     /*!< Who the server thinks we are */
01622    int noncecount;         /*!< Nonce-count */
01623    char lastmsg[256];      /*!< Last Message sent/received */
01624 };
01625 
01626 /*! \brief Definition of a thread that handles a socket */
01627 struct sip_threadinfo {
01628    int stop;
01629    pthread_t threadid;
01630    struct ast_tcptls_session_instance *tcptls_session;
01631    enum sip_transport type;   /*!< We keep a copy of the type here so we can display it in the connection list */
01632    AST_LIST_ENTRY(sip_threadinfo) list;
01633 };
01634 
01635 /* --- Hash tables of various objects --------*/
01636 
01637 #ifdef LOW_MEMORY
01638 static int hash_peer_size = 17;
01639 static int hash_dialog_size = 17;
01640 static int hash_user_size = 17;
01641 #else
01642 static int hash_peer_size = 563; /*!< Size of peer hash table, prime number preferred! */
01643 static int hash_dialog_size = 563;
01644 static int hash_user_size = 563;
01645 #endif
01646 
01647 /*! \brief  The thread list of TCP threads */
01648 static AST_LIST_HEAD_STATIC(threadl, sip_threadinfo);
01649 
01650 /*! \brief  The peer list: Users, Peers and Friends */
01651 struct ao2_container *peers;
01652 struct ao2_container *peers_by_ip;
01653 
01654 /*! \brief  The register list: Other SIP proxies we register with and place calls to */
01655 static struct ast_register_list {
01656    ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
01657    int recheck;
01658 } regl;
01659 
01660 /*! \brief
01661  * \note The only member of the peer used here is the name field
01662  */
01663 static int peer_hash_cb(const void *obj, const int flags)
01664 {
01665    const struct sip_peer *peer = obj;
01666 
01667    return ast_str_case_hash(peer->name);
01668 }
01669 
01670 /*!
01671  * \note The only member of the peer used here is the name field
01672  */
01673 static int peer_cmp_cb(void *obj, void *arg, int flags)
01674 {
01675    struct sip_peer *peer = obj, *peer2 = arg;
01676 
01677    return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
01678 }
01679 
01680 /*!
01681  * \note the peer's addr struct provides to fields combined to make a key: the sin_addr.s_addr and sin_port fields.
01682  */
01683 static int peer_iphash_cb(const void *obj, const int flags)
01684 {
01685    const struct sip_peer *peer = obj;
01686    int ret1 = peer->addr.sin_addr.s_addr;
01687    if (ret1 < 0)
01688       ret1 = -ret1;
01689    
01690    if (ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT)) {
01691       return ret1;
01692    } else {
01693       return ret1 + peer->addr.sin_port;
01694    }
01695 }
01696 
01697 /*!
01698  * \note the peer's addr struct provides to fields combined to make a key: the sin_addr.s_addr and sin_port fields.
01699  */
01700 static int peer_ipcmp_cb(void *obj, void *arg, int flags)
01701 {
01702    struct sip_peer *peer = obj, *peer2 = arg;
01703 
01704    if (peer->addr.sin_addr.s_addr != peer2->addr.sin_addr.s_addr) {
01705       return 0;
01706    }
01707    
01708    if (!ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT) && !ast_test_flag(&peer2->flags[0], SIP_INSECURE_PORT)) {
01709       if (peer->addr.sin_port == peer2->addr.sin_port) {
01710          return CMP_MATCH | CMP_STOP;
01711       } else {
01712          return 0;
01713       }
01714    }
01715 
01716    return CMP_MATCH | CMP_STOP;
01717 }
01718 
01719 /*!
01720  * \note The only member of the dialog used here callid string
01721  */
01722 static int dialog_hash_cb(const void *obj, const int flags)
01723 {
01724    const struct sip_pvt *pvt = obj;
01725 
01726    return ast_str_case_hash(pvt->callid);
01727 }
01728 
01729 /*!
01730  * \note The only member of the dialog used here callid string
01731  */
01732 static int dialog_cmp_cb(void *obj, void *arg, int flags)
01733 {
01734    struct sip_pvt *pvt = obj, *pvt2 = arg;
01735    
01736    return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH | CMP_STOP : 0;
01737 }
01738 
01739 static int temp_pvt_init(void *);
01740 static void temp_pvt_cleanup(void *);
01741 
01742 /*! \brief A per-thread temporary pvt structure */
01743 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
01744 
01745 #ifdef LOW_MEMORY
01746 static void ts_ast_rtp_destroy(void *);
01747 
01748 AST_THREADSTORAGE_CUSTOM(ts_audio_rtp, NULL, ts_ast_rtp_destroy);
01749 AST_THREADSTORAGE_CUSTOM(ts_video_rtp, NULL, ts_ast_rtp_destroy);
01750 AST_THREADSTORAGE_CUSTOM(ts_text_rtp, NULL, ts_ast_rtp_destroy);
01751 #endif
01752 
01753 /*! \brief Authentication list for realm authentication 
01754  * \todo Move the sip_auth list to AST_LIST */
01755 static struct sip_auth *authl = NULL;
01756 
01757 
01758 /* --- Sockets and networking --------------*/
01759 
01760 /*! \brief Main socket for SIP communication.
01761  *
01762  * sipsock is shared between the SIP manager thread (which handles reload
01763  * requests), the io handler (sipsock_read()) and the user routines that
01764  * issue writes (using __sip_xmit()).
01765  * The socket is -1 only when opening fails (this is a permanent condition),
01766  * or when we are handling a reload() that changes its address (this is
01767  * a transient situation during which we might have a harmless race, see
01768  * below). Because the conditions for the race to be possible are extremely
01769  * rare, we don't want to pay the cost of locking on every I/O.
01770  * Rather, we remember that when the race may occur, communication is
01771  * bound to fail anyways, so we just live with this event and let
01772  * the protocol handle this above us.
01773  */
01774 static int sipsock  = -1;
01775 
01776 static struct sockaddr_in bindaddr; /*!< UDP: The address we bind to */
01777 
01778 /*! \brief our (internal) default address/port to put in SIP/SDP messages
01779  *  internip is initialized picking a suitable address from one of the
01780  * interfaces, and the same port number we bind to. It is used as the
01781  * default address/port in SIP messages, and as the default address
01782  * (but not port) in SDP messages.
01783  */
01784 static struct sockaddr_in internip;
01785 
01786 /*! \brief our external IP address/port for SIP sessions.
01787  * externip.sin_addr is only set when we know we might be behind
01788  * a NAT, and this is done using a variety of (mutually exclusive)
01789  * ways from the config file:
01790  *
01791  * + with "externip = host[:port]" we specify the address/port explicitly.
01792  *   The address is looked up only once when (re)loading the config file;
01793  * 
01794  * + with "externhost = host[:port]" we do a similar thing, but the
01795  *   hostname is stored in externhost, and the hostname->IP mapping
01796  *   is refreshed every 'externrefresh' seconds;
01797  * 
01798  * + with "stunaddr = host[:port]" we run queries every externrefresh seconds
01799  *   to the specified server, and store the result in externip.
01800  *
01801  * Other variables (externhost, externexpire, externrefresh) are used
01802  * to support the above functions.
01803  */
01804 static struct sockaddr_in externip;    /*!< External IP address if we are behind NAT */
01805 
01806 static char externhost[MAXHOSTNAMELEN];      /*!< External host name */
01807 static time_t externexpire;         /*!< Expiration counter for re-resolving external host name in dynamic DNS */
01808 static int externrefresh = 10;
01809 static struct sockaddr_in stunaddr;    /*!< stun server address */
01810 
01811 /*! \brief  List of local networks
01812  * We store "localnet" addresses from the config file into an access list,
01813  * marked as 'DENY', so the call to ast_apply_ha() will return
01814  * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
01815  * (i.e. presumably public) addresses.
01816  */
01817 static struct ast_ha *localaddr;    /*!< List of local networks, on the same side of NAT as this Asterisk */
01818 
01819 static int ourport_tcp;          /*!< The port used for TCP connections */
01820 static int ourport_tls;          /*!< The port used for TCP/TLS connections */
01821 static struct sockaddr_in debugaddr;
01822 
01823 static struct ast_config *notify_types;      /*!< The list of manual NOTIFY types we know how to send */
01824 
01825 /*! some list management macros. */
01826  
01827 #define UNLINK(element, head, prev) do {  \
01828    if (prev)            \
01829       (prev)->next = (element)->next;  \
01830    else              \
01831       (head) = (element)->next;  \
01832    } while (0)
01833 
01834 enum t38_action_flag {
01835    SDP_T38_NONE = 0, /*!< Do not modify T38 information at all */
01836    SDP_T38_INITIATE, /*!< Remote side has requested T38 with us */
01837    SDP_T38_ACCEPT,   /*!< Remote side accepted our T38 request */
01838 };
01839 
01840 /*---------------------------- Forward declarations of functions in chan_sip.c */
01841 /* Note: This is added to help splitting up chan_sip.c into several files
01842    in coming releases. */
01843 
01844 /*--- PBX interface functions */
01845 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
01846 static int sip_devicestate(void *data);
01847 static int sip_sendtext(struct ast_channel *ast, const char *text);
01848 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
01849 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
01850 static int sip_hangup(struct ast_channel *ast);
01851 static int sip_answer(struct ast_channel *ast);
01852 static struct ast_frame *sip_read(struct ast_channel *ast);
01853 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
01854 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
01855 static int sip_transfer(struct ast_channel *ast, const char *dest);
01856 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
01857 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
01858 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
01859 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
01860 static const char *sip_get_callid(struct ast_channel *chan);
01861 
01862 static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin);
01863 static int sip_standard_port(enum sip_transport type, int port);
01864 static int sip_prepare_socket(struct sip_pvt *p);
01865 static int sip_parse_host(char *line, int lineno, char **hostname, int *portnum, enum sip_transport *transport);
01866 
01867 /*--- Transmitting responses and requests */
01868 static int sipsock_read(int *id, int fd, short events, void *ignore);
01869 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len);
01870 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod);
01871 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01872 static int retrans_pkt(const void *data);
01873 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);
01874 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01875 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01876 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01877 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp);
01878 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
01879 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);
01880 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01881 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable);
01882 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
01883 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
01884 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
01885 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
01886 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
01887 static int transmit_info_with_vidupdate(struct sip_pvt *p);
01888 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
01889 static int transmit_refer(struct sip_pvt *p, const char *dest);
01890 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten);
01891 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
01892 static int transmit_notify_custom(struct sip_pvt *p, struct ast_variable *vars);
01893 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
01894 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
01895 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
01896 static void copy_request(struct sip_request *dst, const struct sip_request *src);
01897 static void receive_message(struct sip_pvt *p, struct sip_request *req);
01898 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req);
01899 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only);
01900 
01901 /*--- Dialog management */
01902 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
01903              int useglobal_nat, const int intended_method, struct sip_request *req);
01904 static int __sip_autodestruct(const void *data);
01905 static void sip_scheddestroy(struct sip_pvt *p, int ms);
01906 static int sip_cancel_destroy(struct sip_pvt *p);
01907 static struct sip_pvt *sip_destroy(struct sip_pvt *p);
01908 static void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist);
01909 static void *registry_unref(struct sip_registry *reg, char *tag);
01910 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist);
01911 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
01912 static void __sip_pretend_ack(struct sip_pvt *p);
01913 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
01914 static int auto_congest(const void *arg);
01915 static int update_call_counter(struct sip_pvt *fup, int event);
01916 static int hangup_sip2cause(int cause);
01917 static const char *hangup_cause2sip(int cause);
01918 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
01919 static void free_old_route(struct sip_route *route);
01920 static void list_route(struct sip_route *route);
01921 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
01922 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
01923                      struct sip_request *req, char *uri);
01924 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
01925 static void check_pendings(struct sip_pvt *p);
01926 static void *sip_park_thread(void *stuff);
01927 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
01928 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
01929 
01930 /*--- Codec handling / SDP */
01931 static void try_suggested_sip_codec(struct sip_pvt *p);
01932 static const char* get_sdp_iterate(int* start, struct sip_request *req, const char *name);
01933 static const char *get_sdp(struct sip_request *req, const char *name);
01934 static int find_sdp(struct sip_request *req);
01935 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
01936 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
01937               struct ast_str **m_buf, struct ast_str **a_buf,
01938               int debug, int *min_packet_size);
01939 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
01940             struct ast_str **m_buf, struct ast_str **a_buf,
01941             int debug);
01942 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
01943 static void do_setnat(struct sip_pvt *p, int natflags);
01944 static void stop_media_flows(struct sip_pvt *p);
01945 
01946 /*--- Authentication stuff */
01947 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
01948 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
01949 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
01950                 const char *secret, const char *md5secret, int sipmethod,
01951                 char *uri, enum xmittype reliable, int ignore);
01952 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
01953                      int sipmethod, char *uri, enum xmittype reliable,
01954                      struct sockaddr_in *sin, struct sip_peer **authpeer);
01955 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);
01956 
01957 /*--- Domain handling */
01958 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
01959 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
01960 static void clear_sip_domains(void);
01961 
01962 /*--- SIP realm authentication */
01963 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno);
01964 static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */
01965 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
01966 
01967 /*--- Misc functions */
01968 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t);
01969 static int sip_do_reload(enum channelreloadreason reason);
01970 static int reload_config(enum channelreloadreason reason);
01971 static int expire_register(const void *data);
01972 static void *do_monitor(void *data);
01973 static int restart_monitor(void);
01974 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
01975 /* static int sip_addrcmp(char *name, struct sockaddr_in *sin);   Support for peer matching */
01976 static int sip_refer_allocate(struct sip_pvt *p);
01977 static void ast_quiet_chan(struct ast_channel *chan);
01978 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
01979 /*!
01980  * \brief generic function for determining if a correct transport is being 
01981  * used to contact a peer
01982  *
01983  * this is done as a macro so that the "tmpl" var can be passed either a 
01984  * sip_request or a sip_peer 
01985  */
01986 #define check_request_transport(peer, tmpl) ({ \
01987    int ret = 0; \
01988    if (peer->socket.type == tmpl->socket.type) \
01989       ; \
01990    else if (!(peer->transports & tmpl->socket.type)) {\
01991       ast_log(LOG_ERROR, \
01992          "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
01993          get_transport(tmpl->socket.type), peer->name, get_transport_list(peer) \
01994          ); \
01995       ret = 1; \
01996    } else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
01997       ast_log(LOG_WARNING, \
01998          "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
01999          peer->name, get_transport(tmpl->socket.type) \
02000       ); \
02001    } else { \
02002       ast_debug(1, \
02003          "peer '%s' has contacted us over %s even though we prefer %s.\n", \
02004          peer->name, get_transport(tmpl->socket.type), get_transport(peer->socket.type) \
02005       ); \
02006    }\
02007    (ret); \
02008 })
02009 
02010 
02011 /*--- Device monitoring and Device/extension state/event handling */
02012 static int cb_extensionstate(char *context, char* exten, int state, void *data);
02013 static int sip_devicestate(void *data);
02014 static int sip_poke_noanswer(const void *data);
02015 static int sip_poke_peer(struct sip_peer *peer, int force);
02016 static void sip_poke_all_peers(void);
02017 static void sip_peer_hold(struct sip_pvt *p, int hold);
02018 static void mwi_event_cb(const struct ast_event *, void *);
02019 
02020 /*--- Applications, functions, CLI and manager command helpers */
02021 static const char *sip_nat_mode(const struct sip_pvt *p);
02022 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02023 static char *transfermode2str(enum transfermodes mode) attribute_const;
02024 static const char *nat2str(int nat) attribute_const;
02025 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
02026 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02027 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02028 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02029 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02030 static void  print_group(int fd, ast_group_t group, int crlf);
02031 static const char *dtmfmode2str(int mode) attribute_const;
02032 static int str2dtmfmode(const char *str) attribute_unused;
02033 static const char *insecure2str(int mode) attribute_const;
02034 static void cleanup_stale_contexts(char *new, char *old);
02035 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
02036 static const char *domain_mode_to_text(const enum domain_mode mode);
02037 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02038 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02039 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02040 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02041 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02042 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02043 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02044 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02045 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
02046 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
02047 static char *complete_sip_peer(const char *word, int state, int flags2);
02048 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
02049 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
02050 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
02051 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
02052 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
02053 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02054 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02055 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02056 static char *sip_do_debug_ip(int fd, char *arg);
02057 static char *sip_do_debug_peer(int fd, char *arg);
02058 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02059 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02060 static char *sip_do_history_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02061 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02062 static int sip_dtmfmode(struct ast_channel *chan, void *data);
02063 static int sip_addheader(struct ast_channel *chan, void *data);
02064 static int sip_do_reload(enum channelreloadreason reason);
02065 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02066 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
02067 
02068 /*--- Debugging 
02069    Functions for enabling debug per IP or fully, or enabling history logging for
02070    a SIP dialog
02071 */
02072 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to debuglog at end of dialog, before destroying data */
02073 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
02074 static inline int sip_debug_test_pvt(struct sip_pvt *p);
02075 
02076 
02077 /*! \brief Append to SIP dialog history 
02078    \return Always returns 0 */
02079 #define append_history(p, event, fmt , args... )   append_history_full(p, "%-15s " fmt, event, ## args)
02080 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
02081 static void sip_dump_history(struct sip_pvt *dialog);
02082 
02083 /*--- Device object handling */
02084 static struct sip_peer *temp_peer(const char *name);
02085 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime);
02086 static int update_call_counter(struct sip_pvt *fup, int event);
02087 static void sip_destroy_peer(struct sip_peer *peer);
02088 static void sip_destroy_peer_fn(void *peer);
02089 static void set_peer_defaults(struct sip_peer *peer);
02090 static struct sip_peer *temp_peer(const char *name);
02091 static void register_peer_exten(struct sip_peer *peer, int onoff);
02092 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int which_objects, int devstate_only);
02093 static int sip_poke_peer_s(const void *data);
02094 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
02095 static void reg_source_db(struct sip_peer *peer);
02096 static void destroy_association(struct sip_peer *peer);
02097 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
02098 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
02099 static void set_socket_transport(struct sip_socket *socket, int transport);
02100 
02101 /* Realtime device support */
02102 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);
02103 static void update_peer(struct sip_peer *p, int expire);
02104 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
02105 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername);
02106 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin, int devstate_only);
02107 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02108 
02109 /*--- Internal UA client handling (outbound registrations) */
02110 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p);
02111 static void sip_registry_destroy(struct sip_registry *reg);
02112 static int sip_register(const char *value, int lineno);
02113 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
02114 static int sip_reregister(const void *data);
02115 static int __sip_do_register(struct sip_registry *r);
02116 static int sip_reg_timeout(const void *data);
02117 static void sip_send_all_registers(void);
02118 static int sip_reinvite_retry(const void *data);
02119 
02120 /*--- Parsing SIP requests and responses */
02121 static void append_date(struct sip_request *req);  /* Append date to SIP packet */
02122 static int determine_firstline_parts(struct sip_request *req);
02123 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
02124 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
02125 static int find_sip_method(const char *msg);
02126 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
02127 static int parse_request(struct sip_request *req);
02128 static const char *get_header(const struct sip_request *req, const char *name);
02129 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
02130 static int method_match(enum sipmethod id, const char *name);
02131 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
02132 static char *get_in_brackets(char *tmp);
02133 static const char *find_alias(const char *name, const char *_default);
02134 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
02135 static int lws2sws(char *msgbuf, int len);
02136 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
02137 static char *remove_uri_parameters(char *uri);
02138 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
02139 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
02140 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
02141 static int set_address_from_contact(struct sip_pvt *pvt);
02142 static void check_via(struct sip_pvt *p, struct sip_request *req);
02143 static char *get_calleridname(const char *input, char *output, size_t outputsize);
02144 static int get_rpid_num(const char *input, char *output, int maxlen);
02145 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
02146 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
02147 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline);
02148 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
02149 
02150 /*-- TCP connection handling ---*/
02151 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session);
02152 static void *sip_tcp_worker_fn(void *);
02153 
02154 /*--- Constructing requests and responses */
02155 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
02156 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
02157 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
02158 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
02159 static int init_resp(struct sip_request *resp, const char *msg);
02160 static inline int resp_needs_contact(const char *msg, enum sipmethod method);
02161 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
02162 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
02163 static void build_via(struct sip_pvt *p);
02164 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
02165 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog);
02166 static char *generate_random_string(char *buf, size_t size);
02167 static void build_callid_pvt(struct sip_pvt *pvt);
02168 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
02169 static void make_our_tag(char *tagbuf, size_t len);
02170 static int add_header(struct sip_request *req, const char *var, const char *value);
02171 static int add_header_contentLength(struct sip_request *req, int len);
02172 static int add_line(struct sip_request *req, const char *line);
02173 static int add_text(struct sip_request *req, const char *text);
02174 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
02175 static int add_vidupdate(struct sip_request *req);
02176 static void add_route(struct sip_request *req, struct sip_route *route);
02177 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
02178 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
02179 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
02180 static void set_destination(struct sip_pvt *p, char *uri);
02181 static void append_date(struct sip_request *req);
02182 static void build_contact(struct sip_pvt *p);
02183 static void build_rpid(struct sip_pvt *p);
02184 
02185 /*------Request handling functions */
02186 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
02187 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);
02188 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
02189 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
02190 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
02191 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
02192 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
02193 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
02194 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
02195 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
02196 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin);
02197 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
02198 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);
02199 
02200 /*------Response handling functions */
02201 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02202 static void handle_response_notify(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02203 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02204 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02205 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02206 
02207 /*----- RTP interface functions */
02208 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);
02209 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02210 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02211 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02212 static int sip_get_codec(struct ast_channel *chan);
02213 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);
02214 
02215 /*------ T38 Support --------- */
02216 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
02217 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
02218 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
02219 static void change_t38_state(struct sip_pvt *p, int state);
02220 
02221 /*------ Session-Timers functions --------- */
02222 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
02223 static int  proc_session_timer(const void *vp);
02224 static void stop_session_timer(struct sip_pvt *p);
02225 static void start_session_timer(struct sip_pvt *p);
02226 static void restart_session_timer(struct sip_pvt *p);
02227 static const char *strefresher2str(enum st_refresher r);
02228 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
02229 static int parse_minse(const char *p_hdrval, int *const p_interval);
02230 static int st_get_se(struct sip_pvt *, int max);
02231 static enum st_refresher st_get_refresher(struct sip_pvt *);
02232 static enum st_mode st_get_mode(struct sip_pvt *);
02233 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
02234 
02235 
02236 /*! \brief Definition of this channel for PBX channel registration */
02237 static const struct ast_channel_tech sip_tech = {
02238    .type = "SIP",
02239    .description = "Session Initiation Protocol (SIP)",
02240    .capabilities = AST_FORMAT_AUDIO_MASK, /* all audio formats */
02241    .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
02242    .requester = sip_request_call,         /* called with chan unlocked */
02243    .devicestate = sip_devicestate,        /* called with chan unlocked (not chan-specific) */
02244    .call = sip_call,       /* called with chan locked */
02245    .send_html = sip_sendhtml,
02246    .hangup = sip_hangup,         /* called with chan locked */
02247    .answer = sip_answer,         /* called with chan locked */
02248    .read = sip_read,       /* called with chan locked */
02249    .write = sip_write,        /* called with chan locked */
02250    .write_video = sip_write,     /* called with chan locked */
02251    .write_text = sip_write,
02252    .indicate = sip_indicate,     /* called with chan locked */
02253    .transfer = sip_transfer,     /* called with chan locked */
02254    .fixup = sip_fixup,        /* called with chan locked */
02255    .send_digit_begin = sip_senddigit_begin,  /* called with chan unlocked */
02256    .send_digit_end = sip_senddigit_end,
02257    .bridge = ast_rtp_bridge,        /* XXX chan unlocked ? */
02258    .early_bridge = ast_rtp_early_bridge,
02259    .send_text = sip_sendtext,    /* called with chan locked */
02260    .func_channel_read = acf_channel_read,
02261    .queryoption = sip_queryoption,
02262    .get_pvt_uniqueid = sip_get_callid,
02263 };
02264 
02265 /*! \brief This version of the sip channel tech has no send_digit_begin
02266  * callback so that the core knows that the channel does not want
02267  * DTMF BEGIN frames.
02268  * The struct is initialized just before registering the channel driver,
02269  * and is for use with channels using SIP INFO DTMF.
02270  */
02271 static struct ast_channel_tech sip_tech_info;
02272 
02273 
02274 /*! \brief Working TLS connection configuration */
02275 static struct ast_tls_config sip_tls_cfg;
02276 
02277 /*! \brief Default TLS connection configuration */
02278 static struct ast_tls_config default_tls_cfg;
02279 
02280 /*! \brief The TCP server definition */
02281 static struct ast_tcptls_session_args sip_tcp_desc = {
02282    .accept_fd = -1,
02283    .master = AST_PTHREADT_NULL,
02284    .tls_cfg = NULL,
02285    .poll_timeout = -1,
02286    .name = "sip tcp server",
02287    .accept_fn = ast_tcptls_server_root,
02288    .worker_fn = sip_tcp_worker_fn,
02289 };
02290 
02291 /*! \brief The TCP/TLS server definition */
02292 static struct ast_tcptls_session_args sip_tls_desc = {
02293    .accept_fd = -1,
02294    .master = AST_PTHREADT_NULL,
02295    .tls_cfg = &sip_tls_cfg,
02296    .poll_timeout = -1,
02297    .name = "sip tls server",
02298    .accept_fn = ast_tcptls_server_root,
02299    .worker_fn = sip_tcp_worker_fn,
02300 };
02301 
02302 /* wrapper macro to tell whether t points to one of the sip_tech descriptors */
02303 #define IS_SIP_TECH(t)  ((t) == &sip_tech || (t) == &sip_tech_info)
02304 
02305 /*! \brief map from an integer value to a string.
02306  * If no match is found, return errorstring
02307  */
02308 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
02309 {
02310    const struct _map_x_s *cur;
02311 
02312    for (cur = table; cur->s; cur++)
02313       if (cur->x == x)
02314          return cur->s;
02315    return errorstring;
02316 }
02317 
02318 /*! \brief map from a string to an integer value, case insensitive.
02319  * If no match is found, return errorvalue.
02320  */
02321 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
02322 {
02323    const struct _map_x_s *cur;
02324 
02325    for (cur = table; cur->s; cur++)
02326       if (!strcasecmp(cur->s, s))
02327          return cur->x;
02328    return errorvalue;
02329 }
02330 
02331 
02332 /*! \brief Interface structure with callbacks used to connect to RTP module */
02333 static struct ast_rtp_protocol sip_rtp = {
02334    .type = "SIP",
02335    .get_rtp_info = sip_get_rtp_peer,
02336    .get_vrtp_info = sip_get_vrtp_peer,
02337    .get_trtp_info = sip_get_trtp_peer,
02338    .set_rtp_peer = sip_set_rtp_peer,
02339    .get_codec = sip_get_codec,
02340 };
02341 
02342 
02343 /*! \brief SIP TCP connection handler */
02344 static void *sip_tcp_worker_fn(void *data)
02345 {
02346    struct ast_tcptls_session_instance *tcptls_session = data;
02347 
02348    return _sip_tcp_helper_thread(NULL, tcptls_session);
02349 }
02350 
02351 /*! \brief SIP TCP thread management function */
02352 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session) 
02353 {
02354    int res, cl;
02355    struct sip_request req = { 0, } , reqcpy = { 0, };
02356    struct sip_threadinfo *me;
02357    char buf[1024] = "";
02358 
02359    me = ast_calloc(1, sizeof(*me));
02360 
02361    if (!me)
02362       goto cleanup2;
02363 
02364    me->threadid = pthread_self();
02365    me->tcptls_session = tcptls_session;
02366    if (tcptls_session->ssl)
02367       me->type = SIP_TRANSPORT_TLS;
02368    else
02369       me->type = SIP_TRANSPORT_TCP;
02370 
02371    ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
02372 
02373    AST_LIST_LOCK(&threadl);
02374    AST_LIST_INSERT_TAIL(&threadl, me, list);
02375    AST_LIST_UNLOCK(&threadl);
02376 
02377    if (!(req.data = ast_str_create(SIP_MIN_PACKET)))
02378       goto cleanup;
02379    if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET)))
02380       goto cleanup;
02381 
02382    for (;;) {
02383       struct ast_str *str_save;
02384 
02385       str_save = req.data;
02386       memset(&req, 0, sizeof(req));
02387       req.data = str_save;
02388       ast_str_reset(req.data);
02389 
02390       str_save = reqcpy.data;
02391       memset(&reqcpy, 0, sizeof(reqcpy));
02392       reqcpy.data = str_save;
02393       ast_str_reset(reqcpy.data);
02394 
02395       memset(buf, 0, sizeof(buf));
02396 
02397       if (tcptls_session->ssl) {
02398          set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
02399          req.socket.port = htons(ourport_tls);
02400       } else {
02401          set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
02402          req.socket.port = htons(ourport_tcp);
02403       }
02404       req.socket.fd = tcptls_session->fd;
02405       res = ast_wait_for_input(tcptls_session->fd, -1);
02406       if (res < 0) {
02407          ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
02408          goto cleanup;
02409       }
02410 
02411       /* Read in headers one line at a time */
02412       while (req.len < 4 || strncmp(REQ_OFFSET_TO_STR(&req, len - 4), "\r\n\r\n", 4)) {
02413          ast_mutex_lock(&tcptls_session->lock);
02414          if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
02415             ast_mutex_unlock(&tcptls_session->lock);
02416             goto cleanup;
02417          }
02418          ast_mutex_unlock(&tcptls_session->lock);
02419          if (me->stop) 
02420              goto cleanup;
02421          ast_str_append(&req.data, 0, "%s", buf);
02422          req.len = req.data->used;
02423       }
02424       copy_request(&reqcpy, &req);
02425       parse_request(&reqcpy);
02426       if (sscanf(get_header(&reqcpy, "Content-Length"), "%30d", &cl)) {
02427          while (cl > 0) {
02428             ast_mutex_lock(&tcptls_session->lock);
02429             if (!fread(buf, (cl < sizeof(buf)) ? cl : sizeof(buf), 1, tcptls_session->f)) {
02430                ast_mutex_unlock(&tcptls_session->lock);
02431                goto cleanup;
02432             }
02433             ast_mutex_unlock(&tcptls_session->lock);
02434             if (me->stop)
02435                goto cleanup;
02436             cl -= strlen(buf);
02437             ast_str_append(&req.data, 0, "%s", buf);
02438             req.len = req.data->used;
02439          }
02440       }
02441       req.socket.tcptls_session = tcptls_session;
02442       handle_request_do(&req, &tcptls_session->remote_address);
02443    }
02444 
02445 cleanup:
02446    AST_LIST_LOCK(&threadl);
02447    AST_LIST_REMOVE(&threadl, me, list);
02448    AST_LIST_UNLOCK(&threadl);
02449    ast_free(me);
02450 cleanup2:
02451    fclose(tcptls_session->f);
02452    tcptls_session->f = NULL;
02453    tcptls_session->fd = -1;
02454    if (reqcpy.data) {
02455       ast_free(reqcpy.data);
02456    }
02457 
02458    if (req.data) {
02459       ast_free(req.data);
02460       req.data = NULL;
02461    }
02462 
02463    ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
02464 
02465    ao2_ref(tcptls_session, -1);
02466    tcptls_session = NULL;
02467 
02468    return NULL;
02469 }
02470 
02471 
02472 /*!
02473  * helper functions to unreference various types of objects.
02474  * By handling them this way, we don't have to declare the
02475  * destructor on each call, which removes the chance of errors.
02476  */
02477 static void *unref_peer(struct sip_peer *peer, char *tag)
02478 {
02479    ao2_t_ref(peer, -1, tag);
02480    return NULL;
02481 }
02482 
02483 static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
02484 {
02485    ao2_t_ref(peer, 1, tag);
02486    return peer;
02487 }
02488 
02489 /*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
02490  *
02491  * This function sets pvt's outboundproxy pointer to the one referenced
02492  * by the proxy parameter. Because proxy may be a refcounted object, and
02493  * because pvt's old outboundproxy may also be a refcounted object, we need
02494  * to maintain the proper refcounts.
02495  *
02496  * \param pvt The sip_pvt for which we wish to set the outboundproxy
02497  * \param proxy The sip_proxy which we will point pvt towards.
02498  * \return Returns void
02499  */
02500 static struct sip_proxy *ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
02501 {
02502    struct sip_proxy *old_obproxy = pvt->outboundproxy;
02503    /* Cool, now get the refs correct */
02504    if (proxy && proxy != &global_outboundproxy) {
02505       ao2_ref(proxy, +1);
02506    }
02507    pvt->outboundproxy = proxy;
02508    if (old_obproxy && old_obproxy != &global_outboundproxy) {
02509       ao2_ref(old_obproxy, -1);
02510    }
02511    return proxy;
02512 }
02513 
02514 /*!
02515  * \brief Unlink a dialog from the dialogs container, as well as any other places
02516  * that it may be currently stored.
02517  *
02518  * \note A reference to the dialog must be held before calling this function, and this
02519  * function does not release that reference.
02520  */
02521 static void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist)
02522 {
02523    struct sip_pkt *cp;
02524 
02525    dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
02526 
02527    ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
02528 
02529    /* Unlink us from the owner (channel) if we have one */
02530    if (dialog->owner) {
02531       if (lockowner)
02532          ast_channel_lock(dialog->owner);
02533       ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
02534       dialog->owner->tech_pvt = dialog_unref(dialog->owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
02535       if (lockowner)
02536          ast_channel_unlock(dialog->owner);
02537    }
02538    if (dialog->registry) {
02539       if (dialog->registry->call == dialog)
02540          dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
02541       dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
02542    }
02543    if (dialog->stateid > -1) {
02544       ast_extension_state_del(dialog->stateid, NULL);
02545       dialog_unref(dialog, "removing extension_state, should unref the associated dialog ptr that was stored there.");
02546       dialog->stateid = -1; /* shouldn't we 'zero' this out? */
02547    }
02548    /* Remove link from peer to subscription of MWI */
02549    if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog)
02550       dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
02551    if (dialog->relatedpeer && dialog->relatedpeer->call == dialog)
02552       dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
02553 
02554    /* remove all current packets in this dialog */
02555    while((cp = dialog->packets)) {
02556       dialog->packets = dialog->packets->next;
02557       AST_SCHED_DEL(sched, cp->retransid);
02558       dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
02559       if (cp->data) {
02560          ast_free(cp->data);
02561       }
02562       ast_free(cp);
02563    }
02564 
02565    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"));
02566 
02567    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"));
02568    
02569    if (dialog->autokillid > -1)
02570       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"));
02571 
02572    if (dialog->request_queue_sched_id > -1) {
02573       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"));
02574    }
02575 
02576    if (dialog->t38id > -1) {
02577       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"));
02578    }
02579 
02580    dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
02581    return NULL;
02582 }
02583 
02584 static void *registry_unref(struct sip_registry *reg, char *tag)
02585 {
02586    ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
02587    ASTOBJ_UNREF(reg, sip_registry_destroy);
02588    return NULL;
02589 }
02590 
02591 /*! \brief Add object reference to SIP registry */
02592 static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
02593 {
02594    ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
02595    return ASTOBJ_REF(reg); /* Add pointer to registry in packet */
02596 }
02597 
02598 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
02599 static struct ast_udptl_protocol sip_udptl = {
02600    type: "SIP",
02601    get_udptl_info: sip_get_udptl_peer,
02602    set_udptl_peer: sip_set_udptl_peer,
02603 };
02604 
02605 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
02606    __attribute__((format(printf, 2, 3)));
02607 
02608 
02609 /*! \brief Convert transfer status to string */
02610 static const char *referstatus2str(enum referstatus rstatus)
02611 {
02612    return map_x_s(referstatusstrings, rstatus, "");
02613 }
02614 
02615 /*! \brief Initialize the initital request packet in the pvt structure.
02616    This packet is used for creating replies and future requests in
02617    a dialog */
02618 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
02619 {
02620    if (p->initreq.headers)
02621       ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
02622    else
02623       ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
02624    /* Use this as the basis */
02625    copy_request(&p->initreq, req);
02626    parse_request(&p->initreq);
02627    if (req->debug)
02628       ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
02629 }
02630 
02631 /*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
02632 static void sip_alreadygone(struct sip_pvt *dialog)
02633 {
02634    ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
02635    dialog->alreadygone = 1;
02636 }
02637 
02638 /*! Resolve DNS srv name or host name in a sip_proxy structure */
02639 static int proxy_update(struct sip_proxy *proxy)
02640 {
02641    /* if it's actually an IP address and not a name,
02642            there's no need for a managed lookup */
02643    if (!inet_aton(proxy->name, &proxy->ip.sin_addr)) {
02644       /* Ok, not an IP address, then let's check if it's a domain or host */
02645       /* XXX Todo - if we have proxy port, don't do SRV */
02646       if (ast_get_ip_or_srv(&proxy->ip, proxy->name, global_srvlookup ? "_sip._udp" : NULL) < 0) {
02647          ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
02648          return FALSE;
02649       }
02650    }
02651    proxy->last_dnsupdate = time(NULL);
02652    return TRUE;
02653 }
02654 
02655 /*! \brief Allocate and initialize sip proxy */
02656 static struct sip_proxy *proxy_allocate(char *name, char *port, int force)
02657 {
02658    struct sip_proxy *proxy;
02659 
02660    if (ast_strlen_zero(name)) {
02661       return NULL;
02662    }
02663 
02664    proxy = ao2_alloc(sizeof(*proxy), NULL);
02665    if (!proxy)
02666       return NULL;
02667    proxy->force = force;
02668    ast_copy_string(proxy->name, name, sizeof(proxy->name));
02669    proxy->ip.sin_port = htons((!ast_strlen_zero(port) ? atoi(port) : STANDARD_SIP_PORT));
02670    proxy_update(proxy);
02671    return proxy;
02672 }
02673 
02674 /*! \brief Get default outbound proxy or global proxy */
02675 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
02676 {
02677    if (peer && peer->outboundproxy) {
02678       if (sipdebug)
02679          ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
02680       append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
02681       return peer->outboundproxy;
02682    }
02683    if (global_outboundproxy.name[0]) {
02684       if (sipdebug)
02685          ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
02686       append_history(dialog, "OBproxy", "Using global obproxy %s", global_outboundproxy.name);
02687       return &global_outboundproxy;
02688    }
02689    if (sipdebug)
02690       ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
02691    return NULL;
02692 }
02693 
02694 /*! \brief returns true if 'name' (with optional trailing whitespace)
02695  * matches the sip method 'id'.
02696  * Strictly speaking, SIP methods are case SENSITIVE, but we do
02697  * a case-insensitive comparison to be more tolerant.
02698  * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
02699  */
02700 static int method_match(enum sipmethod id, const char *name)
02701 {
02702    int len = strlen(sip_methods[id].text);
02703    int l_name = name ? strlen(name) : 0;
02704    /* true if the string is long enough, and ends with whitespace, and matches */
02705    return (l_name >= len && name[len] < 33 &&
02706       !strncasecmp(sip_methods[id].text, name, len));
02707 }
02708 
02709 /*! \brief  find_sip_method: Find SIP method from header */
02710 static int find_sip_method(const char *msg)
02711 {
02712    int i, res = 0;
02713    
02714    if (ast_strlen_zero(msg))
02715       return 0;
02716    for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
02717       if (method_match(i, msg))
02718          res = sip_methods[i].id;
02719    }
02720    return res;
02721 }
02722 
02723 /*! \brief Parse supported header in incoming packet */
02724 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
02725 {
02726    char *next, *sep;
02727    char *temp;
02728    unsigned int profile = 0;
02729    int i, found;
02730 
02731    if (ast_strlen_zero(supported) )
02732       return 0;
02733    temp = ast_strdupa(supported);
02734 
02735    if (sipdebug)
02736       ast_debug(3, "Begin: parsing SIP \"Supported: %s\"\n", supported);
02737 
02738    for (next = temp; next; next = sep) {
02739       found = FALSE;
02740       if ( (sep = strchr(next, ',')) != NULL)
02741          *sep++ = '\0';
02742       next = ast_skip_blanks(next);
02743       if (sipdebug)
02744          ast_debug(3, "Found SIP option: -%s-\n", next);
02745       for (i = 0; i < ARRAY_LEN(sip_options); i++) {
02746          if (!strcasecmp(next, sip_options[i].text)) {
02747             profile |= sip_options[i].id;
02748             found = TRUE;
02749             if (sipdebug)
02750                ast_debug(3, "Matched SIP option: %s\n", next);
02751             break;
02752          }
02753       }
02754 
02755       /* This function is used to parse both Suported: and Require: headers.
02756       Let the caller of this function know that an unknown option tag was 
02757       encountered, so that if the UAC requires it then the request can be 
02758       rejected with a 420 response. */
02759       if (!found)
02760          profile |= SIP_OPT_UNKNOWN;
02761 
02762       if (!found && sipdebug) {
02763          if (!strncasecmp(next, "x-", 2))
02764             ast_debug(3, "Found private SIP option, not supported: %s\n", next);
02765          else
02766             ast_debug(3, "Found no match for SIP option: %s (Please file bug report!)\n", next);
02767       }
02768    }
02769 
02770    if (pvt)
02771       pvt->sipoptions = profile;
02772    return profile;
02773 }
02774 
02775 /*! \brief See if we pass debug IP filter */
02776 static inline int sip_debug_test_addr(const struct sockaddr_in *addr) 
02777 {
02778    if (!sipdebug)
02779       return 0;
02780    if (debugaddr.sin_addr.s_addr) {
02781       if (((ntohs(debugaddr.sin_port) != 0)
02782          && (debugaddr.sin_port != addr->sin_port))
02783          || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
02784          return 0;
02785    }
02786    return 1;
02787 }
02788 
02789 /*! \brief The real destination address for a write */
02790 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
02791 {
02792    if (p->outboundproxy)
02793       return &p->outboundproxy->ip;
02794 
02795    return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
02796 }
02797 
02798 /*! \brief Display SIP nat mode */
02799 static const char *sip_nat_mode(const struct sip_pvt *p)
02800 {
02801    return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
02802 }
02803 
02804 /*! \brief Test PVT for debugging output */
02805 static inline int sip_debug_test_pvt(struct sip_pvt *p) 
02806 {
02807    if (!sipdebug)
02808       return 0;
02809    return sip_debug_test_addr(sip_real_dst(p));
02810 }
02811    /*! \brief Return int representing a bit field of transport types found in const char *transport */
02812    static int get_transport_str2enum(const char *transport)
02813    {
02814    int res = 0;
02815 
02816    if (ast_strlen_zero(transport)) {
02817       return res;
02818    }
02819 
02820    if (!strcasecmp(transport, "udp")) {
02821       res |= SIP_TRANSPORT_UDP;
02822    }
02823    if (!strcasecmp(transport, "tcp")) {
02824       res |= SIP_TRANSPORT_TCP;
02825    }
02826    if (!strcasecmp(transport, "tls")) {
02827       res |= SIP_TRANSPORT_TLS;
02828    }
02829 
02830    return res;
02831 }
02832 
02833 static inline const char *get_transport_list(struct sip_peer *peer) {
02834    switch (peer->transports) {
02835       case SIP_TRANSPORT_UDP:
02836          return "UDP";
02837       case SIP_TRANSPORT_TCP:
02838          return "TCP";
02839       case SIP_TRANSPORT_TLS:
02840          return "TLS";
02841       case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
02842          return "TCP,UDP";
02843       case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
02844          return "TLS,UDP";
02845       case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
02846          return "TLS,TCP";
02847       default:
02848          return peer->transports ? 
02849             "TLS,TCP,UDP" : "UNKNOWN"; 
02850    }
02851 }
02852 
02853 static inline const char *get_transport(enum sip_transport t)
02854 {
02855    switch (t) {
02856    case SIP_TRANSPORT_UDP:
02857       return "UDP";
02858    case SIP_TRANSPORT_TCP:
02859       return "TCP";
02860    case SIP_TRANSPORT_TLS:
02861       return "TLS";
02862    }
02863 
02864    return "UNKNOWN";
02865 }
02866 
02867 static inline const char *get_transport_pvt(struct sip_pvt *p)
02868 {
02869    if (p->outboundproxy && p->outboundproxy->transport) {
02870       set_socket_transport(&p->socket, p->outboundproxy->transport);
02871    }
02872 
02873    return get_transport(p->socket.type);
02874 }
02875 
02876 /*! \brief Transmit SIP message 
02877    Sends a SIP request or response on a given socket (in the pvt)
02878    Called by retrans_pkt, send_request, send_response and 
02879    __sip_reliable_xmit
02880 */
02881 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len)
02882 {
02883    int res = 0;
02884    const struct sockaddr_in *dst = sip_real_dst(p);
02885 
02886    ast_debug(1, "Trying to put '%.10s' onto %s socket destined for %s:%d\n", data->str, get_transport_pvt(p), ast_inet_ntoa(dst->sin_addr), htons(dst->sin_port));
02887 
02888    if (sip_prepare_socket(p) < 0)
02889       return XMIT_ERROR;
02890 
02891    if (p->socket.tcptls_session)
02892       ast_mutex_lock(&p->socket.tcptls_session->lock);
02893 
02894    if (p->socket.type & SIP_TRANSPORT_UDP) {
02895       res = sendto(p->socket.fd, data->str, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
02896    } else if (p->socket.tcptls_session) {
02897       if (p->socket.tcptls_session->f) {
02898          res = ast_tcptls_server_write(p->socket.tcptls_session, data->str, len);
02899       } else {
02900          ast_debug(2, "No p->socket.tcptls_session->f len=%d\n", len);
02901       }
02902    } else {
02903       ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
02904       return XMIT_ERROR;
02905    }
02906 
02907    if (p->socket.tcptls_session)
02908       ast_mutex_unlock(&p->socket.tcptls_session->lock);
02909 
02910    if (res == -1) {
02911       switch (errno) {
02912       case EBADF:       /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
02913       case EHOSTUNREACH:   /* Host can't be reached */
02914       case ENETDOWN:       /* Inteface down */
02915       case ENETUNREACH: /* Network failure */
02916       case ECONNREFUSED:      /* ICMP port unreachable */ 
02917          res = XMIT_ERROR; /* Don't bother with trying to transmit again */
02918       }
02919    }
02920    if (res != len)
02921       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));
02922 
02923    return res;
02924 }
02925 
02926 /*! \brief Build a Via header for a request */
02927 static void build_via(struct sip_pvt *p)
02928 {
02929    /* Work around buggy UNIDEN UIP200 firmware */
02930    const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
02931 
02932    /* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
02933    snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s:%d;branch=z9hG4bK%08x%s",
02934        get_transport_pvt(p),
02935        ast_inet_ntoa(p->ourip.sin_addr),
02936        ntohs(p->ourip.sin_port), (int) p->branch, rport);
02937 }
02938 
02939 /*! \brief NAT fix - decide which IP address to use for Asterisk server?
02940  *
02941  * Using the localaddr structure built up with localnet statements in sip.conf
02942  * apply it to their address to see if we need to substitute our
02943  * externip or can get away with our internal bindaddr
02944  * 'us' is always overwritten.
02945  */
02946 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p)
02947 {
02948    struct sockaddr_in theirs;
02949    /* Set want_remap to non-zero if we want to remap 'us' to an externally
02950     * reachable IP address and port. This is done if:
02951     * 1. we have a localaddr list (containing 'internal' addresses marked
02952     *    as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
02953     *    and AST_SENSE_ALLOW on 'external' ones);
02954     * 2. either stunaddr or externip is set, so we know what to use as the
02955     *    externally visible address;
02956     * 3. the remote address, 'them', is external;
02957     * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
02958     *    when passed to ast_apply_ha() so it does need to be remapped.
02959     *    This fourth condition is checked later.
02960     */
02961    int want_remap;
02962 
02963    *us = internip;      /* starting guess for the internal address */
02964    /* now ask the system what would it use to talk to 'them' */
02965    ast_ouraddrfor(them, &us->sin_addr);
02966    theirs.sin_addr = *them;
02967 
02968    want_remap = localaddr &&
02969       (externip.sin_addr.s_addr || stunaddr.sin_addr.s_addr) &&
02970       ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
02971 
02972    if (want_remap &&
02973        (!global_matchexterniplocally || !ast_apply_ha(localaddr, us)) ) {
02974       /* if we used externhost or stun, see if it is time to refresh the info */
02975       if (externexpire && time(NULL) >= externexpire) {
02976          if (stunaddr.sin_addr.s_addr) {
02977             ast_stun_request(sipsock, &stunaddr, NULL, &externip);
02978          } else {
02979             if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
02980                ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
02981          }
02982          externexpire = time(NULL) + externrefresh;
02983       }
02984       if (externip.sin_addr.s_addr)
02985          *us = externip;
02986       else
02987          ast_log(LOG_WARNING, "stun failed\n");
02988       ast_debug(1, "Target address %s is not local, substituting externip\n", 
02989          ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
02990    } else if (p) {
02991       /* no remapping, but we bind to a specific address, so use it. */
02992       switch (p->socket.type) {
02993       case SIP_TRANSPORT_TCP:
02994          if (sip_tcp_desc.local_address.sin_addr.s_addr) {
02995             *us = sip_tcp_desc.local_address;
02996          } else {
02997             us->sin_port = sip_tcp_desc.local_address.sin_port;
02998          }
02999          break;
03000       case SIP_TRANSPORT_TLS:
03001          if (sip_tls_desc.local_address.sin_addr.s_addr) {
03002             *us = sip_tls_desc.local_address;
03003          } else {
03004             us->sin_port = sip_tls_desc.local_address.sin_port;
03005          }
03006             break;
03007       case SIP_TRANSPORT_UDP:
03008          /* fall through on purpose */
03009       default:
03010          if (bindaddr.sin_addr.s_addr) {
03011             *us = bindaddr;
03012          }
03013       }
03014    } else if (bindaddr.sin_addr.s_addr) {
03015       *us = bindaddr;
03016    }
03017    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));
03018 }
03019 
03020 /*! \brief Append to SIP dialog history with arg list  */
03021 static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
03022 {
03023    char buf[80], *c = buf; /* max history length */
03024    struct sip_history *hist;
03025    int l;
03026 
03027    vsnprintf(buf, sizeof(buf), fmt, ap);
03028    strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
03029    l = strlen(buf) + 1;
03030    if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
03031       return;
03032    if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
03033       ast_free(hist);
03034       return;
03035    }
03036    memcpy(hist->event, buf, l);
03037    if (p->history_entries == MAX_HISTORY_ENTRIES) {
03038       struct sip_history *oldest;
03039       oldest = AST_LIST_REMOVE_HEAD(p->history, list);
03040       p->history_entries--;
03041       ast_free(oldest);
03042    }
03043    AST_LIST_INSERT_TAIL(p->history, hist, list);
03044    p->history_entries++;
03045 }
03046 
03047 /*! \brief Append to SIP dialog history with arg list  */
03048 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03049 {
03050    va_list ap;
03051 
03052    if (!p)
03053       return;
03054 
03055    if (!p->do_history && !recordhistory && !dumphistory)
03056       return;
03057 
03058    va_start(ap, fmt);
03059    append_history_va(p, fmt, ap);
03060    va_end(ap);
03061 
03062    return;
03063 }
03064 
03065 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
03066 static int retrans_pkt(const void *data)
03067 {
03068    struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
03069    int reschedule = DEFAULT_RETRANS;
03070    int xmitres = 0;
03071    
03072    /* Lock channel PVT */
03073    sip_pvt_lock(pkt->owner);
03074 
03075    if (pkt->retrans < MAX_RETRANS) {
03076       pkt->retrans++;
03077       if (!pkt->timer_t1) {   /* Re-schedule using timer_a and timer_t1 */
03078          if (sipdebug)
03079             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);
03080       } else {
03081          int siptimer_a;
03082 
03083          if (sipdebug)
03084             ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
03085          if (!pkt->timer_a)
03086             pkt->timer_a = 2 ;
03087          else
03088             pkt->timer_a = 2 * pkt->timer_a;
03089  
03090          /* For non-invites, a maximum of 4 secs */
03091          siptimer_a = pkt->timer_t1 * pkt->timer_a;   /* Double each time */
03092          if (pkt->method != SIP_INVITE && siptimer_a > 4000)
03093             siptimer_a = 4000;
03094       
03095          /* Reschedule re-transmit */
03096          reschedule = siptimer_a;
03097          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);
03098       } 
03099 
03100       if (sip_debug_test_pvt(pkt->owner)) {
03101          const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
03102          ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
03103             pkt->retrans, sip_nat_mode(pkt->owner),
03104             ast_inet_ntoa(dst->sin_addr),
03105             ntohs(dst->sin_port), pkt->data->str);
03106       }
03107 
03108       append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
03109       xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
03110       sip_pvt_unlock(pkt->owner);
03111       if (xmitres == XMIT_ERROR)
03112          ast_log(LOG_WARNING, "Network error on retransmit in dialog %s\n", pkt->owner->callid);
03113       else 
03114          return  reschedule;
03115    } 
03116    /* Too many retries */
03117    if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
03118       if (pkt->is_fatal || sipdebug)   /* Tell us if it's critical or if we're debugging */
03119          ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s) -- See doc/sip-retransmit.txt.\n",
03120             pkt->owner->callid, pkt->seqno,
03121             pkt->is_fatal ? "Critical" : "Non-critical", pkt->is_resp ? "Response" : "Request");
03122    } else if (pkt->method == SIP_OPTIONS && sipdebug) {
03123          ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s)  -- See doc/sip-retransmit.txt.\n", pkt->owner->callid);
03124 
03125    } 
03126    if (xmitres == XMIT_ERROR) {
03127       ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
03128       append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03129    } else 
03130       append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03131       
03132    pkt->retransid = -1;
03133 
03134    if (pkt->is_fatal) {
03135       while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
03136          sip_pvt_unlock(pkt->owner);   /* SIP_PVT, not channel */
03137          usleep(1);
03138          sip_pvt_lock(pkt->owner);
03139       }
03140 
03141       if (pkt->owner->owner && !pkt->owner->owner->hangupcause) 
03142          pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
03143       
03144       if (pkt->owner->owner) {
03145          sip_alreadygone(pkt->owner);
03146          ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet (see doc/sip-retransmit.txt).\n", pkt->owner->callid);
03147          ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_PROTOCOL_ERROR);
03148          ast_channel_unlock(pkt->owner->owner);
03149       } else {
03150          /* If no channel owner, destroy now */
03151 
03152          /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
03153          if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
03154             pkt->owner->needdestroy = 1;
03155             sip_alreadygone(pkt->owner);
03156             append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
03157          }
03158       }
03159    }
03160 
03161    if (pkt->method == SIP_BYE) {
03162       /* We're not getting answers on SIP BYE's.  Tear down the call anyway. */
03163       if (pkt->owner->owner) 
03164          ast_channel_unlock(pkt->owner->owner);
03165       append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
03166       pkt->owner->needdestroy = 1;
03167    }
03168 
03169    /* Remove the packet */
03170    for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
03171       if (cur == pkt) {
03172          UNLINK(cur, pkt->owner->packets, prev);
03173          sip_pvt_unlock(pkt->owner);
03174          if (pkt->owner)
03175             pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03176          if (pkt->data)
03177             ast_free(pkt->data);
03178          pkt->data = NULL;
03179          ast_free(pkt);
03180          return 0;
03181       }
03182    }
03183    /* error case */
03184    ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
03185    sip_pvt_unlock(pkt->owner);
03186    return 0;
03187 }
03188 
03189 /*! \brief Transmit packet with retransmits 
03190    \return 0 on success, -1 on failure to allocate packet 
03191 */
03192 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)
03193 {
03194    struct sip_pkt *pkt = NULL;
03195    int siptimer_a = DEFAULT_RETRANS;
03196    int xmitres = 0;
03197    int respid;
03198 
03199    if (sipmethod == SIP_INVITE) {
03200       /* Note this is a pending invite */
03201       p->pendinginvite = seqno;
03202    }
03203 
03204    /* If the transport is something reliable (TCP or TLS) then don't really send this reliably */
03205    /* I removed the code from retrans_pkt that does the same thing so it doesn't get loaded into the scheduler */
03206    /* According to the RFC some packets need to be retransmitted even if its TCP, so this needs to get revisited */
03207    if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
03208       xmitres = __sip_xmit(p, data, len); /* Send packet */
03209       if (xmitres == XMIT_ERROR) {  /* Serious network trouble, no need to try again */
03210          append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
03211          return AST_FAILURE;
03212       } else
03213          return AST_SUCCESS;
03214    }
03215 
03216    if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
03217       return AST_FAILURE;
03218    /* copy data, add a terminator and save length */
03219    if (!(pkt->data = ast_str_create(len))) {
03220       ast_free(pkt);
03221       return AST_FAILURE;
03222    }
03223    ast_str_set(&pkt->data, 0, "%s%s", data->str, "\0");
03224    pkt->packetlen = len;
03225    /* copy other parameters from the caller */
03226    pkt->method = sipmethod;
03227    pkt->seqno = seqno;
03228    pkt->is_resp = resp;
03229    pkt->is_fatal = fatal;
03230    pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
03231    pkt->next = p->packets;
03232    p->packets = pkt; /* Add it to the queue */
03233    if (resp) {
03234       /* Parse out the response code */
03235       if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30d", &respid) == 1) {
03236          pkt->response_code = respid;
03237       }
03238    }
03239    pkt->timer_t1 = p->timer_t1;  /* Set SIP timer T1 */
03240    pkt->retransid = -1;
03241    if (pkt->timer_t1)
03242       siptimer_a = pkt->timer_t1 * 2;
03243 
03244    /* Schedule retransmission */
03245    AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
03246    if (sipdebug)
03247       ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id  #%d\n", pkt->retransid);
03248 
03249    xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);   /* Send packet */
03250 
03251    if (xmitres == XMIT_ERROR) {  /* Serious network trouble, no need to try again */
03252       append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03253       ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
03254       AST_SCHED_DEL(sched, pkt->retransid);
03255       p->packets = pkt->next;
03256       pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03257       ast_free(pkt->data);
03258       ast_free(pkt);
03259       return AST_FAILURE;
03260    } else {
03261       return AST_SUCCESS;
03262    }
03263 }
03264 
03265 /*! \brief Kill a SIP dialog (called only by the scheduler)
03266  * The scheduler has a reference to this dialog when p->autokillid != -1,
03267  * and we are called using that reference. So if the event is not
03268  * rescheduled, we need to call dialog_unref().
03269  */
03270 static int __sip_autodestruct(const void *data)
03271 {
03272    struct sip_pvt *p = (struct sip_pvt *)data;
03273 
03274    /* If this is a subscription, tell the phone that we got a timeout */
03275    if (p->subscribed) {
03276       transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);  /* Send last notification */
03277       p->subscribed = NONE;
03278       append_history(p, "Subscribestatus", "timeout");
03279       ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
03280       return 10000;  /* Reschedule this destruction so that we know that it's gone */
03281    }
03282 
03283    /* If there are packets still waiting for delivery, delay the destruction */
03284    if (p->packets) {
03285       if (!p->needdestroy) {
03286          char method_str[31];
03287          ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
03288          append_history(p, "ReliableXmit", "timeout");
03289          if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
03290             if (method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
03291                p->needdestroy = 1;
03292             }
03293          }
03294          return 10000;
03295       } else {
03296          /* They've had their chance to respond. Time to bail */
03297          __sip_pretend_ack(p);
03298       }
03299    }
03300 
03301    if (p->subscribed == MWI_NOTIFICATION)
03302       if (p->relatedpeer)
03303          p->relatedpeer = unref_peer(p->relatedpeer, "__sip_autodestruct: unref peer p->relatedpeer");   /* Remove link to peer. If it's realtime, make sure it's gone from memory) */
03304 
03305    /* Reset schedule ID */
03306    p->autokillid = -1;
03307 
03308    if (p->owner) {
03309       ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
03310       ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
03311    } else if (p->refer && !p->alreadygone) {
03312       ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
03313       transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
03314       append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
03315       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
03316    } else {
03317       append_history(p, "AutoDestroy", "%s", p->callid);
03318       ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
03319       dialog_unlink_all(p, TRUE, TRUE); /* once it's unlinked and unrefd everywhere, it'll be freed automagically */
03320       /* dialog_unref(p, "unref dialog-- no other matching conditions"); -- unlink all now should finish off the dialog's references and free it. */
03321       /* sip_destroy(p); */      /* Go ahead and destroy dialog. All attempts to recover is done */
03322       /* sip_destroy also absorbs the reference */
03323    }
03324    dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
03325    return 0;
03326 }
03327 
03328 /*! \brief Schedule destruction of SIP dialog */
03329 static void sip_scheddestroy(struct sip_pvt *p, int ms)
03330 {
03331    if (ms < 0) {
03332       if (p->timer_t1 == 0) {
03333          p->timer_t1 = global_t1;   /* Set timer T1 if not set (RFC 3261) */
03334          p->timer_b = global_timer_b;  /* Set timer B if not set (RFC 3261) */
03335       }
03336       ms = p->timer_t1 * 64;
03337    }
03338    if (sip_debug_test_pvt(p))
03339       ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
03340    if (sip_cancel_destroy(p))
03341       ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
03342 
03343    if (p->do_history)
03344       append_history(p, "SchedDestroy", "%d ms", ms);
03345    p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
03346 
03347    if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0)
03348       stop_session_timer(p);
03349 }
03350 
03351 /*! \brief Cancel destruction of SIP dialog.
03352  * Be careful as this also absorbs the reference - if you call it
03353  * from within the scheduler, this might be the last reference.
03354  */
03355 static int sip_cancel_destroy(struct sip_pvt *p)
03356 {
03357    int res = 0;
03358    if (p->autokillid > -1) {
03359       int res3;
03360 
03361       if (!(res3 = ast_sched_del(sched, p->autokillid))) {
03362          append_history(p, "CancelDestroy", "");
03363          p->autokillid = -1;
03364          dialog_unref(p, "dialog unrefd because autokillid is de-sched'd");
03365       }
03366    }
03367    return res;
03368 }
03369 
03370 /*! \brief Acknowledges receipt of a packet and stops retransmission 
03371  * called with p locked*/
03372 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
03373 {
03374    struct sip_pkt *cur, *prev = NULL;
03375    const char *msg = "Not Found";   /* used only for debugging */
03376    int res = FALSE;
03377 
03378    /* If we have an outbound proxy for this dialog, then delete it now since
03379      the rest of the requests in this dialog needs to follow the routing.
03380      If obforcing is set, we will keep the outbound proxy during the whole
03381      dialog, regardless of what the SIP rfc says
03382    */
03383    if (p->outboundproxy && !p->outboundproxy->force){
03384       ref_proxy(p, NULL);
03385    }
03386 
03387    for (cur = p->packets; cur; prev = cur, cur = cur->next) {
03388       if (cur->seqno != seqno || cur->is_resp != resp)
03389          continue;
03390       if (cur->is_resp || cur->method == sipmethod) {
03391          res = TRUE;
03392          msg = "Found";
03393          if (!resp && (seqno == p->pendinginvite)) {
03394             ast_debug(1, "Acked pending invite %d\n", p->pendinginvite);
03395             p->pendinginvite = 0;
03396          }
03397          if (cur->retransid > -1) {
03398             if (sipdebug)
03399                ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
03400          }
03401          /* This odd section is designed to thwart a 
03402           * race condition in the packet scheduler. There are
03403           * two conditions under which deleting the packet from the
03404           * scheduler can fail.
03405           *
03406           * 1. The packet has been removed from the scheduler because retransmission
03407           * is being attempted. The problem is that if the packet is currently attempting
03408           * retransmission and we are at this point in the code, then that MUST mean
03409           * that retrans_pkt is waiting on p's lock. Therefore we will relinquish the
03410           * lock temporarily to allow retransmission.
03411           *
03412           * 2. The packet has reached its maximum number of retransmissions and has
03413           * been permanently removed from the packet scheduler. If this is the case, then
03414           * the packet's retransid will be set to -1. The atomicity of the setting and checking
03415           * of the retransid to -1 is ensured since in both cases p's lock is held.
03416           */
03417          while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
03418             sip_pvt_unlock(p);
03419             usleep(1);
03420             sip_pvt_lock(p);
03421          }
03422          UNLINK(cur, p->packets, prev);
03423          dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
03424          if (cur->data)
03425             ast_free(cur->data);
03426          ast_free(cur);
03427          break;
03428       }
03429    }
03430    ast_debug(1, "Stopping retransmission on '%s' of %s %d: Match %s\n",
03431       p->callid, resp ? "Response" : "Request", seqno, msg);
03432    return res;
03433 }
03434 
03435 /*! \brief Pretend to ack all packets
03436  * called with p locked */
03437 static void __sip_pretend_ack(struct sip_pvt *p)
03438 {
03439    struct sip_pkt *cur = NULL;
03440 
03441    while (p->packets) {
03442       int method;
03443       if (cur == p->packets) {
03444          ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
03445          return;
03446       }
03447       cur = p->packets;
03448       method = (cur->method) ? cur->method : find_sip_method(cur->data->str);
03449       __sip_ack(p, cur->seqno, cur->is_resp, method);
03450    }
03451 }
03452 
03453 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
03454 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
03455 {
03456    struct sip_pkt *cur;
03457    int res = FALSE;
03458 
03459    for (cur = p->packets; cur; cur = cur->next) {
03460       if (cur->seqno == seqno && cur->is_resp == resp &&
03461          (cur->is_resp || method_match(sipmethod, cur->data->str))) {
03462          /* this is our baby */
03463          if (cur->retransid > -1) {
03464             if (sipdebug)
03465                ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
03466          }
03467          AST_SCHED_DEL(sched, cur->retransid);
03468          res = TRUE;
03469          break;
03470       }
03471    }
03472    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");
03473    return res;
03474 }
03475 
03476 
03477 /*! \brief Copy SIP request, parse it */
03478 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
03479 {
03480    copy_request(dst, src);
03481    parse_request(dst);
03482 }
03483 
03484 /*! \brief add a blank line if no body */
03485 static void add_blank(struct sip_request *req)
03486 {
03487    if (!req->lines) {
03488       /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
03489       ast_str_append(&req->data, 0, "\r\n");
03490       req->len = req->data->used;
03491    }
03492 }
03493 
03494 /*! \brief Transmit response on SIP request*/
03495 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
03496 {
03497    int res;
03498 
03499    add_blank(req);
03500    if (sip_debug_test_pvt(p)) {
03501       const struct sockaddr_in *dst = sip_real_dst(p);
03502 
03503       ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
03504          reliable ? "Reliably " : "", sip_nat_mode(p),
03505          ast_inet_ntoa(dst->sin_addr),
03506          ntohs(dst->sin_port), req->data->str);
03507    }
03508    if (p->do_history) {
03509       struct sip_request tmp = { .rlPart1 = 0, };
03510       parse_copy(&tmp, req);
03511       append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), 
03512          (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlPart2) : sip_methods[tmp.method].text);
03513       ast_free(tmp.data);
03514    }
03515    res = (reliable) ?
03516        __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
03517       __sip_xmit(p, req->data, req->len);
03518    ast_free(req->data);
03519    req->data = NULL;
03520    if (res > 0)
03521       return 0;
03522    return res;
03523 }
03524 
03525 /*! \brief Send SIP Request to the other part of the dialogue */
03526 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
03527 {
03528    int res;
03529 
03530    /* If we have an outbound proxy, reset peer address 
03531       Only do this once.
03532    */
03533    if (p->outboundproxy) {
03534       p->sa = p->outboundproxy->ip;
03535    }
03536 
03537    add_blank(req);
03538    if (sip_debug_test_pvt(p)) {
03539       if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
03540          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);
03541       else
03542          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);
03543    }
03544    if (p->do_history) {
03545       struct sip_request tmp = { .rlPart1 = 0, };
03546       parse_copy(&tmp, req);
03547       append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
03548       ast_free(tmp.data);
03549    }
03550    res = (reliable) ?
03551       __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
03552       __sip_xmit(p, req->data, req->len);
03553    if (req->data) {
03554       ast_free(req->data);
03555       req->data = NULL;
03556    }
03557    return res;
03558 }
03559 
03560 /*! \brief Query an option on a SIP dialog */
03561 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
03562 {
03563    int res = -1;
03564    enum ast_t38_state state = T38_STATE_UNAVAILABLE;
03565    struct sip_pvt *p = (struct sip_pvt *) chan->tech_pvt;
03566 
03567    switch (option) {
03568    case AST_OPTION_T38_STATE:
03569       /* Make sure we got an ast_t38_state enum passed in */
03570       if (*datalen != sizeof(enum ast_t38_state)) {
03571          ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
03572          return -1;
03573       }
03574 
03575       sip_pvt_lock(p);
03576 
03577       /* 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 */
03578       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
03579          switch (p->t38.state) {
03580          case T38_LOCAL_REINVITE:
03581          case T38_PEER_REINVITE:
03582             state = T38_STATE_NEGOTIATING;
03583             break;
03584          case T38_ENABLED:
03585             state = T38_STATE_NEGOTIATED;
03586             break;
03587          default:
03588             state = T38_STATE_UNKNOWN;
03589          }
03590       }
03591 
03592       sip_pvt_unlock(p);
03593 
03594       *((enum ast_t38_state *) data) = state;
03595       res = 0;
03596 
03597       break;
03598    default:
03599       break;
03600    }
03601 
03602    return res;
03603 }
03604 
03605 /*! \brief Locate closing quote in a string, skipping escaped quotes.
03606  * optionally with a limit on the search.
03607  * start must be past the first quote.
03608  */
03609 static const char *find_closing_quote(const char *start, const char *lim)
03610 {
03611    char last_char = '\0';
03612    const char *s;
03613    for (s = start; *s && s != lim; last_char = *s++) {
03614       if (*s == '"' && last_char != '\\')
03615          break;
03616    }
03617    return s;
03618 }
03619 
03620 /*! \brief Pick out text in brackets from character string
03621    \return pointer to terminated stripped string
03622    \param tmp input string that will be modified
03623    Examples:
03624 \verbatim
03625    "foo" <bar> valid input, returns bar
03626    foo      returns the whole string
03627    < "foo ... >   returns the string between brackets
03628    < "foo...   bogus (missing closing bracket), returns the whole string
03629          XXX maybe should still skip the opening bracket
03630 \endverbatim
03631  */
03632 static char *get_in_brackets(char *tmp)
03633 {
03634    const char *parse = tmp;
03635    char *first_bracket;
03636 
03637    /*
03638     * Skip any quoted text until we find the part in brackets.
03639    * On any error give up and return the full string.
03640    */
03641    while ( (first_bracket = strchr(parse, '<')) ) {
03642       char *first_quote = strchr(parse, '"');
03643 
03644       if (!first_quote || first_quote > first_bracket)
03645          break; /* no need to look at quoted part */
03646       /* the bracket is within quotes, so ignore it */
03647       parse = find_closing_quote(first_quote + 1, NULL);
03648       if (!*parse) { /* not found, return full string ? */
03649          /* XXX or be robust and return in-bracket part ? */
03650          ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
03651          break;
03652       }
03653       parse++;
03654    }
03655    if (first_bracket) {
03656       char *second_bracket = strchr(first_bracket + 1, '>');
03657       if (second_bracket) {
03658          *second_bracket = '\0';
03659          tmp = first_bracket + 1;
03660       } else {
03661          ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
03662       }
03663    }
03664    
03665    return tmp;
03666 }
03667 
03668 /*! \brief * parses a URI in its components.
03669  *
03670  * \note 
03671  * - If scheme is specified, drop it from the top.
03672  * - If a component is not requested, do not split around it.
03673  *
03674  * This means that if we don't have domain, we cannot split
03675  * name:pass and domain:port.
03676  * It is safe to call with ret_name, pass, domain, port
03677  * pointing all to the same place.
03678  * Init pointers to empty string so we never get NULL dereferencing.
03679  * Overwrites the string.
03680  * return 0 on success, other values on error.
03681  * \verbatim 
03682  * general form we are expecting is sip[s]:username[:password][;parameter]@host[:port][;...] 
03683  * \endverbatim
03684  */
03685 static int parse_uri(char *uri, char *scheme,
03686    char **ret_name, char **pass, char **domain, char **port, char **options, char **transport)
03687 {
03688    char *name = NULL;
03689    int error = 0;
03690 
03691    /* init field as required */
03692    if (pass)
03693       *pass = "";
03694    if (port)
03695       *port = "";
03696    if (scheme) {
03697       int l = strlen(scheme);
03698       if (!strncasecmp(uri, scheme, l))
03699          uri += l;
03700       else {
03701          ast_debug(1, "Missing scheme '%s' in '%s'\n", scheme, uri);
03702          error = -1;
03703       }
03704    }
03705    if (transport) {
03706       char *t, *type = "";
03707       *transport = "";
03708       if ((t = strstr(uri, "transport="))) {
03709          strsep(&t, "=");
03710          if ((type = strsep(&t, ";"))) {
03711             *transport = type;
03712          }
03713       }
03714    }
03715 
03716    if (!domain) {
03717       /* if we don't want to split around domain, keep everything as a name,
03718        * so we need to do nothing here, except remember why.
03719        */
03720    } else {
03721       /* store the result in a temp. variable to avoid it being
03722        * overwritten if arguments point to the same place.
03723        */
03724       char *c, *dom = "";
03725 
03726       if ((c = strchr(uri, '@')) == NULL) {
03727          /* domain-only URI, according to the SIP RFC. */
03728          dom = uri;
03729          name = "";
03730       } else {
03731          *c++ = '\0';
03732          dom = c;
03733          name = uri;
03734       }
03735 
03736       /* Remove options in domain and name */
03737       dom = strsep(&dom, ";");
03738       name = strsep(&name, ";");
03739 
03740       if (port && (c = strchr(dom, ':'))) { /* Remove :port */
03741          *c++ = '\0';
03742          *port = c;
03743       }
03744       if (pass && (c = strchr(name, ':'))) { /* user:password */
03745          *c++ = '\0';
03746          *pass = c;
03747       }
03748       *domain = dom;
03749    }
03750    if (ret_name)  /* same as for domain, store the result only at the end */
03751       *ret_name = name;
03752    if (options)
03753       *options = uri ? uri : "";
03754 
03755    return error;
03756 }
03757 
03758 /*! \brief Send message with Access-URL header, if this is an HTML URL only! */
03759 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
03760 {
03761    struct sip_pvt *p = chan->tech_pvt;
03762 
03763    if (subclass != AST_HTML_URL)
03764       return -1;
03765 
03766    ast_string_field_build(p, url, "<%s>;mode=active", data);
03767 
03768    if (sip_debug_test_pvt(p))
03769       ast_debug(1, "Send URL %s, state = %d!\n", data, chan->_state);
03770 
03771    switch (chan->_state) {
03772    case AST_STATE_RING:
03773       transmit_response(p, "100 Trying", &p->initreq);
03774       break;
03775    case AST_STATE_RINGING:
03776       transmit_response(p, "180 Ringing", &p->initreq);
03777       break;
03778    case AST_STATE_UP:
03779       if (!p->pendinginvite) {      /* We are up, and have no outstanding invite */
03780          transmit_reinvite_with_sdp(p, FALSE, FALSE);
03781       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
03782          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);   
03783       }  
03784       break;
03785    default:
03786       ast_log(LOG_WARNING, "Don't know how to send URI when state is %d!\n", chan->_state);
03787    }
03788 
03789    return 0;
03790 }
03791 
03792 /*! \brief Deliver SIP call ID for the call */
03793 static const char *sip_get_callid(struct ast_channel *chan)
03794 {
03795    return chan->tech_pvt ? ((struct sip_pvt *) chan->tech_pvt)->callid : "";
03796 }
03797 
03798 /*! \brief Send SIP MESSAGE text within a call
03799    Called from PBX core sendtext() application */
03800 static int sip_sendtext(struct ast_channel *ast, const char *text)
03801 {
03802    struct sip_pvt *p = ast->tech_pvt;
03803    int debug = sip_debug_test_pvt(p);
03804 
03805    if (debug)
03806       ast_verbose("Sending text %s on %s\n", text, ast->name);
03807    if (!p)
03808       return -1;
03809    /* NOT ast_strlen_zero, because a zero-length message is specifically
03810     * allowed by RFC 3428 (See section 10, Examples) */
03811    if (!text)
03812       return 0;
03813    if (debug)
03814       ast_verbose("Really sending text %s on %s\n", text, ast->name);
03815    transmit_message_with_text(p, text);
03816    return 0;   
03817 }
03818 
03819 /*! \brief Update peer object in realtime storage 
03820    If the Asterisk system name is set in asterisk.conf, we will use
03821    that name and store that in the "regserver" field in the sippeers
03822    table to facilitate multi-server setups.
03823 */
03824 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)
03825 {
03826    char port[10];
03827    char ipaddr[INET_ADDRSTRLEN];
03828    char regseconds[20];
03829    char *tablename = NULL;
03830    char str_lastms[20];
03831 
03832    const char *sysname = ast_config_AST_SYSTEM_NAME;
03833    char *syslabel = NULL;
03834 
03835    time_t nowtime = time(NULL) + expirey;
03836    const char *fc = fullcontact ? "fullcontact" : NULL;
03837 
03838    int realtimeregs = ast_check_realtime("sipregs");
03839 
03840    tablename = realtimeregs ? "sipregs" : "sippeers";
03841    
03842 
03843    snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
03844    snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);  /* Expiration time */
03845    ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
03846    snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
03847    
03848    if (ast_strlen_zero(sysname)) /* No system name, disable this */
03849       sysname = NULL;
03850    else if (sip_cfg.rtsave_sysname)
03851       syslabel = "regserver";
03852 
03853    if (fc) {
03854       ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
03855          "port", port, "regseconds", regseconds,
03856          deprecated_username ? "username" : "defaultuser", defaultuser,
03857          "useragent", useragent, "lastms", str_lastms,
03858          fc, fullcontact, syslabel, sysname, SENTINEL); /* note fc and syslabel _can_ be NULL */
03859    } else {
03860       ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
03861          "port", port, "regseconds", regseconds,
03862          "useragent", useragent, "lastms", str_lastms,
03863          deprecated_username ? "username" : "defaultuser", defaultuser,
03864          syslabel, sysname, SENTINEL); /* note syslabel _can_ be NULL */
03865    }
03866 }
03867 
03868 /*! \brief Automatically add peer extension to dial plan */
03869 static void register_peer_exten(struct sip_peer *peer, int onoff)
03870 {
03871    char multi[256];
03872    char *stringp, *ext, *context;
03873    struct pbx_find_info q = { .stacklen = 0 };
03874 
03875    /* XXX note that global_regcontext is both a global 'enable' flag and
03876     * the name of the global regexten context, if not specified
03877     * individually.
03878     */
03879    if (ast_strlen_zero(global_regcontext))
03880       return;
03881 
03882    ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
03883    stringp = multi;
03884    while ((ext = strsep(&stringp, "&"))) {
03885       if ((context = strchr(ext, '@'))) {
03886          *context++ = '\0';   /* split ext@context */
03887          if (!ast_context_find(context)) {
03888             ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
03889             continue;
03890          }
03891       } else {
03892          context = global_regcontext;
03893       }
03894       if (onoff) {
03895          if (!ast_exists_extension(NULL, context, ext, 1, NULL)) {
03896             ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
03897                 ast_strdup(peer->name), ast_free_ptr, "SIP");
03898          }
03899       } else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
03900          ast_context_remove_extension(context, ext, 1, NULL);
03901       }
03902    }
03903 }
03904 
03905 /*! Destroy mailbox subscriptions */
03906 static void destroy_mailbox(struct sip_mailbox *mailbox)
03907 {
03908    if (mailbox->mailbox)
03909       ast_free(mailbox->mailbox);
03910    if (mailbox->context)
03911       ast_free(mailbox->context);
03912    if (mailbox->event_sub)
03913       ast_event_unsubscribe(mailbox->event_sub);
03914    ast_free(mailbox);
03915 }
03916 
03917 /*! Destroy all peer-related mailbox subscriptions */
03918 static void clear_peer_mailboxes(struct sip_peer *peer)
03919 {
03920    struct sip_mailbox *mailbox;
03921 
03922    while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
03923       destroy_mailbox(mailbox);
03924 }
03925 
03926 static void sip_destroy_peer_fn(void *peer)
03927 {
03928    sip_destroy_peer(peer);
03929 }
03930 
03931 /*! \brief Destroy peer object from memory */
03932 static void sip_destroy_peer(struct sip_peer *peer)
03933 {
03934    ast_debug(3, "Destroying SIP peer %s\n", peer->name);
03935    if (peer->outboundproxy)
03936       ao2_ref(peer->outboundproxy, -1);
03937    peer->outboundproxy = NULL;
03938 
03939    /* Delete it, it needs to disappear */
03940    if (peer->call) {
03941       dialog_unlink_all(peer->call, TRUE, TRUE);
03942       peer->call = dialog_unref(peer->call, "peer->call is being unset");
03943    }
03944    
03945 
03946    if (peer->mwipvt) {  /* We have an active subscription, delete it */
03947       dialog_unlink_all(peer->mwipvt, TRUE, TRUE);
03948       peer->mwipvt = dialog_unref(peer->mwipvt, "unreffing peer->mwipvt");
03949    }
03950    
03951    if (peer->chanvars) {
03952       ast_variables_destroy(peer->chanvars);
03953       peer->chanvars = NULL;
03954    }
03955    
03956    register_peer_exten(peer, FALSE);
03957    ast_free_ha(peer->ha);
03958    if (peer->selfdestruct)
03959       ast_atomic_fetchadd_int(&apeerobjs, -1);
03960    else if (peer->is_realtime) {
03961       ast_atomic_fetchadd_int(&rpeerobjs, -1);
03962       ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
03963    } else
03964       ast_atomic_fetchadd_int(&speerobjs, -1);
03965    clear_realm_authentication(peer->auth);
03966    peer->auth = NULL;
03967    if (peer->dnsmgr)
03968       ast_dnsmgr_release(peer->dnsmgr);
03969    clear_peer_mailboxes(peer);
03970 
03971    if (peer->socket.tcptls_session) {
03972       ao2_ref(peer->socket.tcptls_session, -1);
03973       peer->socket.tcptls_session = NULL;
03974    }
03975 }
03976 
03977 /*! \brief Update peer data in database (if used) */
03978 static void update_peer(struct sip_peer *p, int expire)
03979 {
03980    int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
03981    if (sip_cfg.peer_rtupdate &&
03982        (p->is_realtime || rtcachefriends)) {
03983       realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, p->useragent, expire, p->deprecated_username, p->lastms);
03984    }
03985 }
03986 
03987 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *cfg)
03988 {
03989    struct ast_variable *var = NULL;
03990    struct ast_flags flags = {0};
03991    char *cat = NULL;
03992    const char *insecure;
03993    while ((cat = ast_category_browse(cfg, cat))) {
03994       insecure = ast_variable_retrieve(cfg, cat, "insecure");
03995       set_insecure_flags(&flags, insecure, -1);
03996       if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
03997          var = ast_category_root(cfg, cat);
03998          break;
03999       }
04000    }
04001    return var;
04002 }
04003 
04004 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername)
04005 {
04006    struct ast_variable *tmp;
04007    for (tmp = var; tmp; tmp = tmp->next) {
04008       if (!newpeername && !strcasecmp(tmp->name, "name"))
04009          newpeername = tmp->value;
04010    }
04011    return newpeername;
04012 }
04013 
04014 /*! \brief  realtime_peer: Get peer from realtime storage
04015  * Checks the "sippeers" realtime family from extconfig.conf 
04016  * Checks the "sipregs" realtime family from extconfig.conf if it's configured.
04017  * This returns a pointer to a peer and because we use build_peer, we can rest
04018  * assured that the refcount is bumped.
04019 */
04020 static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin, int devstate_only)
04021 {
04022    struct sip_peer *peer;
04023    struct ast_variable *var = NULL;
04024    struct ast_variable *varregs = NULL;
04025    struct ast_variable *tmp;
04026    struct ast_config *peerlist = NULL;
04027    char ipaddr[INET_ADDRSTRLEN];
04028    char portstring[6]; /*up to 5 digits plus null terminator*/
04029    char *cat = NULL;
04030    unsigned short portnum;
04031    int realtimeregs = ast_check_realtime("sipregs");
04032 
04033    /* First check on peer name */
04034    if (newpeername) {
04035       if (realtimeregs)
04036          varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04037 
04038       var = ast_load_realtime("sippeers", "name", newpeername, "host", "dynamic", SENTINEL);
04039       if (!var && sin)
04040          var = ast_load_realtime("sippeers", "name", newpeername, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
04041       if (!var) {
04042          var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04043          /*!\note
04044           * If this one loaded something, then we need to ensure that the host
04045           * field matched.  The only reason why we can't have this as a criteria
04046           * is because we only have the IP address and the host field might be
04047           * set as a name (and the reverse PTR might not match).
04048           */
04049          if (var && sin) {
04050             for (tmp = var; tmp; tmp = tmp->next) {
04051                if (!strcasecmp(tmp->name, "host")) {
04052                   struct hostent *hp;
04053                   struct ast_hostent ahp;
04054                   if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(&hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
04055                      /* No match */
04056                      ast_variables_destroy(var);
04057                      var = NULL;
04058                   }
04059                   break;
04060                }
04061             }
04062          }
04063       }
04064    }
04065 
04066    if (!var && sin) {   /* Then check on IP address for dynamic peers */
04067       ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
04068       portnum = ntohs(sin->sin_port);
04069       sprintf(portstring, "%u", portnum);
04070       var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, SENTINEL);  /* First check for fixed IP hosts */
04071       if (var) {
04072          if (realtimeregs) {
04073             newpeername = get_name_from_variable(var, newpeername);
04074             varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04075          }
04076       } else {
04077          if (realtimeregs)
04078             varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, "port", portstring, SENTINEL); /* Then check for registered hosts */
04079          else
04080             var = ast_load_realtime("sippeers", "ipaddr", ipaddr, "port", portstring, SENTINEL); /* Then check for registered hosts */
04081          if (varregs) {
04082             newpeername = get_name_from_variable(varregs, newpeername);
04083             var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04084          }
04085       }
04086       if (!var) { /*We couldn't match on ipaddress and port, so we need to check if port is insecure*/
04087          peerlist = ast_load_realtime_multientry("sippeers", "host", ipaddr, SENTINEL);
04088          if (peerlist) {
04089             var = get_insecure_variable_from_config(peerlist);
04090             if(var) {
04091                if (realtimeregs) {
04092                   newpeername = get_name_from_variable(var, newpeername);
04093                   varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04094                }
04095             } else { /*var wasn't found in the list of "hosts", so try "ipaddr"*/
04096                peerlist = NULL;
04097                cat = NULL;
04098                peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, SENTINEL);
04099                if(peerlist) {
04100                   var = get_insecure_variable_from_config(peerlist);
04101                   if(var) {
04102                      if (realtimeregs) {
04103                         newpeername = get_name_from_variable(var, newpeername);
04104                         varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04105                      }
04106                   }
04107                }
04108             }
04109          } else {
04110             if (realtimeregs) {
04111                peerlist = ast_load_realtime_multientry("sipregs", "ipaddr", ipaddr, SENTINEL);
04112                if (peerlist) {
04113                   varregs = get_insecure_variable_from_config(peerlist);
04114                   if (varregs) {
04115                      newpeername = get_name_from_variable(varregs, newpeername);
04116                      var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04117                   }
04118                }
04119             } else {
04120                peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, SENTINEL);
04121                if (peerlist) {
04122                   var = get_insecure_variable_from_config(peerlist);
04123                   if (var) {
04124                      newpeername = get_name_from_variable(var, newpeername);
04125                      varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04126                   }
04127                }
04128             }
04129          }
04130       }
04131    }
04132 
04133    if (!var) {
04134       if (peerlist)
04135          ast_config_destroy(peerlist);
04136       return NULL;
04137    }
04138 
04139    for (tmp = var; tmp; tmp = tmp->next) {
04140       /* If this is type=user, then skip this object. */
04141       if (!strcasecmp(tmp->name, "type") &&
04142           !strcasecmp(tmp->value, "user")) {
04143          if(peerlist)
04144             ast_config_destroy(peerlist);
04145          else {
04146             ast_variables_destroy(var);
04147             ast_variables_destroy(varregs);
04148          }
04149          return NULL;
04150       } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
04151          newpeername = tmp->value;
04152       }
04153    }
04154    
04155    if (!newpeername) {  /* Did not find peer in realtime */
04156       ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", ipaddr);
04157       if(peerlist)
04158          ast_config_destroy(peerlist);
04159       else
04160          ast_variables_destroy(var);
04161       return NULL;
04162    }
04163 
04164 
04165    /* Peer found in realtime, now build it in memory */
04166    peer = build_peer(newpeername, var, varregs, TRUE);
04167    if (!peer) {
04168       if(peerlist)
04169          ast_config_destroy(peerlist);
04170       else {
04171          ast_variables_destroy(var);
04172          ast_variables_destroy(varregs);
04173       }
04174       return NULL;
04175    }
04176 
04177    ast_debug(3, "-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
04178 
04179    if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && !devstate_only) {
04180       /* Cache peer */
04181       ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
04182       if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
04183          AST_SCHED_REPLACE_UNREF(peer->expire, sched, global_rtautoclear * 1000, expire_register, peer,
04184                unref_peer(_data, "remove registration ref"),
04185                unref_peer(peer, "remove registration ref"),
04186                ref_peer(peer, "add registration ref"));
04187       }
04188       ao2_t_link(peers, peer, "link peer into peers table");
04189       if (peer->addr.sin_addr.s_addr) {
04190          ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
04191       }
04192    }
04193    peer->is_realtime = 1;
04194    if (peerlist)
04195       ast_config_destroy(peerlist);
04196    else {
04197       ast_variables_destroy(var);
04198       ast_variables_destroy(varregs);
04199    }
04200 
04201    return peer;
04202 }
04203 
04204 /* The first element here must *always* be tmp_peer. This is because the user of this function
04205  * passes it in using OBJ_POINTER which causes astobj2 to perform hashing on the name to find
04206  * where the peer is. Since tmp_peer is at the beginning this just magically works. Move it and it
04207  * will break. People will be angry. Just don't do it.
04208  */
04209 struct peer_finding_info {
04210    struct sip_peer tmp_peer;
04211    int which_objects;
04212 };
04213 
04214 /* Function to assist finding peers by name only */
04215 static int find_by_name(void *obj, void *arg, int flags)
04216 {
04217    struct sip_peer *search = obj;
04218    struct peer_finding_info *pfi = arg;
04219 
04220    /* Usernames in SIP uri's are case sensitive. Domains are not */
04221    if (strcmp(search->name, pfi->tmp_peer.name)) {
04222       return 0;
04223    }
04224 
04225    switch (pfi->which_objects) {
04226    case FINDUSERS:
04227       if (!(search->type & SIP_TYPE_USER)) {
04228          return 0;
04229       }
04230       break;
04231    case FINDPEERS:
04232       if (!(search->type & SIP_TYPE_PEER)) {
04233          return 0;
04234       }
04235       break;
04236    case FINDALLDEVICES:
04237       break;
04238    }
04239 
04240    return CMP_MATCH | CMP_STOP;
04241 }
04242 
04243 /*! 
04244  * \brief Locate device by name or ip address 
04245  *
04246  * \param which_objects Define which objects should be matched when doing a lookup
04247  *        by name.  Valid options are FINDUSERS, FINDPEERS, or FINDALLDEVICES.
04248  *        Note that this option is not used at all when doing a lookup by IP.
04249  *
04250  * This is used on find matching device on name or ip/port.
04251  * If the device was declared as type=peer, we don't match on peer name on incoming INVITEs.
04252  *
04253  * \note Avoid using this function in new functions if there is a way to avoid it,
04254  * since it might cause a database lookup.
04255  */
04256 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int which_objects, int devstate_only)
04257 {
04258    struct sip_peer *p = NULL;
04259 
04260    if (peer) {
04261       struct peer_finding_info pfi = {
04262          .which_objects = which_objects,
04263       };
04264       ast_copy_string(pfi.tmp_peer.name, peer, sizeof(pfi.tmp_peer.name));
04265       p = ao2_t_callback(peers, OBJ_POINTER, find_by_name, &pfi, "ao2_callback in peers table");
04266    } else if (sin) { /* search by addr? */
04267       struct sip_peer tmp_peer;
04268       tmp_peer.addr.sin_addr.s_addr = sin->sin_addr.s_addr;
04269       tmp_peer.addr.sin_port = sin->sin_port;
04270       tmp_peer.flags[0].flags = 0;
04271       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); */
04272       if (!p) {
04273          ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
04274          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); */
04275          if (p) {
04276             return p;
04277          }
04278       }
04279    }
04280 
04281    if (!p && (realtime || devstate_only))
04282       p = realtime_peer(peer, sin, devstate_only);
04283 
04284    return p;
04285 }
04286 
04287 /*! \brief Set nat mode on the various data sockets */
04288 static void do_setnat(struct sip_pvt *p, int natflags)
04289 {
04290    const char *mode = natflags ? "On" : "Off";
04291 
04292    if (p->rtp) {
04293       ast_debug(1, "Setting NAT on RTP to %s\n", mode);
04294       ast_rtp_setnat(p->rtp, natflags);
04295    }
04296    if (p->vrtp) {
04297       ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
04298       ast_rtp_setnat(p->vrtp, natflags);
04299    }
04300    if (p->udptl) {
04301       ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
04302       ast_udptl_setnat(p->udptl, natflags);
04303    }
04304    if (p->trtp) {
04305       ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
04306       ast_rtp_setnat(p->trtp, natflags);
04307    }
04308 }
04309 
04310 /*! \brief Change the T38 state on a SIP dialog */
04311 static void change_t38_state(struct sip_pvt *p, int state)
04312 {
04313    int old = p->t38.state;
04314    struct ast_channel *chan = p->owner;
04315    struct ast_control_t38_parameters parameters = { .request_response = 0 };
04316 
04317    /* Don't bother changing if we are already in the state wanted */
04318    if (old == state)
04319       return;
04320 
04321    p->t38.state = state;
04322    ast_debug(2, "T38 state changed to %d on channel %s\n", p->t38.state, chan ? chan->name : "<none>");
04323 
04324    /* If no channel was provided we can't send off a control frame */
04325    if (!chan)
04326       return;
04327 
04328    /* Given the state requested and old state determine what control frame we want to queue up */
04329    if (state == T38_PEER_REINVITE) {
04330       parameters = p->t38.their_parms;
04331       parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
04332       parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
04333    } else if (state == T38_ENABLED) {
04334       parameters = p->t38.their_parms;
04335       parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
04336       parameters.request_response = AST_T38_NEGOTIATED;
04337    } else if (state == T38_DISABLED && old == T38_ENABLED)
04338       parameters.request_response = AST_T38_TERMINATED;
04339    else if (state == T38_DISABLED && old == T38_LOCAL_REINVITE)
04340       parameters.request_response = AST_T38_REFUSED;
04341 
04342    /* Woot we got a message, create a control frame and send it on! */
04343    if (parameters.request_response)
04344       ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
04345 }
04346 
04347 /*! \brief Set the global T38 capabilities on a SIP dialog structure */
04348 static void set_t38_capabilities(struct sip_pvt *p)
04349 {
04350    if (p->udptl) {
04351       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY) {
04352                         ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
04353       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_FEC) {
04354          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
04355       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL) {
04356          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
04357       }
04358    }
04359 }
04360 
04361 static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
04362 {
04363    if (to_sock->tcptls_session) {
04364       ao2_ref(to_sock->tcptls_session, -1);
04365       to_sock->tcptls_session = NULL;
04366    }
04367 
04368    if (from_sock->tcptls_session) {
04369       ao2_ref(from_sock->tcptls_session, +1);
04370    }
04371 
04372    *to_sock = *from_sock;
04373 }
04374 
04375 /*! \brief Create address structure from peer reference.
04376  * This function copies data from peer to the dialog, so we don't have to look up the peer
04377  * again from memory or database during the life time of the dialog.
04378  *
04379  * \return -1 on error, 0 on success.
04380  *
04381  */
04382 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
04383 {
04384    /* this checks that the dialog is contacting the peer on a valid
04385     * transport type based on the peers transport configuration,
04386     * otherwise, this function bails out */
04387    if (dialog->socket.type && check_request_transport(peer, dialog))
04388       return -1;
04389    copy_socket_data(&dialog->socket, &peer->socket);
04390 
04391    if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
04392        (!peer->maxms || ((peer->lastms >= 0)  && (peer->lastms <= peer->maxms)))) {
04393       dialog->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
04394       dialog->recv = dialog->sa;
04395    } else 
04396       return -1;
04397 
04398    ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
04399    ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
04400    dialog->capability = peer->capability;
04401    if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) &&
04402          (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
04403             !(dialog->capability & AST_FORMAT_VIDEO_MASK)) &&
04404          dialog->vrtp) {
04405       ast_rtp_destroy(dialog->vrtp);
04406       dialog->vrtp = NULL;
04407    }
04408    if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT) && dialog->trtp) {
04409       ast_rtp_destroy(dialog->trtp);
04410       dialog->trtp = NULL;
04411    }
04412    dialog->prefs = peer->prefs;
04413    if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
04414       if (!dialog->udptl) {
04415          /* t38pt_udptl was enabled in the peer and not in [general] */
04416          dialog->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr);
04417       }
04418       set_t38_capabilities(dialog);
04419    } else if (dialog->udptl) {
04420       ast_udptl_destroy(dialog->udptl);
04421       dialog->udptl = NULL;
04422    }
04423    do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
04424 
04425    if (dialog->rtp) { /* Audio */
04426       ast_rtp_setdtmf(dialog->rtp, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
04427       ast_rtp_setdtmfcompensate(dialog->rtp, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
04428       ast_rtp_set_rtptimeout(dialog->rtp, peer->rtptimeout);
04429       ast_rtp_set_rtpholdtimeout(dialog->rtp, peer->rtpholdtimeout);
04430       ast_rtp_set_rtpkeepalive(dialog->rtp, peer->rtpkeepalive);
04431       /* Set Frame packetization */
04432       ast_rtp_codec_setpref(dialog->rtp, &dialog->prefs);
04433       dialog->autoframing = peer->autoframing;
04434    }
04435    if (dialog->vrtp) { /* Video */
04436       ast_rtp_setdtmf(dialog->vrtp, 0);
04437       ast_rtp_setdtmfcompensate(dialog->vrtp, 0);
04438       ast_rtp_set_rtptimeout(dialog->vrtp, peer->rtptimeout);
04439       ast_rtp_set_rtpholdtimeout(dialog->vrtp, peer->rtpholdtimeout);
04440       ast_rtp_set_rtpkeepalive(dialog->vrtp, peer->rtpkeepalive);
04441    }
04442    if (dialog->trtp) { /* Realtime text */
04443       ast_rtp_setdtmf(dialog->trtp, 0);
04444       ast_rtp_setdtmfcompensate(dialog->trtp, 0);
04445       ast_rtp_set_rtptimeout(dialog->trtp, peer->rtptimeout);
04446       ast_rtp_set_rtpholdtimeout(dialog->trtp, peer->rtpholdtimeout);
04447       ast_rtp_set_rtpkeepalive(dialog->trtp, peer->rtpkeepalive);
04448    }
04449 
04450    ast_string_field_set(dialog, peername, peer->name);
04451    ast_string_field_set(dialog, authname, peer->username);
04452    ast_string_field_set(dialog, username, peer->username);
04453    ast_string_field_set(dialog, peersecret, peer->secret);
04454    ast_string_field_set(dialog, peermd5secret, peer->md5secret);
04455    ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
04456    ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
04457    ast_string_field_set(dialog, tohost, peer->tohost);
04458    ast_string_field_set(dialog, fullcontact, peer->fullcontact);
04459    ast_string_field_set(dialog, context, peer->context);
04460    ast_string_field_set(dialog, parkinglot, peer->parkinglot);
04461    ref_proxy(dialog, obproxy_get(dialog, peer));
04462    dialog->callgroup = peer->callgroup;
04463    dialog->pickupgroup = peer->pickupgroup;
04464    dialog->allowtransfer = peer->allowtransfer;
04465    dialog->jointnoncodeccapability = dialog->noncodeccapability;
04466    dialog->rtptimeout = peer->rtptimeout;
04467    dialog->peerauth = peer->auth;
04468    dialog->maxcallbitrate = peer->maxcallbitrate;
04469    if (ast_strlen_zero(dialog->tohost))
04470       ast_string_field_set(dialog, tohost, ast_inet_ntoa(dialog->sa.sin_addr));
04471    if (!ast_strlen_zero(peer->fromdomain)) {
04472       ast_string_field_set(dialog, fromdomain, peer->fromdomain);
04473       if (!dialog->initreq.headers) {
04474          char *c;
04475          char *tmpcall = ast_strdupa(dialog->callid);
04476          /* this sure looks to me like we are going to change the callid on this dialog!! */
04477          c = strchr(tmpcall, '@');
04478          if (c) {
04479             *c = '\0';
04480             ao2_t_unlink(dialogs, dialog, "About to change the callid -- remove the old name");
04481             ast_string_field_build(dialog, callid, "%s@%s", tmpcall, peer->fromdomain);
04482             ao2_t_link(dialogs, dialog, "New dialog callid -- inserted back into table");
04483          }
04484       }
04485    }
04486    if (!ast_strlen_zero(peer->fromuser)) 
04487       ast_string_field_set(dialog, fromuser, peer->fromuser);
04488    if (!ast_strlen_zero(peer->language))
04489       ast_string_field_set(dialog, language, peer->language);
04490    /* Set timer T1 to RTT for this peer (if known by qualify=) */
04491    /* Minimum is settable or default to 100 ms */
04492    /* If there is a maxms and lastms from a qualify use that over a manual T1
04493       value. Otherwise, use the peer's T1 value. */
04494    if (peer->maxms && peer->lastms)
04495       dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
04496    else
04497       dialog->timer_t1 = peer->timer_t1;
04498 
04499    /* Set timer B to control transaction timeouts, the peer setting is the default and overrides
04500       the known timer */
04501    if (peer->timer_b)
04502       dialog->timer_b = peer->timer_b;
04503    else
04504       dialog->timer_b = 64 * dialog->timer_t1;
04505 
04506    if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
04507        (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
04508       dialog->noncodeccapability |= AST_RTP_DTMF;
04509    else
04510       dialog->noncodeccapability &= ~AST_RTP_DTMF;
04511    if (peer->call_limit)
04512       ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
04513    
04514    return 0;
04515 }
04516 
04517 /*! \brief create address structure from device name
04518  *      Or, if peer not found, find it in the global DNS 
04519  *      returns TRUE (-1) on failure, FALSE on success */
04520 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog)
04521 {
04522    struct hostent *hp;
04523    struct ast_hostent ahp;
04524    struct sip_peer *peer;
04525    char *port;
04526    int portno = 0;
04527    char host[MAXHOSTNAMELEN], *hostn;
04528    char peername[256];
04529    int srv_ret = 0;
04530 
04531    ast_copy_string(peername, opeer, sizeof(peername));
04532    port = strchr(peername, ':');
04533    if (port)
04534       *port++ = '\0';
04535    dialog->sa.sin_family = AF_INET;
04536    dialog->timer_t1 = global_t1; /* Default SIP retransmission timer T1 (RFC 3261) */
04537    dialog->timer_b = global_timer_b; /* Default SIP transaction timer B (RFC 3261) */
04538    peer = find_peer(peername, NULL, TRUE, FINDPEERS, FALSE);
04539 
04540    if (peer) {
04541       int res;
04542       if (newdialog) {
04543          set_socket_transport(&dialog->socket, 0);
04544       }
04545       res = create_addr_from_peer(dialog, peer);
04546       if (!ast_strlen_zero(port)) {
04547          if ((portno = atoi(port))) {
04548             dialog->sa.sin_port = dialog->recv.sin_port = htons(portno);
04549          }
04550       }
04551       unref_peer(peer, "create_addr: unref peer from find_peer hashtab lookup");
04552       return res;
04553    }
04554 
04555    do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
04556 
04557    ast_string_field_set(dialog, tohost, peername);
04558 
04559    /* Get the outbound proxy information */
04560    ref_proxy(dialog, obproxy_get(dialog, NULL));
04561 
04562    if (sin) {
04563       /* This address should be updated using dnsmgr */
04564       memcpy(&dialog->sa.sin_addr, &sin->sin_addr, sizeof(dialog->sa.sin_addr));
04565       if (!sin->sin_port) {
04566          if (ast_strlen_zero(port) || sscanf(port, "%5u", &portno) != 1) {
04567             portno = (dialog->socket.type & SIP_TRANSPORT_TLS) ?
04568                STANDARD_TLS_PORT : STANDARD_SIP_PORT;
04569          }
04570       } else {
04571          portno = ntohs(sin->sin_port);
04572       }
04573    } else {
04574 
04575       /* Let's see if we can find the host in DNS. First try DNS SRV records,
04576          then hostname lookup */
04577       /*! \todo Fix this function. When we ask SRC, we should check all transports 
04578            In the future, we should first check NAPTR to find out transport preference
04579        */
04580       hostn = peername;
04581       /* Section 4.2 of RFC 3263 specifies that if a port number is specified, then
04582        * an A record lookup should be used instead of SRV.
04583        */
04584       if (!port && global_srvlookup) {
04585          char service[MAXHOSTNAMELEN];
04586          int tportno;
04587    
04588          snprintf(service, sizeof(service), "_sip._%s.%s", get_transport(dialog->socket.type), peername);
04589          srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
04590          if (srv_ret > 0) {
04591             hostn = host;
04592             portno = tportno;
04593          }
04594       }
04595       if (!portno)
04596          portno = port ? atoi(port) : (dialog->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT;
04597       hp = ast_gethostbyname(hostn, &ahp);
04598       if (!hp) {
04599          ast_log(LOG_WARNING, "No such host: %s\n", peername);
04600          return -1;
04601       }
04602       memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
04603    }
04604 
04605    if (!dialog->socket.type)
04606       set_socket_transport(&dialog->socket, SIP_TRANSPORT_UDP);
04607    if (!dialog->socket.port)
04608       dialog->socket.port = bindaddr.sin_port;
04609    dialog->sa.sin_port = htons(portno);
04610    dialog->recv = dialog->sa;
04611    return 0;
04612 }
04613 
04614 /*! \brief Scheduled congestion on a call.
04615  * Only called by the scheduler, must return the reference when done.
04616  */
04617 static int auto_congest(const void *arg)
04618 {
04619    struct sip_pvt *p = (struct sip_pvt *)arg;
04620 
04621    sip_pvt_lock(p);
04622    p->initid = -1;   /* event gone, will not be rescheduled */
04623    if (p->owner) {
04624       /* XXX fails on possible deadlock */
04625       if (!ast_channel_trylock(p->owner)) {
04626          append_history(p, "Cong", "Auto-congesting (timer)");
04627          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
04628          ast_channel_unlock(p->owner);
04629       }
04630    }
04631    sip_pvt_unlock(p);
04632    dialog_unref(p, "unreffing arg passed into auto_congest callback (p->initid)");
04633    return 0;
04634 }
04635 
04636 
04637 /*! \brief Initiate SIP call from PBX 
04638  *      used from the dial() application      */
04639 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
04640 {
04641    int res;
04642    struct sip_pvt *p = ast->tech_pvt;  /* chan is locked, so the reference cannot go away */
04643    struct varshead *headp;
04644    struct ast_var_t *current;
04645    const char *referer = NULL;   /* SIP referrer */
04646 
04647    if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
04648       ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
04649       return -1;
04650    }
04651 
04652    /* Check whether there is vxml_url, distinctive ring variables */
04653    headp=&ast->varshead;
04654    AST_LIST_TRAVERSE(headp, current, entries) {
04655       /* Check whether there is a VXML_URL variable */
04656       if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
04657          p->options->vxml_url = ast_var_value(current);
04658       } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
04659          p->options->uri_options = ast_var_value(current);
04660       } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
04661          /* Check whether there is a variable with a name starting with SIPADDHEADER */
04662          p->options->addsipheaders = 1;
04663       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
04664          /* This is a transfered call */
04665          p->options->transfer = 1;
04666       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
04667          /* This is the referrer */
04668          referer = ast_var_value(current);
04669       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
04670          /* We're replacing a call. */
04671          p->options->replaces = ast_var_value(current);
04672       }
04673    }
04674 
04675    res = 0;
04676    ast_set_flag(&p->flags[0], SIP_OUTGOING);
04677 
04678    if (p->options->transfer) {
04679       char buf[SIPBUFSIZE/2];
04680 
04681       if (referer) {
04682          if (sipdebug)
04683             ast_debug(3, "Call for %s transfered by %s\n", p->username, referer);
04684          snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
04685       } else 
04686          snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
04687       ast_string_field_set(p, cid_name, buf);
04688    } 
04689    ast_debug(1, "Outgoing Call for %s\n", p->username);
04690 
04691    res = update_call_counter(p, INC_CALL_RINGING);
04692 
04693    if (res == -1) {
04694       ast->hangupcause = AST_CAUSE_USER_BUSY;
04695       return res;
04696    }
04697    p->callingpres = ast->cid.cid_pres;
04698    p->jointcapability = ast_translate_available_formats(p->capability, p->prefcodec);
04699    p->jointnoncodeccapability = p->noncodeccapability;
04700 
04701    /* If there are no audio formats left to offer, punt */
04702    if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
04703       ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
04704       res = -1;
04705    } else {
04706       int xmitres;
04707 
04708       xmitres = transmit_invite(p, SIP_INVITE, 1, 2);
04709       if (xmitres == XMIT_ERROR)
04710          return -1;
04711       p->invitestate = INV_CALLING;
04712    
04713       /* Initialize auto-congest time */
04714       AST_SCHED_REPLACE_UNREF(p->initid, sched, p->timer_b, auto_congest, p, 
04715                         dialog_unref(_data, "dialog ptr dec when SCHED_REPLACE del op succeeded"), 
04716                         dialog_unref(p, "dialog ptr dec when SCHED_REPLACE add failed"),
04717                         dialog_ref(p, "dialog ptr inc when SCHED_REPLACE add succeeded") );
04718    }
04719    return res;
04720 }
04721 
04722 /*! \brief Destroy registry object
04723    Objects created with the register= statement in static configuration */
04724 static void sip_registry_destroy(struct sip_registry *reg)
04725 {
04726    /* Really delete */
04727    ast_debug(3, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
04728 
04729    if (reg->call) {
04730       /* Clear registry before destroying to ensure
04731          we don't get reentered trying to grab the registry lock */
04732       reg->call->registry = registry_unref(reg->call->registry, "destroy reg->call->registry");
04733       ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
04734       dialog_unlink_all(reg->call, TRUE, TRUE);
04735       reg->call = dialog_unref(reg->call, "unref reg->call");
04736       /* reg->call = sip_destroy(reg->call); */
04737    }
04738    AST_SCHED_DEL(sched, reg->expire);  
04739    AST_SCHED_DEL(sched, reg->timeout);
04740    
04741    ast_string_field_free_memory(reg);
04742    ast_atomic_fetchadd_int(&regobjs, -1);
04743    ast_dnsmgr_release(reg->dnsmgr);
04744    ast_free(reg);
04745 }
04746 
04747 /*! \brief Execute destruction of SIP dialog structure, release memory */
04748 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
04749 {
04750    struct sip_request *req;
04751 
04752    if (sip_debug_test_pvt(p))
04753       ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
04754 
04755    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
04756       update_call_counter(p, DEC_CALL_LIMIT);
04757       ast_debug(2, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
04758    }
04759 
04760    /* Unlink us from the owner if we have one */
04761    if (p->owner) {
04762       if (lockowner)
04763          ast_channel_lock(p->owner);
04764       if (option_debug)
04765          ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
04766       p->owner->tech_pvt = NULL;
04767       /* Make sure that the channel knows its backend is going away */
04768       p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
04769       if (lockowner)
04770          ast_channel_unlock(p->owner);
04771       /* Give the channel a chance to react before deallocation */
04772       usleep(1);
04773    }
04774 
04775    /* Remove link from peer to subscription of MWI */
04776    if (p->relatedpeer && p->relatedpeer->mwipvt)
04777       p->relatedpeer->mwipvt = dialog_unref(p->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
04778    if (p->relatedpeer && p->relatedpeer->call == p)
04779       p->relatedpeer->call = dialog_unref(p->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
04780    
04781    if (p->relatedpeer)
04782       p->relatedpeer = unref_peer(p->relatedpeer,"unsetting a dialog relatedpeer field in sip_destroy");
04783    
04784    if (p->registry) {
04785       if (p->registry->call == p)
04786          p->registry->call = dialog_unref(p->registry->call, "nulling out the registry's call dialog field in unlink_all");
04787       p->registry = registry_unref(p->registry, "delete p->registry");
04788    }
04789    
04790    if (dumphistory)
04791       sip_dump_history(p);
04792 
04793    if (p->options)
04794       ast_free(p->options);
04795 
04796    if (p->notify_headers) {
04797       ast_variables_destroy(p->notify_headers);
04798       p->notify_headers = NULL;
04799    }
04800    if (p->rtp) {
04801       ast_rtp_destroy(p->rtp);
04802    }
04803    if (p->vrtp) {
04804       ast_rtp_destroy(p->vrtp);
04805    }
04806    if (p->trtp) {
04807       while (ast_rtp_get_bridged(p->trtp))
04808          usleep(1);
04809       ast_rtp_destroy(p->trtp);
04810    }
04811    if (p->udptl)
04812       ast_udptl_destroy(p->udptl);
04813    if (p->refer)
04814       ast_free(p->refer);
04815    if (p->route) {
04816       free_old_route(p->route);
04817       p->route = NULL;
04818    }
04819    if (p->initreq.data)
04820       ast_free(p->initreq.data);
04821 
04822    /* Destroy Session-Timers if allocated */
04823    if (p->stimer) {
04824       if (p->stimer->st_active == TRUE && p->stimer->st_schedid > -1) {
04825          AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
04826                dialog_unref(p, "removing session timer ref"));
04827       }
04828       ast_free(p->stimer);
04829       p->stimer = NULL;
04830    }
04831 
04832    /* Clear history */
04833    if (p->history) {
04834       struct sip_history *hist;
04835       while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
04836          ast_free(hist);
04837          p->history_entries--;
04838       }
04839       ast_free(p->history);
04840       p->history = NULL;
04841    }
04842 
04843    while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
04844       ast_free(req);
04845    }
04846 
04847    if (p->chanvars) {
04848       ast_variables_destroy(p->chanvars);
04849       p->chanvars = NULL;
04850    }
04851 
04852    ast_string_field_free_memory(p);
04853 
04854    if (p->socket.tcptls_session) {
04855       ao2_ref(p->socket.tcptls_session, -1);
04856       p->socket.tcptls_session = NULL;
04857    }
04858 }
04859 
04860 /*! \brief  update_call_counter: Handle call_limit for SIP devices
04861  * Setting a call-limit will cause calls above the limit not to be accepted.
04862  *
04863  * Remember that for a type=friend, there's one limit for the user and
04864  * another for the peer, not a combined call limit.
04865  * This will cause unexpected behaviour in subscriptions, since a "friend"
04866  * is *two* devices in Asterisk, not one.
04867  *
04868  * Thought: For realtime, we should probably update storage with inuse counter... 
04869  *
04870  * \return 0 if call is ok (no call limit, below threshold)
04871  * -1 on rejection of call
04872  *    
04873  */
04874 static int update_call_counter(struct sip_pvt *fup, int event)
04875 {
04876    char name[256];
04877    int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
04878    int outgoing = fup->outgoing_call;
04879    struct sip_peer *p = NULL;
04880 
04881    ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
04882 
04883 
04884    /* Test if we need to check call limits, in order to avoid 
04885       realtime lookups if we do not need it */
04886    if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
04887       return 0;
04888 
04889    ast_copy_string(name, fup->username, sizeof(name));
04890 
04891    /* Check the list of devices */
04892    if ( (p = find_peer(ast_strlen_zero(fup->peername) ? name : fup->peername, NULL, TRUE, FINDALLDEVICES, FALSE) ) ) { /* Try to find peer */
04893       inuse = &p->inUse;
04894       call_limit = &p->call_limit;
04895       inringing = &p->inRinging;
04896       ast_copy_string(name, fup->peername, sizeof(name));
04897    }
04898    if (!p) {
04899       ast_debug(2, "%s is not a local device, no call limit\n", name);
04900       return 0;
04901    }
04902 
04903    switch(event) {
04904    /* incoming and outgoing affects the inUse counter */
04905    case DEC_CALL_LIMIT:
04906       /* Decrement inuse count if applicable */
04907       if (inuse) {
04908          sip_pvt_lock(fup);
04909          ao2_lock(p);
04910          if (*inuse > 0) {
04911             if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
04912                (*inuse)--;
04913                ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
04914             }
04915          } else {
04916             *inuse = 0;
04917          }
04918          ao2_unlock(p);
04919          sip_pvt_unlock(fup);
04920       }
04921 
04922       /* Decrement ringing count if applicable */
04923       if (inringing) {
04924          sip_pvt_lock(fup);
04925          ao2_lock(p);
04926          if (*inringing > 0) {
04927             if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
04928                (*inringing)--;
04929                ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
04930             }
04931          } else {
04932             *inringing = 0;
04933          }
04934          ao2_unlock(p);
04935          sip_pvt_unlock(fup);
04936       }
04937 
04938       /* Decrement onhold count if applicable */
04939       sip_pvt_lock(fup);
04940       ao2_lock(p);
04941       if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && global_notifyhold) {
04942          ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
04943          ao2_unlock(p);
04944          sip_pvt_unlock(fup);
04945          sip_peer_hold(fup, FALSE);
04946       } else {
04947          ao2_unlock(p);
04948          sip_pvt_unlock(fup);
04949       }
04950       if (sipdebug)
04951          ast_debug(2, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
04952       break;
04953 
04954    case INC_CALL_RINGING:
04955    case INC_CALL_LIMIT:
04956       /* If call limit is active and we have reached the limit, reject the call */
04957       if (*call_limit > 0 ) {
04958          if (*inuse >= *call_limit) {
04959             ast_log(LOG_ERROR, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
04960             unref_peer(p, "update_call_counter: unref peer p, call limit exceeded");
04961             return -1; 
04962          }
04963       }
04964       if (inringing && (event == INC_CALL_RINGING)) {
04965          sip_pvt_lock(fup);
04966          ao2_lock(p);
04967          if (!ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
04968             (*inringing)++;
04969             ast_set_flag(&fup->flags[0], SIP_INC_RINGING);
04970          }
04971          ao2_unlock(p);
04972          sip_pvt_unlock(fup);
04973       }
04974       if (inuse) {
04975          sip_pvt_lock(fup);
04976          ao2_lock(p);
04977          if (!ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
04978             (*inuse)++;
04979             ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
04980          }
04981          ao2_unlock(p);
04982          sip_pvt_unlock(fup);
04983       }
04984       if (sipdebug) {
04985          ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", "peer", name, *inuse, *call_limit);
04986       }
04987       break;
04988 
04989    case DEC_CALL_RINGING:
04990       if (inringing) {
04991          sip_pvt_lock(fup);
04992          ao2_lock(p);
04993          if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
04994             if (*inringing > 0) {
04995                (*inringing)--;
04996             }
04997             ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
04998          }
04999          ao2_unlock(p);
05000          sip_pvt_unlock(fup);
05001       }
05002       break;
05003 
05004    default:
05005       ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
05006    }
05007 
05008    if (p) {
05009       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", p->name);
05010       unref_peer(p, "update_call_counter: unref_peer from call counter");
05011    } 
05012    return 0;
05013 }
05014 
05015 
05016 static void sip_destroy_fn(void *p)
05017 {
05018    sip_destroy(p);
05019 }
05020 
05021 /*! \brief Destroy SIP call structure.
05022  * Make it return NULL so the caller can do things like
05023  * foo = sip_destroy(foo);
05024  * and reduce the chance of bugs due to dangling pointers.
05025  */
05026 static struct sip_pvt * sip_destroy(struct sip_pvt *p)
05027 {
05028    ast_debug(3, "Destroying SIP dialog %s\n", p->callid);
05029    __sip_destroy(p, TRUE, TRUE);
05030    return NULL;
05031 }
05032 
05033 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
05034 static int hangup_sip2cause(int cause)
05035 {
05036    /* Possible values taken from causes.h */
05037 
05038    switch(cause) {
05039       case 401:   /* Unauthorized */
05040          return AST_CAUSE_CALL_REJECTED;
05041       case 403:   /* Not found */
05042          return AST_CAUSE_CALL_REJECTED;
05043       case 404:   /* Not found */
05044          return AST_CAUSE_UNALLOCATED;
05045       case 405:   /* Method not allowed */
05046          return AST_CAUSE_INTERWORKING;
05047       case 407:   /* Proxy authentication required */
05048          return AST_CAUSE_CALL_REJECTED;
05049       case 408:   /* No reaction */
05050          return AST_CAUSE_NO_USER_RESPONSE;
05051       case 409:   /* Conflict */
05052          return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
05053       case 410:   /* Gone */
05054          return AST_CAUSE_NUMBER_CHANGED;
05055       case 411:   /* Length required */
05056          return AST_CAUSE_INTERWORKING;
05057       case 413:   /* Request entity too large */
05058          return AST_CAUSE_INTERWORKING;
05059       case 414:   /* Request URI too large */
05060          return AST_CAUSE_INTERWORKING;
05061       case 415:   /* Unsupported media type */
05062          return AST_CAUSE_INTERWORKING;
05063       case 420:   /* Bad extension */
05064          return AST_CAUSE_NO_ROUTE_DESTINATION;
05065       case 480:   /* No answer */
05066          return AST_CAUSE_NO_ANSWER;
05067       case 481:   /* No answer */
05068          return AST_CAUSE_INTERWORKING;
05069       case 482:   /* Loop detected */
05070          return AST_CAUSE_INTERWORKING;
05071       case 483:   /* Too many hops */
05072          return AST_CAUSE_NO_ANSWER;
05073       case 484:   /* Address incomplete */
05074          return AST_CAUSE_INVALID_NUMBER_FORMAT;
05075       case 485:   /* Ambiguous */
05076          return AST_CAUSE_UNALLOCATED;
05077       case 486:   /* Busy everywhere */
05078          return AST_CAUSE_BUSY;
05079       case 487:   /* Request terminated */
05080          return AST_CAUSE_INTERWORKING;
05081       case 488:   /* No codecs approved */
05082          return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05083       case 491:   /* Request pending */
05084          return AST_CAUSE_INTERWORKING;
05085       case 493:   /* Undecipherable */
05086          return AST_CAUSE_INTERWORKING;
05087       case 500:   /* Server internal failure */
05088          return AST_CAUSE_FAILURE;
05089       case 501:   /* Call rejected */
05090          return AST_CAUSE_FACILITY_REJECTED;
05091       case 502:   
05092          return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
05093       case 503:   /* Service unavailable */
05094          return AST_CAUSE_CONGESTION;
05095       case 504:   /* Gateway timeout */
05096          return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
05097       case 505:   /* SIP version not supported */
05098          return AST_CAUSE_INTERWORKING;
05099       case 600:   /* Busy everywhere */
05100          return AST_CAUSE_USER_BUSY;
05101       case 603:   /* Decline */
05102          return AST_CAUSE_CALL_REJECTED;
05103       case 604:   /* Does not exist anywhere */
05104          return AST_CAUSE_UNALLOCATED;
05105       case 606:   /* Not acceptable */
05106          return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05107       default:
05108          return AST_CAUSE_NORMAL;
05109    }
05110    /* Never reached */
05111    return 0;
05112 }
05113 
05114 /*! \brief Convert Asterisk hangup causes to SIP codes 
05115 \verbatim
05116  Possible values from causes.h
05117         AST_CAUSE_NOTDEFINED    AST_CAUSE_NORMAL        AST_CAUSE_BUSY
05118         AST_CAUSE_FAILURE       AST_CAUSE_CONGESTION    AST_CAUSE_UNALLOCATED
05119 
05120    In addition to these, a lot of PRI codes is defined in causes.h 
05121    ...should we take care of them too ?
05122    
05123    Quote RFC 3398
05124 
05125    ISUP Cause value                        SIP response
05126    ----------------                        ------------
05127    1  unallocated number                   404 Not Found
05128    2  no route to network                  404 Not found
05129    3  no route to destination              404 Not found
05130    16 normal call clearing                 --- (*)
05131    17 user busy                            486 Busy here
05132    18 no user responding                   408 Request Timeout
05133    19 no answer from the user              480 Temporarily unavailable
05134    20 subscriber absent                    480 Temporarily unavailable
05135    21 call rejected                        403 Forbidden (+)
05136    22 number changed (w/o diagnostic)      410 Gone
05137    22 number changed (w/ diagnostic)       301 Moved Permanently
05138    23 redirection to new destination       410 Gone
05139    26 non-selected user clearing           404 Not Found (=)
05140    27 destination out of order             502 Bad Gateway
05141    28 address incomplete                   484 Address incomplete
05142    29 facility rejected                    501 Not implemented
05143    31 normal unspecified                   480 Temporarily unavailable
05144 \endverbatim
05145 */
05146 static const char *hangup_cause2sip(int cause)
05147 {
05148    switch (cause) {
05149       case AST_CAUSE_UNALLOCATED:      /* 1 */
05150       case AST_CAUSE_NO_ROUTE_DESTINATION:   /* 3 IAX2: Can't find extension in context */
05151       case AST_CAUSE_NO_ROUTE_TRANSIT_NET:   /* 2 */
05152          return "404 Not Found";
05153       case AST_CAUSE_CONGESTION:    /* 34 */
05154       case AST_CAUSE_SWITCH_CONGESTION:   /* 42 */
05155          return "503 Service Unavailable";
05156       case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
05157          return "408 Request Timeout";
05158       case AST_CAUSE_NO_ANSWER:     /* 19 */
05159       case AST_CAUSE_UNREGISTERED:        /* 20 */
05160          return "480 Temporarily unavailable";
05161       case AST_CAUSE_CALL_REJECTED:    /* 21 */
05162          return "403 Forbidden";
05163       case AST_CAUSE_NUMBER_CHANGED:      /* 22 */
05164          return "410 Gone";
05165       case AST_CAUSE_NORMAL_UNSPECIFIED:  /* 31 */
05166          return "480 Temporarily unavailable";
05167       case AST_CAUSE_INVALID_NUMBER_FORMAT:
05168          return "484 Address incomplete";
05169       case AST_CAUSE_USER_BUSY:
05170          return "486 Busy here";
05171       case AST_CAUSE_FAILURE:
05172          return "500 Server internal failure";
05173       case AST_CAUSE_FACILITY_REJECTED:   /* 29 */
05174          return "501 Not Implemented";
05175       case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
05176          return "503 Service Unavailable";
05177       /* Used in chan_iax2 */
05178       case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
05179          return "502 Bad Gateway";
05180       case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
05181          return "488 Not Acceptable Here";
05182          
05183       case AST_CAUSE_NOTDEFINED:
05184       default:
05185          ast_debug(1, "AST hangup cause %d (no match found in SIP)\n", cause);
05186          return NULL;
05187    }
05188 
05189    /* Never reached */
05190    return 0;
05191 }
05192 
05193 
05194 /*! \brief  sip_hangup: Hangup SIP call
05195  * Part of PBX interface, called from ast_hangup */
05196 static int sip_hangup(struct ast_channel *ast)
05197 {
05198    struct sip_pvt *p = ast->tech_pvt;
05199    int needcancel = FALSE;
05200    int needdestroy = 0;
05201    struct ast_channel *oldowner = ast;
05202 
05203    if (!p) {
05204       ast_debug(1, "Asked to hangup channel that was not connected\n");
05205       return 0;
05206    }
05207    if (ast_test_flag(ast, AST_FLAG_ANSWERED_ELSEWHERE)) {
05208       ast_debug(1, "This call was answered elsewhere");
05209       append_history(p, "Cancel", "Call answered elsewhere");
05210       p->answered_elsewhere = TRUE;
05211    }
05212 
05213    /* Store hangupcause locally in PVT so we still have it before disconnect */
05214    if (p->owner)
05215       p->hangupcause = p->owner->hangupcause;
05216 
05217    if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
05218       if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05219          if (sipdebug)
05220             ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
05221          update_call_counter(p, DEC_CALL_LIMIT);
05222       }
05223       ast_debug(4, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
05224       if (p->autokillid > -1 && sip_cancel_destroy(p))
05225          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
05226       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05227       ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Really hang up next time */
05228       p->needdestroy = 0;
05229       p->owner->tech_pvt = dialog_unref(p->owner->tech_pvt, "unref p->owner->tech_pvt");
05230       sip_pvt_lock(p);
05231       p->owner = NULL;  /* Owner will be gone after we return, so take it away */
05232       sip_pvt_unlock(p);
05233       return 0;
05234    }
05235 
05236    if (ast_test_flag(ast, AST_FLAG_ZOMBIE)) {
05237       if (p->refer)
05238          ast_debug(1, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast->name, p->callid);
05239       else
05240          ast_debug(1, "Hanging up zombie call. Be scared.\n");
05241    } else
05242       ast_debug(1, "Hangup call %s, SIP callid %s\n", ast->name, p->callid);
05243 
05244    sip_pvt_lock(p);
05245    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05246       if (sipdebug)
05247          ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
05248       update_call_counter(p, DEC_CALL_LIMIT);
05249    }
05250 
05251    /* Determine how to disconnect */
05252    if (p->owner != ast) {
05253       ast_log(LOG_WARNING, "Huh?  We aren't the owner? Can't hangup call.\n");
05254       sip_pvt_unlock(p);
05255       return 0;
05256    }
05257    /* If the call is not UP, we need to send CANCEL instead of BYE */
05258    /* In case of re-invites, the call might be UP even though we have an incomplete invite transaction */
05259    if (p->invitestate < INV_COMPLETED && p->owner->_state != AST_STATE_UP) {
05260       needcancel = TRUE;
05261       ast_debug(4, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
05262    }
05263 
05264    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
05265 
05266    append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", p->owner ? ast_cause2str(p->hangupcause) : "Unknown");
05267 
05268    /* Disconnect */
05269    if (p->vad)
05270       ast_dsp_free(p->vad);
05271 
05272    p->owner = NULL;
05273    ast->tech_pvt = dialog_unref(ast->tech_pvt, "unref ast->tech_pvt");
05274 
05275    ast_module_unref(ast_module_info->self);
05276    /* Do not destroy this pvt until we have timeout or
05277       get an answer to the BYE or INVITE/CANCEL 
05278       If we get no answer during retransmit period, drop the call anyway.
05279       (Sorry, mother-in-law, you can't deny a hangup by sending
05280       603 declined to BYE...)
05281    */
05282    if (p->alreadygone)
05283       needdestroy = 1;  /* Set destroy flag at end of this function */
05284    else if (p->invitestate != INV_CALLING)
05285       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05286 
05287    /* Start the process if it's not already started */
05288    if (!p->alreadygone && p->initreq.data && !ast_strlen_zero(p->initreq.data->str)) {
05289       if (needcancel) { /* Outgoing call, not up */
05290          if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
05291             /* stop retransmitting an INVITE that has not received a response */
05292             struct sip_pkt *cur;
05293             for (cur = p->packets; cur; cur = cur->next) {
05294                __sip_semi_ack(p, cur->seqno, cur->is_resp, cur->method ? cur->method : find_sip_method(cur->data->str));
05295             }
05296 
05297             /* if we can't send right now, mark it pending */
05298             if (p->invitestate == INV_CALLING) {
05299                /* We can't send anything in CALLING state */
05300                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
05301                /* Do we need a timer here if we don't hear from them at all? */
05302                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05303                append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
05304             } else {
05305                p->invitestate = INV_CANCELLED;
05306                /* Send a new request: CANCEL */
05307                transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
05308                /* Actually don't destroy us yet, wait for the 487 on our original 
05309                   INVITE, but do set an autodestruct just in case we never get it. */
05310                needdestroy = 0;
05311                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05312             }
05313          } else { /* Incoming call, not up */
05314             const char *res;
05315             if (p->hangupcause && (res = hangup_cause2sip(p->hangupcause)))
05316                transmit_response_reliable(p, res, &p->initreq);
05317             else 
05318                transmit_response_reliable(p, "603 Declined", &p->initreq);
05319             p->invitestate = INV_TERMINATED;
05320          }
05321       } else { /* Call is in UP state, send BYE */
05322          if (p->stimer->st_active == TRUE) {
05323             stop_session_timer(p);
05324          }
05325 
05326          if (!p->pendinginvite) {
05327             struct ast_channel *bridge = ast_bridged_channel(oldowner);
05328             char *audioqos = "";
05329             char *videoqos = "";
05330             char *textqos = "";
05331 
05332             /* We need to get the lock on bridge because ast_rtp_set_vars will attempt
05333              * to lock the bridge. This may get hairy...
05334              */
05335             while (bridge && ast_channel_trylock(bridge)) {
05336                struct ast_channel *chan = p->owner;
05337                sip_pvt_unlock(p);
05338                do {
05339                   /* Use chan since p->owner could go NULL on us
05340                    * while p is unlocked
05341                    */
05342                   CHANNEL_DEADLOCK_AVOIDANCE(chan);
05343                } while (sip_pvt_trylock(p));
05344                bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
05345             }
05346 
05347             if (p->rtp)
05348                ast_rtp_set_vars(oldowner, p->rtp);
05349 
05350             if (bridge) {
05351                struct sip_pvt *q = bridge->tech_pvt;
05352 
05353                if (IS_SIP_TECH(bridge->tech) && q && q->rtp)
05354                   ast_rtp_set_vars(bridge, q->rtp);
05355                ast_channel_unlock(bridge);
05356             }
05357 
05358             if (p->vrtp)
05359                videoqos = ast_rtp_get_quality(p->vrtp, NULL, RTPQOS_SUMMARY);
05360             if (p->trtp)
05361                textqos = ast_rtp_get_quality(p->trtp, NULL, RTPQOS_SUMMARY);
05362             /* Send a hangup */
05363             if (oldowner->_state == AST_STATE_UP) {
05364                transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
05365             }
05366 
05367             /* Get RTCP quality before end of call */
05368             if (p->do_history) {
05369                if (p->rtp)
05370                   append_history(p, "RTCPaudio", "Quality:%s", audioqos);
05371                if (p->vrtp)
05372                   append_history(p, "RTCPvideo", "Quality:%s", videoqos);
05373                if (p->trtp)
05374                   append_history(p, "RTCPtext", "Quality:%s", textqos);
05375             }
05376             if (p->rtp && oldowner)
05377                pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", audioqos);
05378             if (p->vrtp && oldowner)
05379                pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", videoqos);
05380             if (p->trtp && oldowner)
05381                pbx_builtin_setvar_helper(oldowner, "RTPTEXTQOS", textqos);
05382          } else {
05383             /* Note we will need a BYE when this all settles out
05384                but we can't send one while we have "INVITE" outstanding. */
05385             ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
05386             ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE); 
05387             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"));
05388             if (sip_cancel_destroy(p))
05389                ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
05390          }
05391       }
05392    }
05393    if (needdestroy)
05394       p->needdestroy = 1;
05395    sip_pvt_unlock(p);
05396    return 0;
05397 }
05398 
05399 /*! \brief Try setting codec suggested by the SIP_CODEC channel variable */
05400 static void try_suggested_sip_codec(struct sip_pvt *p)
05401 {
05402    int fmt;
05403    const char *codec;
05404 
05405    while (p->owner && ast_channel_trylock(p->owner)) {
05406       sip_pvt_unlock(p);
05407       sched_yield();
05408       sip_pvt_lock(p);
05409    }
05410 
05411    if (!p->owner)
05412       return;
05413 
05414    codec = ast_strdupa(S_OR(pbx_builtin_getvar_helper(p->owner, "SIP_CODEC"), ""));
05415 
05416    ast_channel_unlock(p->owner);
05417 
05418    if (ast_strlen_zero(codec))
05419       return;
05420 
05421    fmt = ast_getformatbyname(codec);
05422    if (fmt) {
05423       ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
05424       if (p->jointcapability & fmt) {
05425          p->jointcapability &= fmt;
05426          p->capability &= fmt;
05427       } else
05428          ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
05429    } else
05430       ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
05431    return;  
05432 }
05433 
05434 /*! \brief  sip_answer: Answer SIP call , send 200 OK on Invite 
05435  * Part of PBX interface */
05436 static int sip_answer(struct ast_channel *ast)
05437 {
05438    int res = 0;
05439    struct sip_pvt *p = ast->tech_pvt;
05440 
05441    sip_pvt_lock(p);
05442    if (ast->_state != AST_STATE_UP) {
05443       try_suggested_sip_codec(p);   
05444 
05445       ast_setstate(ast, AST_STATE_UP);
05446       ast_debug(1, "SIP answering channel: %s\n", ast->name);
05447       ast_rtp_new_source(p->rtp);
05448       res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL, FALSE);
05449       ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
05450    }
05451    sip_pvt_unlock(p);
05452    return res;
05453 }
05454 
05455 /*! \brief Send frame to media channel (rtp) */
05456 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
05457 {
05458    struct sip_pvt *p = ast->tech_pvt;
05459    int res = 0;
05460 
05461    switch (frame->frametype) {
05462    case AST_FRAME_VOICE:
05463       if (!(frame->subclass & ast->nativeformats)) {
05464          char s1[512], s2[512], s3[512];
05465          ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %s(%d) read/write = %s(%d)/%s(%d)\n",
05466             frame->subclass, 
05467             ast_getformatname_multiple(s1, sizeof(s1) - 1, ast->nativeformats & AST_FORMAT_AUDIO_MASK),
05468             ast->nativeformats & AST_FORMAT_AUDIO_MASK,
05469             ast_getformatname_multiple(s2, sizeof(s2) - 1, ast->readformat),
05470             ast->readformat,
05471             ast_getformatname_multiple(s3, sizeof(s3) - 1, ast->writeformat),
05472             ast->writeformat);
05473          return 0;
05474       }
05475       if (p) {
05476          sip_pvt_lock(p);
05477          if (p->rtp) {
05478             /* If channel is not up, activate early media session */
05479             if ((ast->_state != AST_STATE_UP) &&
05480                 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
05481                 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
05482                ast_rtp_new_source(p->rtp);
05483                p->invitestate = INV_EARLY_MEDIA;
05484                transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE, FALSE);
05485                ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);  
05486             } else if (p->t38.state == T38_ENABLED) {
05487                change_t38_state(p, T38_DISABLED);
05488                transmit_reinvite_with_sdp(p, FALSE, FALSE);
05489             } else {
05490                p->lastrtptx = time(NULL);
05491                res = ast_rtp_write(p->rtp, frame);
05492             }
05493          }
05494          sip_pvt_unlock(p);
05495       }
05496       break;
05497    case AST_FRAME_VIDEO:
05498       if (p) {
05499          sip_pvt_lock(p);
05500          if (p->vrtp) {
05501             /* Activate video early media */
05502             if ((ast->_state != AST_STATE_UP) &&
05503                 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
05504                 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
05505                p->invitestate = INV_EARLY_MEDIA;
05506                transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE, FALSE);
05507                ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);  
05508             }
05509             p->lastrtptx = time(NULL);
05510             res = ast_rtp_write(p->vrtp, frame);
05511          }
05512          sip_pvt_unlock(p);
05513       }
05514       break;
05515    case AST_FRAME_TEXT:
05516       if (p) {
05517          sip_pvt_lock(p);
05518          if (p->red) {
05519             red_buffer_t140(p->trtp, frame);
05520          } else {
05521             if (p->trtp) {
05522                /* Activate text early media */
05523                if ((ast->_state != AST_STATE_UP) &&
05524                    !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
05525                    !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
05526                   p->invitestate = INV_EARLY_MEDIA;
05527                   transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE, FALSE);
05528                   ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);  
05529                }
05530                p->lastrtptx = time(NULL);
05531                res = ast_rtp_write(p->trtp, frame);
05532             }
05533          }
05534          sip_pvt_unlock(p);
05535       }
05536       break;
05537    case AST_FRAME_IMAGE:
05538       return 0;
05539       break;
05540    case AST_FRAME_MODEM:
05541       if (p) {
05542          sip_pvt_lock(p);
05543          /* UDPTL requires two-way communication, so early media is not needed here.
05544             we simply forget the frames if we get modem frames before the bridge is up.
05545             Fax will re-transmit.
05546          */
05547          if ((ast->_state == AST_STATE_UP) &&
05548              p->udptl &&
05549              (p->t38.state == T38_ENABLED)) {
05550             res = ast_udptl_write(p->udptl, frame);
05551          }
05552          sip_pvt_unlock(p);
05553       }
05554       break;
05555    default: 
05556       ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
05557       return 0;
05558    }
05559 
05560    return res;
05561 }
05562 
05563 /*! \brief  sip_fixup: Fix up a channel:  If a channel is consumed, this is called.
05564         Basically update any ->owner links */
05565 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
05566 {
05567    int ret = -1;
05568    struct sip_pvt *p;
05569 
05570    if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE))
05571       ast_debug(1, "New channel is zombie\n");
05572    if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE))
05573       ast_debug(1, "Old channel is zombie\n");
05574 
05575    if (!newchan || !newchan->tech_pvt) {
05576       if (!newchan)
05577          ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
05578       else
05579          ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
05580       return -1;
05581    }
05582    p = newchan->tech_pvt;
05583 
05584    sip_pvt_lock(p);
05585    append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
05586    append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
05587    if (p->owner != oldchan)
05588       ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
05589    else {
05590       p->owner = newchan;
05591       /* Re-invite RTP back to Asterisk. Needed if channel is masqueraded out of a native
05592          RTP bridge (i.e., RTP not going through Asterisk): RTP bridge code might not be
05593          able to do this if the masquerade happens before the bridge breaks (e.g., AMI
05594          redirect of both channels). Note that a channel can not be masqueraded *into*
05595          a native bridge. So there is no danger that this breaks a native bridge that
05596          should stay up. */
05597       sip_set_rtp_peer(newchan, NULL, NULL, 0, 0, 0);
05598       ret = 0;
05599    }
05600    ast_debug(3, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);
05601 
05602    sip_pvt_unlock(p);
05603    return ret;
05604 }
05605 
05606 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
05607 {
05608    struct sip_pvt *p = ast->tech_pvt;
05609    int res = 0;
05610 
05611    sip_pvt_lock(p);
05612    switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
05613    case SIP_DTMF_INBAND:
05614       res = -1; /* Tell Asterisk to generate inband indications */
05615       break;
05616    case SIP_DTMF_RFC2833:
05617       if (p->rtp)
05618          ast_rtp_senddigit_begin(p->rtp, digit);
05619       break;
05620    default:
05621       break;
05622    }
05623    sip_pvt_unlock(p);
05624 
05625    return res;
05626 }
05627 
05628 /*! \brief Send DTMF character on SIP channel
05629    within one call, we're able to transmit in many methods simultaneously */
05630 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
05631 {
05632    struct sip_pvt *p = ast->tech_pvt;
05633    int res = 0;
05634 
05635    sip_pvt_lock(p);
05636    switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
05637    case SIP_DTMF_INFO:
05638    case SIP_DTMF_SHORTINFO:
05639       transmit_info_with_digit(p, digit, duration);
05640       break;
05641    case SIP_DTMF_RFC2833:
05642       if (p->rtp)
05643          ast_rtp_senddigit_end(p->rtp, digit);
05644       break;
05645    case SIP_DTMF_INBAND:
05646       res = -1; /* Tell Asterisk to stop inband indications */
05647       break;
05648    }
05649    sip_pvt_unlock(p);
05650 
05651    return res;
05652 }
05653 
05654 /*! \brief Transfer SIP call */
05655 static int sip_transfer(struct ast_channel *ast, const char *dest)
05656 {
05657    struct sip_pvt *p = ast->tech_pvt;
05658    int res;
05659 
05660    if (dest == NULL) /* functions below do not take a NULL */
05661       dest = "";
05662    sip_pvt_lock(p);
05663    if (ast->_state == AST_STATE_RING)
05664       res = sip_sipredirect(p, dest);
05665    else
05666       res = transmit_refer(p, dest);
05667    sip_pvt_unlock(p);
05668    return res;
05669 }
05670 
05671 /*! \brief Helper function which updates T.38 capability information and triggers a reinvite */
05672 static void interpret_t38_parameters(struct sip_pvt *p, const struct ast_control_t38_parameters *parameters)
05673 {
05674    switch (parameters->request_response) {
05675    case AST_T38_NEGOTIATED:
05676    case AST_T38_REQUEST_NEGOTIATE:         /* Request T38 */
05677       if (p->t38.state == T38_PEER_REINVITE) {
05678          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"));
05679          p->t38.our_parms = *parameters;
05680          /* modify our parameters to conform to the peer's parameters,
05681           * based on the rules in the ITU T.38 recommendation
05682           */
05683          if (!p->t38.their_parms.fill_bit_removal) {
05684             p->t38.our_parms.fill_bit_removal = FALSE;
05685          }
05686          if (!p->t38.their_parms.transcoding_mmr) {
05687             p->t38.our_parms.transcoding_mmr = FALSE;
05688          }
05689          if (!p->t38.their_parms.transcoding_jbig) {
05690             p->t38.our_parms.transcoding_jbig = FALSE;
05691          }
05692          p->t38.our_parms.version = MIN(p->t38.our_parms.version, p->t38.their_parms.version);
05693          p->t38.our_parms.rate_management = p->t38.their_parms.rate_management;
05694          ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
05695          change_t38_state(p, T38_ENABLED);
05696          transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
05697       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && p->t38.state != T38_ENABLED) {
05698          p->t38.our_parms = *parameters;
05699          ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
05700          change_t38_state(p, T38_LOCAL_REINVITE);
05701          if (!p->pendinginvite) {
05702             transmit_reinvite_with_sdp(p, TRUE, FALSE);
05703          } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
05704             ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
05705          }
05706       }
05707       break;
05708    case AST_T38_TERMINATED:
05709    case AST_T38_REFUSED:
05710    case AST_T38_REQUEST_TERMINATE:         /* Shutdown T38 */
05711       if (p->t38.state == T38_PEER_REINVITE) {
05712          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"));
05713          change_t38_state(p, T38_DISABLED);
05714          transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
05715       } else if (p->t38.state == T38_ENABLED)
05716          transmit_reinvite_with_sdp(p, FALSE, FALSE);
05717       break;
05718    default:
05719       break;
05720    }
05721 }
05722 
05723 /*! \brief Play indication to user 
05724  * With SIP a lot of indications is sent as messages, letting the device play
05725    the indication - busy signal, congestion etc 
05726    \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
05727 */
05728 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
05729 {
05730    struct sip_pvt *p = ast->tech_pvt;
05731    int res = 0;
05732 
05733    sip_pvt_lock(p);
05734    switch(condition) {
05735    case AST_CONTROL_RINGING:
05736       if (ast->_state == AST_STATE_RING) {
05737          p->invitestate = INV_EARLY_MEDIA;
05738          if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
05739              (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {            
05740             /* Send 180 ringing if out-of-band seems reasonable */
05741             transmit_response(p, "180 Ringing", &p->initreq);
05742             ast_set_flag(&p->flags[0], SIP_RINGING);
05743             if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
05744                break;
05745          } else {
05746             /* Well, if it's not reasonable, just send in-band */
05747          }
05748       }
05749       res = -1;
05750       break;
05751    case AST_CONTROL_BUSY:
05752       if (ast->_state != AST_STATE_UP) {
05753          transmit_response_reliable(p, "486 Busy Here", &p->initreq);
05754          p->invitestate = INV_COMPLETED;
05755          sip_alreadygone(p);
05756          ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
05757          break;
05758       }
05759       res = -1;
05760       break;
05761    case AST_CONTROL_CONGESTION:
05762       if (ast->_state != AST_STATE_UP) {
05763          transmit_response_reliable(p, "503 Service Unavailable", &p->initreq);
05764          p->invitestate = INV_COMPLETED;
05765          sip_alreadygone(p);
05766          ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
05767          break;
05768       }
05769       res = -1;
05770       break;
05771    case AST_CONTROL_PROCEEDING:
05772       if ((ast->_state != AST_STATE_UP) &&
05773           !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
05774           !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
05775          transmit_response(p, "100 Trying", &p->initreq);
05776          p->invitestate = INV_PROCEEDING;  
05777          break;
05778       }
05779       res = -1;
05780       break;
05781    case AST_CONTROL_PROGRESS:
05782       if ((ast->_state != AST_STATE_UP) &&
05783           !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
05784           !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
05785          p->invitestate = INV_EARLY_MEDIA;
05786          transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE, FALSE);
05787          ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);  
05788          break;
05789       }
05790       res = -1;
05791       break;
05792    case AST_CONTROL_HOLD:
05793       ast_rtp_new_source(p->rtp);
05794       ast_moh_start(ast, data, p->mohinterpret);
05795       break;
05796    case AST_CONTROL_UNHOLD:
05797       ast_rtp_new_source(p->rtp);
05798       ast_moh_stop(ast);
05799       break;
05800    case AST_CONTROL_VIDUPDATE:   /* Request a video frame update */
05801       if (p->vrtp && !p->novideo) {
05802          transmit_info_with_vidupdate(p);
05803          /* ast_rtcp_send_h261fur(p->vrtp); */
05804       } else
05805          res = -1;
05806       break;
05807    case AST_CONTROL_T38_PARAMETERS:
05808       if (datalen != sizeof(struct ast_control_t38_parameters)) {
05809          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);
05810       } else {
05811          const struct ast_control_t38_parameters *parameters = data;
05812          interpret_t38_parameters(p, parameters);
05813       }
05814       break;
05815    case AST_CONTROL_SRCUPDATE:
05816       ast_rtp_new_source(p->rtp);
05817       break;
05818    case -1:
05819       res = -1;
05820       break;
05821    default:
05822       ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
05823       res = -1;
05824       break;
05825    }
05826    sip_pvt_unlock(p);
05827    return res;
05828 }
05829 
05830 
05831 /*! \brief Initiate a call in the SIP channel
05832    called from sip_request_call (calls from the pbx ) for outbound channels
05833    and from handle_request_invite for inbound channels
05834    
05835 */
05836 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title)
05837 {
05838    struct ast_channel *tmp;
05839    struct ast_variable *v = NULL;
05840    int fmt;
05841    int what;
05842    int video;
05843    int text;
05844    int needvideo = 0;
05845    int needtext = 0;
05846    char buf[SIPBUFSIZE];
05847    char *decoded_exten;
05848 
05849    {
05850       const char *my_name; /* pick a good name */
05851    
05852       if (title)
05853          my_name = title;
05854       else if ( (my_name = strchr(i->fromdomain, ':')) )
05855          my_name++;  /* skip ':' */
05856       else
05857          my_name = i->fromdomain;
05858 
05859       sip_pvt_unlock(i);
05860       /* Don't hold a sip pvt lock while we allocate a channel */
05861       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, (int)(long) i);
05862 
05863    }
05864    if (!tmp) {
05865       ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
05866       sip_pvt_lock(i);
05867       return NULL;
05868    }
05869    sip_pvt_lock(i);
05870 
05871    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;
05872 
05873    /* Select our native format based on codec preference until we receive
05874       something from another device to the contrary. */
05875    if (i->jointcapability) {  /* The joint capabilities of us and peer */
05876       what = i->jointcapability;
05877       video = i->jointcapability & AST_FORMAT_VIDEO_MASK;
05878       text = i->jointcapability & AST_FORMAT_TEXT_MASK;
05879    } else if (i->capability) {      /* Our configured capability for this peer */
05880       what = i->capability;
05881       video = i->capability & AST_FORMAT_VIDEO_MASK;
05882       text = i->capability & AST_FORMAT_TEXT_MASK;
05883    } else {
05884       what = global_capability;  /* Global codec support */
05885       video = global_capability & AST_FORMAT_VIDEO_MASK;
05886       text = global_capability & AST_FORMAT_TEXT_MASK;
05887    }
05888 
05889    /* Set the native formats for audio  and merge in video */
05890    tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | video | text;
05891    ast_debug(3, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmp->nativeformats));
05892    ast_debug(3, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcapability));
05893    ast_debug(3, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->capability));
05894    ast_debug(3, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, ast_codec_choose(&i->prefs, what, 1)));
05895    if (i->prefcodec)
05896       ast_debug(3, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcodec));
05897 
05898    /* XXX Why are we choosing a codec from the native formats?? */
05899    fmt = ast_best_codec(tmp->nativeformats);
05900 
05901    /* If we have a prefcodec setting, we have an inbound channel that set a 
05902       preferred format for this call. Otherwise, we check the jointcapability
05903       We also check for vrtp. If it's not there, we are not allowed do any video anyway.
05904     */
05905    if (i->vrtp) {
05906       if (ast_test_flag(&i->flags[1], SIP_PAGE2_VIDEOSUPPORT))
05907          needvideo = AST_FORMAT_VIDEO_MASK;
05908       else if (i->prefcodec)
05909          needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK;  /* Outbound call */
05910       else
05911          needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK;  /* Inbound call */
05912    }
05913 
05914    if (i->trtp) {
05915       if (i->prefcodec)
05916          needtext = i->prefcodec & AST_FORMAT_TEXT_MASK; /* Outbound call */
05917       else
05918          needtext = i->jointcapability & AST_FORMAT_TEXT_MASK; /* Inbound call */
05919    }
05920 
05921    if (needvideo) 
05922       ast_debug(3, "This channel can handle video! HOLLYWOOD next!\n");
05923    else
05924       ast_debug(3, "This channel will not be able to handle video.\n");
05925 
05926    if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) || (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
05927       i->vad = ast_dsp_new();
05928       ast_dsp_set_features(i->vad, DSP_FEATURE_DIGIT_DETECT);
05929       if (global_relaxdtmf)
05930          ast_dsp_set_digitmode(i->vad, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
05931    }
05932 
05933    /* Set file descriptors for audio, video, realtime text and UDPTL as needed */
05934    if (i->rtp) {
05935       ast_channel_set_fd(tmp, 0, ast_rtp_fd(i->rtp));
05936       ast_channel_set_fd(tmp, 1, ast_rtcp_fd(i->rtp));
05937    }
05938    if (needvideo && i->vrtp) {
05939       ast_channel_set_fd(tmp, 2, ast_rtp_fd(i->vrtp));
05940       ast_channel_set_fd(tmp, 3, ast_rtcp_fd(i->vrtp));
05941    }
05942    if (needtext && i->trtp) 
05943       ast_channel_set_fd(tmp, 4, ast_rtp_fd(i->trtp));
05944    if (i->udptl)
05945       ast_channel_set_fd(tmp, 5, ast_udptl_fd(i->udptl));
05946 
05947    if (state == AST_STATE_RING)
05948       tmp->rings = 1;
05949    tmp->adsicpe = AST_ADSI_UNAVAILABLE;
05950    tmp->writeformat = fmt;
05951    tmp->rawwriteformat = fmt;
05952    tmp->readformat = fmt;
05953    tmp->rawreadformat = fmt;
05954    tmp->tech_pvt = dialog_ref(i, "sip_new: set chan->tech_pvt to i");
05955 
05956    tmp->callgroup = i->callgroup;
05957    tmp->pickupgroup = i->pickupgroup;
05958    tmp->cid.cid_pres = i->callingpres;
05959    if (!ast_strlen_zero(i->accountcode))
05960       ast_string_field_set(tmp, accountcode, i->accountcode);
05961    if (i->amaflags)
05962       tmp->amaflags = i->amaflags;
05963    if (!ast_strlen_zero(i->language))
05964       ast_string_field_set(tmp, language, i->language);
05965    i->owner = tmp;
05966    ast_module_ref(ast_module_info->self);
05967    ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
05968    /*Since it is valid to have extensions in the dialplan that have unescaped characters in them
05969     * we should decode the uri before storing it in the channel, but leave it encoded in the sip_pvt
05970     * structure so that there aren't issues when forming URI's
05971     */
05972    decoded_exten = ast_strdupa(i->exten);
05973    ast_uri_decode(decoded_exten);
05974    ast_copy_string(tmp->exten, decoded_exten, sizeof(tmp->exten));
05975 
05976    /* Don't use ast_set_callerid() here because it will
05977     * generate an unnecessary NewCallerID event  */
05978    tmp->cid.cid_ani = ast_strdup(i->cid_num);
05979    if (!ast_strlen_zero(i->rdnis))
05980       tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
05981    
05982    if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
05983       tmp->cid.cid_dnid = ast_strdup(i->exten);
05984 
05985    tmp->priority = 1;
05986    if (!ast_strlen_zero(i->uri))
05987       pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
05988    if (!ast_strlen_zero(i->domain))
05989       pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
05990    if (!ast_strlen_zero(i->callid))
05991       pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
05992    if (i->rtp)
05993       ast_jb_configure(tmp, &global_jbconf);
05994 
05995    /* Set channel variables for this call from configuration */
05996    for (v = i->chanvars ; v ; v = v->next)
05997       pbx_builtin_setvar_helper(tmp, v->name, v->value);
05998 
05999    if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
06000       ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
06001       tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
06002       ast_hangup(tmp);
06003       tmp = NULL;
06004    }
06005 
06006    if (i->do_history)
06007       append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);
06008 
06009    /* Inform manager user about new channel and their SIP call ID */
06010    if (global_callevents)
06011       manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
06012          "Channel: %s\r\nUniqueid: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\n",
06013          tmp->name, tmp->uniqueid, "SIP", i->callid, i->fullcontact);
06014 
06015    return tmp;
06016 }
06017 
06018 /*! \brief Reads one line of SIP message body */
06019 static char *get_body_by_line(const char *line, const char *name, int nameLen)
06020 {
06021    if (!strncasecmp(line, name, nameLen) && line[nameLen] == '=')
06022       return ast_skip_blanks(line + nameLen + 1);
06023 
06024    return "";
06025 }
06026 
06027 /*! \brief Lookup 'name' in the SDP starting
06028  * at the 'start' line. Returns the matching line, and 'start'
06029  * is updated with the next line number.
06030  */
06031 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
06032 {
06033    int len = strlen(name);
06034 
06035    while (*start < req->sdp_end) {
06036       const char *r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[(*start)++]), name, len);
06037       if (r[0] != '\0')
06038          return r;
06039    }
06040 
06041    return "";
06042 }
06043 
06044 /*! \brief Get a line from an SDP message body */
06045 static const char *get_sdp(struct sip_request *req, const char *name) 
06046 {
06047    int dummy = 0;
06048 
06049    return get_sdp_iterate(&dummy, req, name);
06050 }
06051 
06052 /*! \brief Get a specific line from the message body */
06053 static char *get_body(struct sip_request *req, char *name) 
06054 {
06055    int x;
06056    int len = strlen(name);
06057    char *r;
06058 
06059    for (x = 0; x < req->lines; x++) {
06060       r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[x]), name, len);
06061       if (r[0] != '\0')
06062          return r;
06063    }
06064 
06065    return "";
06066 }
06067 
06068 /*! \brief Find compressed SIP alias */
06069 static const char *find_alias(const char *name, const char *_default)
06070 {
06071    /*! \brief Structure for conversion between compressed SIP and "normal" SIP */
06072    static const struct cfalias {
06073       char * const fullname;
06074       char * const shortname;
06075    } aliases[] = {
06076       { "Content-Type",  "c" },
06077       { "Content-Encoding",    "e" },
06078       { "From",       "f" },
06079       { "Call-ID",       "i" },
06080       { "Contact",       "m" },
06081       { "Content-Length",   "l" },
06082       { "Subject",       "s" },
06083       { "To",         "t" },
06084       { "Supported",     "k" },
06085       { "Refer-To",      "r" },
06086       { "Referred-By",   "b" },
06087       { "Allow-Events",  "u" },
06088       { "Event",      "o" },
06089       { "Via",     "v" },
06090       { "Accept-Contact",      "a" },
06091       { "Reject-Contact",      "j" },
06092       { "Request-Disposition", "d" },
06093       { "Session-Expires",     "x" },
06094       { "Identity",            "y" },
06095       { "Identity-Info",       "n" },
06096    };
06097    int x;
06098 
06099    for (x = 0; x < ARRAY_LEN(aliases); x++) {
06100       if (!strcasecmp(aliases[x].fullname, name))
06101          return aliases[x].shortname;
06102    }
06103 
06104    return _default;
06105 }
06106 
06107 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
06108 {
06109    int pass;
06110 
06111    /*
06112     * Technically you can place arbitrary whitespace both before and after the ':' in
06113     * a header, although RFC3261 clearly says you shouldn't before, and place just
06114     * one afterwards.  If you shouldn't do it, what absolute idiot decided it was 
06115     * a good idea to say you can do it, and if you can do it, why in the hell would.
06116     * you say you shouldn't.
06117     * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
06118     * and we always allow spaces after that for compatibility.
06119     */
06120    for (pass = 0; name && pass < 2;pass++) {
06121       int x, len = strlen(name);
06122       for (x = *start; x < req->headers; x++) {
06123          char *header = REQ_OFFSET_TO_STR(req, header[x]);
06124          if (!strncasecmp(header, name, len)) {
06125             char *r = header + len; /* skip name */
06126             if (pedanticsipchecking)
06127                r = ast_skip_blanks(r);
06128 
06129             if (*r == ':') {
06130                *start = x+1;
06131                return ast_skip_blanks(r+1);
06132             }
06133          }
06134       }
06135       if (pass == 0) /* Try aliases */
06136          name = find_alias(name, NULL);
06137    }
06138 
06139    /* Don't return NULL, so get_header is always a valid pointer */
06140    return "";
06141 }
06142 
06143 /*! \brief Get header from SIP request 
06144    \return Always return something, so don't check for NULL because it won't happen :-)
06145 */
06146 static const char *get_header(const struct sip_request *req, const char *name)
06147 {
06148    int start = 0;
06149    return __get_header(req, name, &start);
06150 }
06151 
06152 /*! \brief Read RTP from network */
06153 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
06154 {
06155    /* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
06156    struct ast_frame *f;
06157    
06158    if (!p->rtp) {
06159       /* We have no RTP allocated for this channel */
06160       return &ast_null_frame;
06161    }
06162 
06163    switch(ast->fdno) {
06164    case 0:
06165       f = ast_rtp_read(p->rtp);  /* RTP Audio */
06166       break;
06167    case 1:
06168       f = ast_rtcp_read(p->rtp); /* RTCP Control Channel */
06169       break;
06170    case 2:
06171       f = ast_rtp_read(p->vrtp); /* RTP Video */
06172       break;
06173    case 3:
06174       f = ast_rtcp_read(p->vrtp);   /* RTCP Control Channel for video */
06175       break;
06176    case 4:
06177       f = ast_rtp_read(p->trtp); /* RTP Text */
06178       if (sipdebug_text) {
06179          int i;
06180          unsigned char* arr = f->data.ptr;
06181          for (i=0; i < f->datalen; i++)
06182             ast_verbose("%c", (arr[i] > ' ' && arr[i] < '}') ? arr[i] : '.');
06183          ast_verbose(" -> ");
06184          for (i=0; i < f->datalen; i++)
06185             ast_verbose("%02X ", arr[i]);
06186          ast_verbose("\n");
06187       }
06188       break;
06189    case 5:
06190       f = ast_udptl_read(p->udptl); /* UDPTL for T.38 */
06191       break;
06192    default:
06193       f = &ast_null_frame;
06194    }
06195    /* Don't forward RFC2833 if we're not supposed to */
06196    if (f && (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) &&
06197        (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833)) {
06198       ast_debug(1, "Ignoring DTMF (%c) RTP frame because dtmfmode is not RFC2833\n", f->subclass);
06199       return &ast_null_frame;
06200    }
06201 
06202    /* We already hold the channel lock */
06203    if (!p->owner || (f && f->frametype != AST_FRAME_VOICE))
06204       return f;
06205 
06206    if (f && f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
06207       if (!(f->subclass & p->jointcapability)) {
06208          ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
06209             ast_getformatname(f->subclass), p->owner->name);
06210          return &ast_null_frame;
06211       }
06212       ast_debug(1, "Oooh, format changed to %d %s\n",
06213          f->subclass, ast_getformatname(f->subclass));
06214       p->owner->nativeformats = (p->owner->nativeformats & (AST_FORMAT_VIDEO_MASK | AST_FORMAT_TEXT_MASK)) | f->subclass;
06215       ast_set_read_format(p->owner, p->owner->readformat);
06216       ast_set_write_format(p->owner, p->owner->writeformat);
06217    }
06218 
06219    if (f && (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
06220       f = ast_dsp_process(p->owner, p->vad, f);
06221       if (f && f->frametype == AST_FRAME_DTMF) {
06222          if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && f->subclass == 'f') {
06223             ast_debug(1, "Fax CNG detected on %s\n", ast->name);
06224             *faxdetect = 1;
06225          } else {
06226             ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass);
06227          }
06228       }
06229    }
06230    
06231    return f;
06232 }
06233 
06234 /*! \brief Read SIP RTP from channel */
06235 static struct ast_frame *sip_read(struct ast_channel *ast)
06236 {
06237    struct ast_frame *fr;
06238    struct sip_pvt *p = ast->tech_pvt;
06239    int faxdetected = FALSE;
06240 
06241    sip_pvt_lock(p);
06242    fr = sip_rtp_read(ast, p, &faxdetected);
06243    p->lastrtprx = time(NULL);
06244 
06245    /* If we are NOT bridged to another channel, and we have detected fax tone we issue T38 re-invite to a peer */
06246    /* If we are bridged then it is the responsibility of the SIP device to issue T38 re-invite if it detects CNG or fax preamble */
06247    if (faxdetected && ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && (p->t38.state == T38_DISABLED) && !(ast_bridged_channel(ast))) {
06248       if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
06249          if (!p->pendinginvite) {
06250             ast_debug(3, "Sending reinvite on SIP (%s) for T.38 negotiation.\n", ast->name);
06251             change_t38_state(p, T38_LOCAL_REINVITE);
06252             transmit_reinvite_with_sdp(p, TRUE, FALSE);
06253          }
06254       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
06255          ast_debug(3, "Deferring reinvite on SIP (%s) - it will be re-negotiated for T.38\n", ast->name);
06256          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
06257       }
06258    }
06259 
06260    /* Only allow audio through if they sent progress with SDP, or if the channel is actually answered */
06261    if (fr && fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast->_state != AST_STATE_UP) {
06262       fr = &ast_null_frame;
06263    }
06264 
06265    sip_pvt_unlock(p);
06266 
06267    return fr;
06268 }
06269 
06270 
06271 /*! \brief Generate 32 byte random string for callid's etc */
06272 static char *generate_random_string(char *buf, size_t size)
06273 {
06274    long val[4];
06275    int x;
06276 
06277    for (x=0; x<4; x++)
06278       val[x] = ast_random();
06279    snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
06280 
06281    return buf;
06282 }
06283 
06284 /*! \brief Build SIP Call-ID value for a non-REGISTER transaction */
06285 static void build_callid_pvt(struct sip_pvt *pvt)
06286 {
06287    char buf[33];
06288 
06289    const char *host = S_OR(pvt->fromdomain, ast_inet_ntoa(pvt->ourip.sin_addr));
06290    
06291    ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
06292 
06293 }
06294 
06295 /*! \brief Build SIP Call-ID value for a REGISTER transaction */
06296 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain)
06297 {
06298    char buf[33];
06299 
06300    const char *host = S_OR(fromdomain, ast_inet_ntoa(ourip));
06301 
06302    ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
06303 }
06304 
06305 /*! \brief Make our SIP dialog tag */
06306 static void make_our_tag(char *tagbuf, size_t len)
06307 {
06308    snprintf(tagbuf, len, "as%08lx", ast_random());
06309 }
06310 
06311 /*! \brief Allocate Session-Timers struct w/in dialog */
06312 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
06313 {
06314    struct sip_st_dlg *stp;
06315 
06316    if (p->stimer) {
06317       ast_log(LOG_ERROR, "Session-Timer struct already allocated\n");
06318       return p->stimer;
06319    }
06320 
06321    if (!(stp = ast_calloc(1, sizeof(struct sip_st_dlg))))
06322       return NULL;
06323 
06324    p->stimer = stp;
06325 
06326    stp->st_schedid = -1;           /* Session-Timers ast_sched scheduler id */
06327 
06328    return p->stimer;
06329 }
06330 
06331 /*! \brief Allocate sip_pvt structure, set defaults and link in the container.
06332  * Returns a reference to the object so whoever uses it later must
06333  * remember to release the reference.
06334  */
06335 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
06336              int useglobal_nat, const int intended_method, struct sip_request *req)
06337 {
06338    struct sip_pvt *p;
06339 
06340    if (!(p = ao2_t_alloc(sizeof(*p), sip_destroy_fn, "allocate a dialog(pvt) struct")))
06341       return NULL;
06342 
06343    if (ast_string_field_init(p, 512)) {
06344       ao2_t_ref(p, -1, "failed to string_field_init, drop p");
06345       return NULL;
06346    }
06347 
06348    if (req) {
06349       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 */
06350    } else {
06351       set_socket_transport(&p->socket, SIP_TRANSPORT_UDP);
06352    }
06353 
06354    p->socket.fd = -1;
06355    p->method = intended_method;
06356    p->initid = -1;
06357    p->waitid = -1;
06358    p->autokillid = -1;
06359    p->request_queue_sched_id = -1;
06360    p->t38id = -1;
06361    p->subscribed = NONE;
06362    p->stateid = -1;
06363    p->sessionversion_remote = -1;
06364    p->session_modify = TRUE;
06365    p->stimer = NULL;
06366    p->prefs = default_prefs;     /* Set default codecs for this call */
06367 
06368    if (intended_method != SIP_OPTIONS) {  /* Peerpoke has it's own system */
06369       p->timer_t1 = global_t1;   /* Default SIP retransmission timer T1 (RFC 3261) */
06370       p->timer_b = global_timer_b;  /* Default SIP transaction timer B (RFC 3261) */
06371    }
06372 
06373    if (!sin)
06374       p->ourip = internip;
06375    else {
06376       p->sa = *sin;
06377       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
06378    }
06379 
06380    /* Copy global flags to this PVT at setup. */
06381    ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
06382    ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
06383 
06384    p->do_history = recordhistory;
06385 
06386    p->branch = ast_random();  
06387    make_our_tag(p->tag, sizeof(p->tag));
06388    p->ocseq = INITIAL_CSEQ;
06389 
06390    if (sip_methods[intended_method].need_rtp) {
06391       p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
06392       /* If the global videosupport flag is on, we always create a RTP interface for video */
06393       if (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT))
06394          p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
06395       if (ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT))
06396          p->trtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
06397       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT))
06398          p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr);
06399       if (!p->rtp|| (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) && !p->vrtp) 
06400             || (ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) && !p->trtp)) {
06401          ast_log(LOG_WARNING, "Unable to create RTP audio %s%ssession: %s\n",
06402             ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "and video " : "",
06403             ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "and text " : "", strerror(errno));
06404          if (p->chanvars) {
06405             ast_variables_destroy(p->chanvars);
06406             p->chanvars = NULL;
06407          }
06408          ao2_t_ref(p, -1, "failed to create RTP audio session, drop p");
06409          return NULL;
06410       }
06411       ast_rtp_setqos(p->rtp, global_tos_audio, global_cos_audio, "SIP RTP");
06412       ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
06413       ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
06414       ast_rtp_set_rtptimeout(p->rtp, global_rtptimeout);
06415       ast_rtp_set_rtpholdtimeout(p->rtp, global_rtpholdtimeout);
06416       ast_rtp_set_rtpkeepalive(p->rtp, global_rtpkeepalive);
06417       if (p->vrtp) {
06418          ast_rtp_setqos(p->vrtp, global_tos_video, global_cos_video, "SIP VRTP");
06419          ast_rtp_setdtmf(p->vrtp, 0);
06420          ast_rtp_setdtmfcompensate(p->vrtp, 0);
06421          ast_rtp_set_rtptimeout(p->vrtp, global_rtptimeout);
06422          ast_rtp_set_rtpholdtimeout(p->vrtp, global_rtpholdtimeout);
06423          ast_rtp_set_rtpkeepalive(p->vrtp, global_rtpkeepalive);
06424       }
06425       if (p->trtp) {
06426          ast_rtp_setqos(p->trtp, global_tos_text, global_cos_text, "SIP TRTP");
06427          ast_rtp_setdtmf(p->trtp, 0);
06428          ast_rtp_setdtmfcompensate(p->trtp, 0);
06429       }
06430       if (p->udptl)
06431          ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
06432       p->maxcallbitrate = default_maxcallbitrate;
06433       p->autoframing = global_autoframing;
06434       ast_rtp_codec_setpref(p->rtp, &p->prefs);
06435    }
06436 
06437    if (useglobal_nat && sin) {
06438       /* Setup NAT structure according to global settings if we have an address */
06439       ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
06440       p->recv = *sin;
06441       do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
06442    }
06443 
06444    if (p->method != SIP_REGISTER)
06445       ast_string_field_set(p, fromdomain, default_fromdomain);
06446    build_via(p);
06447    if (!callid)
06448       build_callid_pvt(p);
06449    else
06450       ast_string_field_set(p, callid, callid);
06451    /* Assign default music on hold class */
06452    ast_string_field_set(p, mohinterpret, default_mohinterpret);
06453    ast_string_field_set(p, mohsuggest, default_mohsuggest);
06454    p->capability = global_capability;
06455    p->allowtransfer = global_allowtransfer;
06456    if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
06457        (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
06458       p->noncodeccapability |= AST_RTP_DTMF;
06459    if (p->udptl) {
06460       set_t38_capabilities(p);
06461    }
06462    ast_string_field_set(p, context, default_context);
06463    ast_string_field_set(p, parkinglot, default_parkinglot);
06464 
06465    AST_LIST_HEAD_INIT_NOLOCK(&p->request_queue);
06466 
06467    /* Add to active dialog list */
06468 
06469    ao2_t_link(dialogs, p, "link pvt into dialogs table");
06470    
06471    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");
06472    return p;
06473 }
06474 
06475 /*! \brief argument to the helper function to identify a call */
06476 struct find_call_cb_arg {
06477    enum sipmethod method;
06478    const char *callid;
06479    const char *fromtag;
06480    const char *totag;
06481    const char *tag;
06482 };
06483 
06484 /*!
06485  * code to determine whether this is the pvt that we are looking for.
06486  * Return FALSE if not found, true otherwise. p is unlocked.
06487  */
06488 static int find_call_cb(void *__pvt, void *__arg, int flags)
06489 {
06490    struct sip_pvt *p = __pvt;
06491    struct find_call_cb_arg *arg = __arg;
06492    /* In pedantic, we do not want packets with bad syntax to be connected to a PVT */
06493    int found = FALSE;
06494    
06495    if (!ast_strlen_zero(p->callid)) { /* XXX double check, do we allow match on empty p->callid ? */
06496       if (arg->method == SIP_REGISTER)
06497          found = (!strcmp(p->callid, arg->callid));
06498       else {
06499          found = !strcmp(p->callid, arg->callid);
06500          if (pedanticsipchecking && found) {
06501             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);
06502          } 
06503       }
06504       
06505       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);
06506       
06507       /* If we get a new request within an existing to-tag - check the to tag as well */
06508       if (pedanticsipchecking && found && arg->method != SIP_RESPONSE) { /* SIP Request */
06509          if (p->tag[0] == '\0' && arg->totag[0]) {
06510             /* We have no to tag, but they have. Wrong dialog */
06511             found = FALSE;
06512          } else if (arg->totag[0]) { /* Both have tags, compare them */
06513             if (strcmp(arg->totag, p->tag)) {
06514                found = FALSE; /* This is not our packet */
06515             }
06516          }
06517          if (!found)
06518             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);
06519       }
06520    }
06521    return found;
06522 }
06523 
06524 /*! \brief find or create a dialog structure for an incoming SIP message.
06525  * Connect incoming SIP message to current dialog or create new dialog structure
06526  * Returns a reference to the sip_pvt object, remember to give it back once done.
06527  *     Called by handle_incoming(), sipsock_read
06528  */
06529 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
06530 {
06531    struct sip_pvt *p = NULL;
06532    char *tag = "";   /* note, tag is never NULL */
06533    char totag[128];
06534    char fromtag[128];
06535    struct find_call_cb_arg arg;
06536    const char *callid = get_header(req, "Call-ID");
06537    const char *from = get_header(req, "From");
06538    const char *to = get_header(req, "To");
06539    const char *cseq = get_header(req, "Cseq");
06540    struct sip_pvt *sip_pvt_ptr;
06541 
06542    /* Call-ID, to, from and Cseq are required by RFC 3261. (Max-forwards and via too - ignored now) */
06543    /* get_header always returns non-NULL so we must use ast_strlen_zero() */
06544    if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
06545          ast_strlen_zero(from) || ast_strlen_zero(cseq))
06546       return NULL;   /* Invalid packet */
06547 
06548    arg.method = req->method;
06549    arg.callid = callid;
06550    arg.fromtag = fromtag;
06551    arg.totag = totag;
06552    arg.tag = ""; /* make sure tag is never NULL */
06553 
06554    if (pedanticsipchecking) {
06555       /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
06556          we need more to identify a branch - so we have to check branch, from
06557          and to tags to identify a call leg.
06558          For Asterisk to behave correctly, you need to turn on pedanticsipchecking
06559          in sip.conf
06560          */
06561       if (gettag(req, "To", totag, sizeof(totag)))
06562          req->has_to_tag = 1; /* Used in handle_request/response */
06563       gettag(req, "From", fromtag, sizeof(fromtag));
06564 
06565       tag = (req->method == SIP_RESPONSE) ? totag : fromtag;
06566 
06567       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);
06568 
06569       /* All messages must always have From: tag */
06570       if (ast_strlen_zero(fromtag)) {
06571          ast_debug(5, "%s request has no from tag, dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
06572          return NULL;
06573       }
06574       /* reject requests that must always have a To: tag */
06575       if (ast_strlen_zero(totag) && (req->method == SIP_ACK || req->method == SIP_BYE || req->method == SIP_INFO )) {
06576          ast_debug(5, "%s must have a to tag. dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
06577          return NULL;
06578       }
06579    }
06580 
06581 restartsearch:
06582    if (!pedanticsipchecking) {
06583       struct sip_pvt tmp_dialog = {
06584          .callid = callid,
06585       };       
06586       sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find in dialogs");
06587       if (sip_pvt_ptr) {  /* well, if we don't find it-- what IS in there? */
06588          /* Found the call */
06589          sip_pvt_lock(sip_pvt_ptr);
06590          return sip_pvt_ptr;
06591       }
06592    } else { /* in pedantic mode! -- do the fancy linear search */
06593       ao2_lock(dialogs);
06594       p = ao2_t_callback(dialogs, 0 /* single, data */, find_call_cb, &arg, "pedantic linear search for dialog");
06595       if (p) {
06596          if (sip_pvt_trylock(p)) {
06597             ao2_unlock(dialogs);
06598             usleep(1);
06599             goto restartsearch;
06600          }
06601          ao2_unlock(dialogs);
06602          return p;
06603       }
06604       ao2_unlock(dialogs);
06605    }
06606  
06607    /* See if the method is capable of creating a dialog */
06608    if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
06609       if (intended_method == SIP_REFER) {
06610          /* We do support REFER, but not outside of a dialog yet */
06611          transmit_response_using_temp(callid, sin, 1, intended_method, req, "603 Declined (no dialog)");
06612       } else if (intended_method == SIP_NOTIFY) {
06613          /* We do not support out-of-dialog NOTIFY either,
06614             like voicemail notification, so cancel that early */
06615          transmit_response_using_temp(callid, sin, 1, intended_method, req, "489 Bad event");
06616       } else {
06617          /* Ok, time to create a new SIP dialog object, a pvt */
06618          if ((p = sip_alloc(callid, sin, 1, intended_method, req)))  {
06619             /* Ok, we've created a dialog, let's go and process it */
06620             sip_pvt_lock(p);
06621          } else {
06622             /* We have a memory or file/socket error (can't allocate RTP sockets or something) so we're not
06623                getting a dialog from sip_alloc. 
06624    
06625                Without a dialog we can't retransmit and handle ACKs and all that, but at least
06626                send an error message.
06627    
06628                Sorry, we apologize for the inconvienience
06629             */
06630             transmit_response_using_temp(callid, sin, 1, intended_method, req, "500 Server internal error");
06631             ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
06632          }
06633       }
06634       return p; /* can be NULL */
06635    } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
06636       /* A method we do not support, let's take it on the volley */
06637       transmit_response_using_temp(callid, sin, 1, intended_method, req, "501 Method Not Implemented");
06638       ast_debug(2, "Got a request with unsupported SIP method.\n");
06639    } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
06640       /* This is a request outside of a dialog that we don't know about */
06641       transmit_response_using_temp(callid, sin, 1, intended_method, req, "481 Call leg/transaction does not exist");
06642       ast_debug(2, "That's odd...  Got a request in unknown dialog. Callid %s\n", callid ? callid : "<unknown>");
06643    }
06644    /* We do not respond to responses for dialogs that we don't know about, we just drop
06645       the session quickly */
06646    if (intended_method == SIP_RESPONSE)
06647       ast_debug(2, "That's odd...  Got a response on a call we dont know about. Callid %s\n", callid ? callid : "<unknown>");
06648 
06649    return NULL;
06650 }
06651 
06652 /*! \brief Parse register=> line in sip.conf and add to registry */
06653 static int sip_register(const char *value, int lineno)
06654 {
06655    struct sip_registry *reg;
06656    int portnum = 0;
06657    enum sip_transport transport = SIP_TRANSPORT_UDP;
06658    char buf[256] = "";
06659    char *username = NULL;
06660    char *hostname=NULL, *secret=NULL, *authuser=NULL, *expire=NULL, *tmp=NULL;
06661    char *callback=NULL, *peername=NULL;
06662 
06663    if (!value)
06664       return -1;
06665    ast_copy_string(buf, value, sizeof(buf));
06666    tmp = strrchr(buf, '@');
06667 
06668    /* split [/extension][~expiry] */
06669    expire = strchr(tmp, '~');
06670    if (expire)
06671       *expire++ = '\0';
06672    callback = strrchr(tmp, '/');
06673    if (callback)
06674       *callback++ = '\0';
06675    if (ast_strlen_zero(callback))
06676       callback = "s";
06677 
06678    /* split [peername?][transport://] */
06679    tmp = strchr(buf, '?');
06680    if (tmp) {
06681       *tmp++ = '\0';
06682       peername = buf;
06683    } else {
06684       tmp = buf;
06685    }
06686    /* tmp is set at the beginning of [transport://] */
06687    sip_parse_host(tmp, lineno, &username, &portnum, &transport);
06688 
06689    /* First split around the last '@' then parse the two components. */
06690    hostname = strrchr(username, '@'); /* allow @ in the first part */
06691    if (hostname)
06692       *hostname++ = '\0';
06693    if (ast_strlen_zero(username) || ast_strlen_zero(hostname)) {
06694       ast_log(LOG_WARNING, "Format for registration is [transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] at line %d\n", lineno);
06695       return -1;
06696    }
06697    /* split user[:secret[:authuser]] */
06698    secret = strchr(username, ':');
06699    if (secret) {
06700       *secret++ = '\0';
06701       authuser = strchr(secret, ':');
06702       if (authuser)
06703          *authuser++ = '\0';
06704    }
06705 
06706    if (!(reg = ast_calloc(1, sizeof(*reg)))) {
06707       ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
06708       return -1;
06709    }
06710 
06711    if (ast_string_field_init(reg, 256)) {
06712       ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry strings\n");
06713       ast_free(reg);
06714       return -1;
06715    }
06716 
06717    ast_atomic_fetchadd_int(&regobjs, 1);
06718    ASTOBJ_INIT(reg);
06719    ast_string_field_set(reg, callback, callback);
06720    if (!ast_strlen_zero(username))
06721       ast_string_field_set(reg, username, username);
06722    if (hostname)
06723       ast_string_field_set(reg, hostname, hostname);
06724    if (authuser)
06725       ast_string_field_set(reg, authuser, authuser);
06726    if (secret)
06727       ast_string_field_set(reg, secret, secret);
06728    if (peername) {
06729       ast_string_field_set(reg, peername, peername);
06730    }
06731    reg->transport = transport;
06732    reg->expire = -1;
06733    reg->expiry = (expire ? atoi(expire) : default_expiry);
06734    reg->timeout =  -1;
06735    reg->refresh = reg->expiry;
06736    reg->portno = portnum;
06737    reg->callid_valid = FALSE;
06738    reg->ocseq = INITIAL_CSEQ;
06739    ASTOBJ_CONTAINER_LINK(&regl, reg); /* Add the new registry entry to the list */
06740    registry_unref(reg, "unref the reg pointer");   /* release the reference given by ASTOBJ_INIT. The container has another reference */
06741    return 0;
06742 }
06743 
06744 /*! \brief  Parse multiline SIP headers into one header
06745    This is enabled if pedanticsipchecking is enabled */
06746 static int lws2sws(char *msgbuf, int len) 
06747 {
06748    int h = 0, t = 0; 
06749    int lws = 0; 
06750 
06751    for (; h < len;) { 
06752       /* Eliminate all CRs */ 
06753       if (msgbuf[h] == '\r') { 
06754          h++; 
06755          continue; 
06756       } 
06757       /* Check for end-of-line */ 
06758       if (msgbuf[h] == '\n') { 
06759          /* Check for end-of-message */ 
06760          if (h + 1 == len) 
06761             break; 
06762          /* Check for a continuation line */ 
06763          if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') { 
06764             /* Merge continuation line */ 
06765             h++; 
06766             continue; 
06767          } 
06768          /* Propagate LF and start new line */ 
06769          msgbuf[t++] = msgbuf[h++]; 
06770          lws = 0;
06771          continue; 
06772       } 
06773       if (msgbuf[h] == ' ' || msgbuf[h] == '\t') { 
06774          if (lws) { 
06775             h++; 
06776             continue; 
06777          } 
06778          msgbuf[t++] = msgbuf[h++]; 
06779          lws = 1; 
06780          continue; 
06781       } 
06782       msgbuf[t++] = msgbuf[h++]; 
06783       if (lws) 
06784          lws = 0; 
06785    } 
06786    msgbuf[t] = '\0'; 
06787    return t; 
06788 }
06789 
06790 /*! \brief Parse a SIP message 
06791    \note this function is used both on incoming and outgoing packets
06792 */
06793 static int parse_request(struct sip_request *req)
06794 {
06795    char *c = req->data->str;
06796    ptrdiff_t *dst = req->header;
06797    int i = 0, lim = SIP_MAX_HEADERS - 1;
06798    unsigned int skipping_headers = 0;
06799    ptrdiff_t current_header_offset = 0;
06800    char *previous_header = "";
06801 
06802    req->header[0] = 0;
06803    req->headers = -1;   /* mark that we are working on the header */
06804    for (; *c; c++) {
06805       if (*c == '\r') {    /* remove \r */
06806          *c = '\0';
06807       } else if (*c == '\n') {   /* end of this line */
06808          *c = '\0';
06809          current_header_offset = (c + 1) - req->data->str;
06810          previous_header = req->data->str + dst[i];
06811          if (skipping_headers) {
06812             /* check to see if this line is blank; if so, turn off
06813                the skipping flag, so the next line will be processed
06814                as a body line */
06815             if (ast_strlen_zero(previous_header)) {
06816                skipping_headers = 0;
06817             }
06818             dst[i] = current_header_offset; /* record start of next line */
06819             continue;
06820          }
06821          if (sipdebug) {
06822             ast_debug(4, "%7s %2d [%3d]: %s\n",
06823                  req->headers < 0 ? "Header" : "Body",
06824                  i, (int) strlen(previous_header), previous_header);
06825          }
06826          if (ast_strlen_zero(previous_header) && req->headers < 0) {
06827             req->headers = i; /* record number of header lines */
06828             dst = req->line;  /* start working on the body */
06829             i = 0;
06830             lim = SIP_MAX_LINES - 1;
06831          } else { /* move to next line, check for overflows */
06832             if (i++ == lim) {
06833                /* if we're processing headers, then skip any remaining
06834                   headers and move on to processing the body, otherwise
06835                   we're done */
06836                if (req->headers != -1) {
06837                   break;
06838                } else {
06839                   req->headers = i;
06840                   dst = req->line;
06841                   i = 0;
06842                   lim = SIP_MAX_LINES - 1;
06843                   skipping_headers = 1;
06844                }
06845             }
06846          }
06847          dst[i] = current_header_offset; /* record start of next line */
06848       }
06849    }
06850 
06851    /* Check for last header or body line without CRLF. The RFC for SDP requires CRLF,
06852       but since some devices send without, we'll be generous in what we accept. However,
06853       if we've already reached the maximum number of lines for portion of the message
06854       we were parsing, we can't accept any more, so just ignore it.
06855    */
06856    previous_header = req->data->str + dst[i];
06857    if ((i < lim) && !ast_strlen_zero(previous_header)) {
06858       if (sipdebug) {
06859          ast_debug(4, "%7s %2d [%3d]: %s\n",
06860               req->headers < 0 ? "Header" : "Body",
06861               i, (int) strlen(previous_header), previous_header );
06862       }
06863       i++;
06864    }
06865 
06866    /* update count of header or body lines */
06867    if (req->headers >= 0) {   /* we are in the body */
06868       req->lines = i;
06869    } else {       /* no body */
06870       req->headers = i;
06871       req->lines = 0;
06872       /* req->data->used will be a NULL byte */
06873       req->line[0] = req->data->used;
06874    }
06875 
06876    if (*c) {
06877       ast_log(LOG_WARNING, "Too many lines, skipping <%s>\n", c);
06878    }
06879 
06880    /* Split up the first line parts */
06881    return determine_firstline_parts(req);
06882 }
06883 
06884 /*!
06885   \brief Determine whether a SIP message contains an SDP in its body
06886   \param req the SIP request to process
06887   \return 1 if SDP found, 0 if not found
06888 
06889   Also updates req->sdp_start and req->sdp_end to indicate where the SDP
06890   lives in the message body.
06891 */
06892 static int find_sdp(struct sip_request *req)
06893 {
06894    const char *content_type;
06895    const char *content_length;
06896    const char *search;
06897    char *boundary;
06898    unsigned int x;
06899    int boundaryisquoted = FALSE;
06900    int found_application_sdp = FALSE;
06901    int found_end_of_headers = FALSE;
06902 
06903    content_length = get_header(req, "Content-Length");
06904 
06905    if (!ast_strlen_zero(content_length)) {
06906       if (sscanf(content_length, "%30u", &x) != 1) {
06907          ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
06908          return 0;
06909       }
06910 
06911       /* Content-Length of zero means there can't possibly be an
06912          SDP here, even if the Content-Type says there is */
06913       if (x == 0)
06914          return 0;
06915    }
06916 
06917    content_type = get_header(req, "Content-Type");
06918 
06919    /* if the body contains only SDP, this is easy */
06920    if (!strncasecmp(content_type, "application/sdp", 15)) {
06921       req->sdp_start = 0;
06922       req->sdp_end = req->lines;
06923       return req->lines ? 1 : 0;
06924    }
06925 
06926    /* if it's not multipart/mixed, there cannot be an SDP */
06927    if (strncasecmp(content_type, "multipart/mixed", 15))
06928       return 0;
06929 
06930    /* if there is no boundary marker, it's invalid */
06931    if ((search = strcasestr(content_type, ";boundary=")))
06932       search += 10;
06933    else if ((search = strcasestr(content_type, "; boundary=")))
06934       search += 11;
06935    else
06936       return 0;
06937 
06938    if (ast_strlen_zero(search))
06939       return 0;
06940 
06941    /* If the boundary is quoted with ", remove quote */
06942    if (*search == '\"')  {
06943       search++;
06944       boundaryisquoted = TRUE;
06945    }
06946 
06947    /* make a duplicate of the string, with two extra characters
06948       at the beginning */
06949    boundary = ast_strdupa(search - 2);
06950    boundary[0] = boundary[1] = '-';
06951    /* Remove final quote */
06952    if (boundaryisquoted)
06953       boundary[strlen(boundary) - 1] = '\0';
06954 
06955    /* search for the boundary marker, the empty line delimiting headers from
06956       sdp part and the end boundry if it exists */
06957 
06958    for (x = 0; x < (req->lines); x++) {
06959       char *line = REQ_OFFSET_TO_STR(req, line[x]);
06960       if (!strncasecmp(line, boundary, strlen(boundary))){
06961          if (found_application_sdp && found_end_of_headers) {
06962             req->sdp_end = x-1;
06963             return 1;
06964          }
06965          found_application_sdp = FALSE;
06966       }
06967       if (!strcasecmp(line, "Content-Type: application/sdp"))
06968          found_application_sdp = TRUE;
06969       
06970       if (ast_strlen_zero(line)) {
06971          if (found_application_sdp && !found_end_of_headers){
06972             req->sdp_start = x;
06973             found_end_of_headers = TRUE;
06974          }
06975       }
06976    }
06977    if (found_application_sdp && found_end_of_headers) {
06978       req->sdp_end = x;
06979       return TRUE;
06980    }
06981    return FALSE;
06982 }
06983 
06984 enum media_type {
06985    SDP_AUDIO,
06986    SDP_VIDEO,
06987    SDP_IMAGE,
06988    SDP_TEXT,
06989 };
06990 
06991 static int get_ip_and_port_from_sdp(struct sip_request *req, const enum media_type media, struct sockaddr_in *sin)
06992 {
06993    const char *m;
06994    const char *c;
06995    int miterator = req->sdp_start;
06996    int citerator = req->sdp_start;
06997    int x = 0;
06998    int numberofports;
06999    int len;
07000    char host[258] = ""; /*Initialize to empty so we will know if we have any input */
07001    struct ast_hostent audiohp;
07002    struct hostent *hp;
07003 
07004    c = get_sdp_iterate(&citerator, req, "c");
07005    if (sscanf(c, "IN IP4 %256s", host) != 1) {
07006       ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
07007       /* Continue since there may be a valid host in a c= line specific to the audio stream */
07008    }
07009    /* We only want the m and c lines for audio */
07010    for (m = get_sdp_iterate(&miterator, req, "m"); !ast_strlen_zero(m); m = get_sdp_iterate(&miterator, req, "m")) {
07011       if ((media == SDP_AUDIO && ((sscanf(m, "audio %30d/%30d RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
07012           (sscanf(m, "audio %30d RTP/AVP %n", &x, &len) == 1 && len > 0))) ||
07013          (media == SDP_VIDEO && ((sscanf(m, "video %30d/%30d RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
07014           (sscanf(m, "video %30d RTP/AVP %n", &x, &len) == 1 && len > 0)))) {
07015          /* See if there's a c= line for this media stream.
07016           * XXX There is no guarantee that we'll be grabbing the c= line for this
07017           * particular media stream here. However, this is the same logic used in process_sdp.
07018           */
07019          c = get_sdp_iterate(&citerator, req, "c");
07020          if (!ast_strlen_zero(c)) {
07021             sscanf(c, "IN IP4 %256s", host);
07022          }
07023          break;
07024       }
07025    }
07026 
07027    if (ast_strlen_zero(host) || x == 0) {
07028       ast_log(LOG_WARNING, "Failed to read an alternate host or port in SDP. Expect %s problems\n", media == SDP_AUDIO ? "audio" : "video");
07029       return -1;
07030    }
07031 
07032    hp = ast_gethostbyname(host, &audiohp);
07033    if (!hp) {
07034       ast_log(LOG_WARNING, "Could not look up IP address of alternate hostname. Expect %s problems\n", media == SDP_AUDIO? "audio" : "video");
07035       return -1;
07036    }
07037 
07038    memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
07039    sin->sin_port = htons(x);
07040    return 0;
07041 }
07042 
07043 /*! \brief Process SIP SDP offer, select formats and activate RTP channels
07044    If offer is rejected, we will not change any properties of the call
07045    Return 0 on success, a negative value on errors.
07046    Must be called after find_sdp().
07047 */
07048 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
07049 {
07050    const char *m;    /* SDP media offer */
07051    const char *c;
07052    const char *a;
07053    const char *o;    /* Pointer to o= line */
07054    char *o_copy;     /* Copy of o= line */
07055    char *token;
07056    char host[258];
07057    int len = -1;
07058    int portno = -1;     /*!< RTP Audio port number */
07059    int vportno = -1;    /*!< RTP Video port number */
07060    int tportno = -1;    /*!< RTP Text port number */
07061    int udptlportno = -1;
07062    char s[256];
07063    int old = 0;
07064 
07065    /* Peer capability is the capability in the SDP, non codec is RFC2833 DTMF (101) */ 
07066    int peercapability = 0, peernoncodeccapability = 0;
07067    int vpeercapability = 0, vpeernoncodeccapability = 0;
07068    int tpeercapability = 0, tpeernoncodeccapability = 0;
07069    struct sockaddr_in sin;    /*!< media socket address */
07070    struct sockaddr_in vsin;   /*!< Video socket address */
07071    struct sockaddr_in tsin;   /*!< Text socket address */
07072 
07073    const char *codecs;
07074    struct hostent *hp;     /*!< RTP Audio host IP */
07075    struct hostent *vhp = NULL;   /*!< RTP video host IP */
07076    struct hostent *thp = NULL;   /*!< RTP text host IP */
07077    struct ast_hostent audiohp;
07078    struct ast_hostent videohp;
07079    struct ast_hostent texthp;
07080    int codec;
07081    int destiterator = 0;
07082    int iterator;
07083    int sendonly = -1;
07084    int numberofports;
07085    struct ast_rtp *newaudiortp, *newvideortp, *newtextrtp;  /* Buffers for codec handling */
07086    int newjointcapability;          /* Negotiated capability */
07087    int newpeercapability;
07088    int newnoncodeccapability;
07089    int numberofmediastreams = 0;
07090    int debug = sip_debug_test_pvt(p);
07091       
07092    int found_rtpmap_codecs[SDP_MAX_RTPMAP_CODECS];
07093    int last_rtpmap_codec=0;
07094 
07095    char buf[SIPBUFSIZE];
07096    int64_t rua_version;
07097    
07098    int red_data_pt[10];
07099    int red_num_gen = 0;
07100    int red_pt = 0;
07101 
07102    char *red_cp;           /* For T.140 red */
07103    char red_fmtp[100] = "empty";    /* For T.140 red */
07104 
07105    if (!p->rtp) {
07106       ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
07107       return -1;
07108    }
07109 
07110    /* Initialize the temporary RTP structures we use to evaluate the offer from the peer */
07111 #ifdef LOW_MEMORY
07112    newaudiortp = ast_threadstorage_get(&ts_audio_rtp, ast_rtp_alloc_size());
07113 #else
07114    newaudiortp = alloca(ast_rtp_alloc_size());
07115 #endif
07116    memset(newaudiortp, 0, ast_rtp_alloc_size());
07117    ast_rtp_new_init(newaudiortp);
07118    ast_rtp_pt_clear(newaudiortp);
07119 
07120 #ifdef LOW_MEMORY
07121    newvideortp = ast_threadstorage_get(&ts_video_rtp, ast_rtp_alloc_size());
07122 #else
07123    newvideortp = alloca(ast_rtp_alloc_size());
07124 #endif
07125    memset(newvideortp, 0, ast_rtp_alloc_size());
07126    ast_rtp_new_init(newvideortp);
07127    ast_rtp_pt_clear(newvideortp);
07128 
07129 #ifdef LOW_MEMORY
07130    newtextrtp = ast_threadstorage_get(&ts_text_rtp, ast_rtp_alloc_size());
07131 #else
07132    newtextrtp = alloca(ast_rtp_alloc_size());
07133 #endif
07134    memset(newtextrtp, 0, ast_rtp_alloc_size());
07135    ast_rtp_new_init(newtextrtp);
07136    ast_rtp_pt_clear(newtextrtp);
07137 
07138    /* Update our last rtprx when we receive an SDP, too */
07139    p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
07140 
07141    memset(p->offered_media, 0, sizeof(p->offered_media));
07142 
07143    /* Store the SDP version number of remote UA. This will allow us to 
07144    distinguish between session modifications and session refreshes. If 
07145    the remote UA does not send an incremented SDP version number in a 
07146    subsequent RE-INVITE then that means its not changing media session. 
07147    The RE-INVITE may have been sent to update connected party, remote  
07148    target or to refresh the session (Session-Timers).  Asterisk must not 
07149    change media session and increment its own version number in answer 
07150    SDP in this case. */ 
07151    
07152    o = get_sdp(req, "o");
07153    if (ast_strlen_zero(o)) {
07154       ast_log(LOG_WARNING, "SDP sytax error. SDP without an o= line\n");
07155       return -1;
07156    }
07157 
07158    o_copy = ast_strdupa(o);
07159    token = strsep(&o_copy, " ");  /* Skip username   */
07160    if (!o_copy) { 
07161       ast_log(LOG_WARNING, "SDP sytax error in o= line username\n");
07162       return -1;
07163    }
07164    token = strsep(&o_copy, " ");  /* Skip session-id */
07165    if (!o_copy) { 
07166       ast_log(LOG_WARNING, "SDP sytax error in o= line session-id\n");
07167       return -1;
07168    }
07169    token = strsep(&o_copy, " ");  /* Version         */
07170    if (!o_copy) { 
07171       ast_log(LOG_WARNING, "SDP sytax error in o= line\n");
07172       return -1;
07173    }
07174    if (!sscanf(token, "%30" SCNd64, &rua_version)) {
07175       ast_log(LOG_WARNING, "SDP sytax error in o= line version\n");
07176       return -1;
07177    }
07178 
07179    /* we need to check the SDP version number the other end sent us;
07180     * our rules for deciding what to accept are a bit complex.
07181     *
07182     * 1) if 'ignoresdpversion' has been set for this dialog, then
07183     *    we will just accept whatever they sent and assume it is
07184     *    a modification of the session, even if it is not
07185     * 2) otherwise, if this is the first SDP we've seen from them
07186     *    we accept it
07187     * 3) otherwise, if the new SDP version number is higher than the
07188     *    old one, we accept it
07189     * 4) otherwise, if this SDP is in response to us requesting a switch
07190     *    to T.38, we accept the SDP, but also generate a warning message
07191     *    that this peer should have the 'ignoresdpversion' option set,
07192     *    because it is not following the SDP offer/answer RFC; if we did
07193     *    not request a switch to T.38, then we stop parsing the SDP, as it
07194     *    has not changed from the previous version
07195     */
07196 
07197    if (ast_test_flag(&p->flags[1], SIP_PAGE2_IGNORESDPVERSION) ||
07198        (p->sessionversion_remote < 0) ||
07199        (p->sessionversion_remote < rua_version)) {
07200       p->sessionversion_remote = rua_version;
07201       p->session_modify = TRUE;
07202    } else {
07203       if (p->t38.state == T38_LOCAL_REINVITE) {
07204          p->sessionversion_remote = rua_version;
07205          p->session_modify = TRUE;
07206          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);
07207       } else {
07208          p->session_modify = FALSE;
07209          ast_debug(2, "Call %s responded to our reinvite without changing SDP version; ignoring SDP.\n", p->callid);
07210          return 0;
07211       }
07212    } 
07213 
07214    /* Try to find first media stream */
07215    m = get_sdp(req, "m");
07216    destiterator = req->sdp_start;
07217    c = get_sdp_iterate(&destiterator, req, "c");
07218    if (ast_strlen_zero(m) || ast_strlen_zero(c)) {
07219       ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
07220       return -1;
07221    }
07222 
07223    /* Check for IPv4 address (not IPv6 yet) */
07224    if (sscanf(c, "IN IP4 %256s", host) != 1) {
07225       ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
07226       return -1;
07227    }
07228 
07229    /* XXX This could block for a long time, and block the main thread! XXX */
07230    hp = ast_gethostbyname(host, &audiohp);
07231    if (!hp) {
07232       ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
07233       return -1;
07234    }
07235    vhp = hp;   /* Copy to video address as default too */
07236    thp = hp;   /* Copy to text address as default too */
07237    
07238    iterator = req->sdp_start;
07239    /* default: novideo and notext set */
07240    p->novideo = TRUE;
07241    p->notext = TRUE;
07242 
07243    if (p->vrtp)
07244       ast_rtp_pt_clear(newvideortp);  /* Must be cleared in case no m=video line exists */
07245  
07246    if (p->trtp)
07247       ast_rtp_pt_clear(newtextrtp);  /* Must be cleared in case no m=text line exists */
07248 
07249    /* Find media streams in this SDP offer */
07250    while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
07251       int x;
07252       int audio = FALSE;
07253       int video = FALSE;
07254       int text = FALSE;
07255 
07256       numberofports = 1;
07257       len = -1;
07258       if ((sscanf(m, "audio %30d/%30d RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
07259           (sscanf(m, "audio %30d RTP/AVP %n", &x, &len) == 1 && len > 0)) {
07260          audio = TRUE;
07261          p->offered_media[SDP_AUDIO].offered = TRUE;
07262          numberofmediastreams++;
07263          /* Found audio stream in this media definition */
07264          portno = x;
07265          /* Scan through the RTP payload types specified in a "m=" line: */
07266          codecs = m + len;
07267          ast_copy_string(p->offered_media[SDP_AUDIO].text, codecs, sizeof(p->offered_media[SDP_AUDIO].text));
07268          for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
07269             if (sscanf(codecs, "%30d%n", &codec, &len) != 1) {
07270                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
07271                return -1;
07272             }
07273             if (debug)
07274                ast_verbose("Found RTP audio format %d\n", codec);
07275             ast_rtp_set_m_type(newaudiortp, codec);
07276          }
07277       } else if ((sscanf(m, "video %30d/%30d RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
07278           (sscanf(m, "video %30d RTP/AVP %n", &x, &len) == 1 && len >= 0)) {
07279          video = TRUE;
07280          p->novideo = FALSE;
07281          p->offered_media[SDP_VIDEO].offered = TRUE;
07282          numberofmediastreams++;
07283          vportno = x;
07284          /* Scan through the RTP payload types specified in a "m=" line: */
07285          codecs = m + len;
07286          ast_copy_string(p->offered_media[SDP_VIDEO].text, codecs, sizeof(p->offered_media[SDP_VIDEO].text));
07287          for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
07288             if (sscanf(codecs, "%30d%n", &codec, &len) != 1) {
07289                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
07290                return -1;
07291             }
07292             if (debug)
07293                ast_verbose("Found RTP video format %d\n", codec);
07294             ast_rtp_set_m_type(newvideortp, codec);
07295          }
07296       } else if ((sscanf(m, "text %30d/%30d RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
07297           (sscanf(m, "text %30d RTP/AVP %n", &x, &len) == 1 && len > 0)) {
07298          text = TRUE;
07299          p->offered_media[SDP_TEXT].offered = TRUE;
07300          p->notext = FALSE;
07301          numberofmediastreams++;
07302          tportno = x;
07303          /* Scan through the RTP payload types specified in a "m=" line: */
07304          codecs = m + len;
07305          ast_copy_string(p->offered_media[SDP_TEXT].text, codecs, sizeof(p->offered_media[SDP_TEXT].text));
07306          for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
07307             if (sscanf(codecs, "%30d%n", &codec, &len) != 1) {
07308                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
07309                return -1;
07310             }
07311             if (debug)
07312                ast_verbose("Found RTP text format %d\n", codec);
07313             ast_rtp_set_m_type(newtextrtp, codec);
07314          }
07315       } else if (p->udptl && ( (sscanf(m, "image %30d udptl t38%n", &x, &len) == 1 && len > 0) || 
07316          (sscanf(m, "image %30d UDPTL t38%n", &x, &len) == 1 && len > 0) )) {
07317          if (debug)
07318             ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
07319          p->offered_media[SDP_IMAGE].offered = TRUE;
07320          udptlportno = x;
07321          numberofmediastreams++;
07322       } else 
07323          ast_log(LOG_WARNING, "Unsupported SDP media type in offer: %s\n", m);
07324       if (numberofports > 1)
07325          ast_log(LOG_WARNING, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports);
07326       
07327 
07328       /* Check for Media-description-level-address for audio */
07329       c = get_sdp_iterate(&destiterator, req, "c");
07330       if (!ast_strlen_zero(c)) {
07331          if (sscanf(c, "IN IP4 %256s", host) != 1) {
07332             ast_log(LOG_WARNING, "Invalid secondary host in c= line, '%s'\n", c);
07333          } else {
07334             /* XXX This could block for a long time, and block the main thread! XXX */
07335             if (audio) {
07336                if ( !(hp = ast_gethostbyname(host, &audiohp))) {
07337                   ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in secondary c= line, '%s'\n", c);
07338                   return -2;
07339                }
07340             } else if (video) {
07341                if (!(vhp = ast_gethostbyname(host, &videohp))) {
07342                   ast_log(LOG_WARNING, "Unable to lookup RTP video host in secondary c= line, '%s'\n", c);
07343                   return -2;
07344                }
07345             } else if (text) {
07346                if (!(thp = ast_gethostbyname(host, &texthp))) {
07347                   ast_log(LOG_WARNING, "Unable to lookup RTP text host in secondary c= line, '%s'\n", c);
07348                   return -2;
07349                }
07350             }
07351          }
07352 
07353       }
07354    }
07355    if (portno == -1 && vportno == -1 && udptlportno == -1  && tportno == -1)
07356       /* No acceptable offer found in SDP  - we have no ports */
07357       /* Do not change RTP or VRTP if this is a re-invite */
07358       return -2;
07359 
07360    if (numberofmediastreams > 3)
07361       /* We have too many fax, audio and/or video and/or text media streams, fail this offer */
07362       return -3;
07363 
07364    /* RTP addresses and ports for audio and video */
07365    sin.sin_family = AF_INET;
07366    vsin.sin_family = AF_INET;
07367    tsin.sin_family = AF_INET;
07368    memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
07369    if (vhp)
07370       memcpy(&vsin.sin_addr, vhp->h_addr, sizeof(vsin.sin_addr));
07371    if (thp)
07372       memcpy(&tsin.sin_addr, thp->h_addr, sizeof(tsin.sin_addr));
07373 
07374    /* Setup UDPTL port number */
07375    if (p->udptl) {
07376       if (udptlportno > 0) {
07377          sin.sin_port = htons(udptlportno);
07378          if (ast_test_flag(&p->flags[0], SIP_NAT) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
07379             struct sockaddr_in peer;
07380             ast_rtp_get_peer(p->rtp, &peer);
07381             if (peer.sin_addr.s_addr) {
07382                memcpy(&sin.sin_addr, &peer.sin_addr, sizeof(sin.sin_addr));
07383                if (debug) {
07384                   ast_log(LOG_DEBUG, "Peer T.38 UDPTL is set behind NAT and with destination, destination address now %s\n", ast_inet_ntoa(sin.sin_addr));
07385                }
07386             }
07387          }
07388          ast_udptl_set_peer(p->udptl, &sin);
07389          if (debug)
07390             ast_debug(1, "Peer T.38 UDPTL is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
07391       } else {
07392          ast_udptl_stop(p->udptl);
07393          if (debug)
07394             ast_debug(1, "Peer doesn't provide T.38 UDPTL\n");
07395       }
07396    }
07397 
07398       
07399    if (p->rtp) {
07400       if (portno > 0) {
07401          sin.sin_port = htons(portno);
07402          ast_rtp_set_peer(p->rtp, &sin);
07403          if (debug)
07404             ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
07405       } else {
07406          if (udptlportno > 0) {
07407             if (debug)
07408                ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session. Callid %s\n", p->callid);
07409          } else {
07410             ast_rtp_stop(p->rtp);
07411             if (debug)
07412                ast_verbose("Peer doesn't provide audio. Callid %s\n", p->callid);
07413          }
07414       }
07415    }
07416    /* Setup video port number, assumes we have audio */
07417    if (vportno != -1)
07418       vsin.sin_port = htons(vportno);
07419 
07420    /* Setup text port number, assumes we have audio */
07421    if (tportno != -1)
07422       tsin.sin_port = htons(tportno);
07423 
07424    /* Next, scan through each "a=xxxx:" line, noting each
07425     * specified RTP payload type (with corresponding MIME subtype):
07426     */
07427    /* XXX This needs to be done per media stream, since it's media stream specific */
07428    iterator = req->sdp_start;
07429    while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
07430       char mimeSubtype[128];
07431       if (option_debug > 1) {
07432          int breakout = FALSE;
07433       
07434          /* If we're debugging, check for unsupported sdp options */
07435          if (!strncasecmp(a, "rtcp:", (size_t) 5)) {
07436             if (debug)
07437                ast_verbose("Got unsupported a:rtcp in SDP offer \n");
07438             breakout = TRUE;
07439          } else if (!strncasecmp(a, "fmtp:", (size_t) 5)) {
07440             /* Format parameters:  Not supported */
07441             /* Note: This is used for codec parameters, like bitrate for
07442                G722 and video formats for H263 and H264 
07443                See RFC2327 for an example */
07444             if (debug)
07445                ast_verbose("Got unsupported a:fmtp in SDP offer \n");
07446             breakout = TRUE;
07447          } else if (!strncasecmp(a, "framerate:", (size_t) 10)) {
07448             /* Video stuff:  Not supported */
07449             if (debug)
07450                ast_verbose("Got unsupported a:framerate in SDP offer \n");
07451             breakout = TRUE;
07452          } else if (!strncasecmp(a, "maxprate:", (size_t) 9)) {
07453             /* Video stuff:  Not supported */
07454             if (debug)
07455                ast_verbose("Got unsupported a:maxprate in SDP offer \n");
07456             breakout = TRUE;
07457          } else if (!strncasecmp(a, "crypto:", (size_t) 7)) {
07458             /* SRTP stuff, not yet supported */
07459             if (debug)
07460                ast_verbose("Got unsupported a:crypto in SDP offer \n");
07461             breakout = TRUE;
07462          }
07463          if (breakout)  /* We have a match, skip to next header */
07464             continue;
07465       }
07466       if (!strcasecmp(a, "sendonly")) {
07467          if (sendonly == -1)
07468             sendonly = 1;
07469          continue;
07470       } else if (!strcasecmp(a, "inactive")) {
07471          if (sendonly == -1)
07472             sendonly = 2;
07473          continue;
07474       }  else if (!strcasecmp(a, "sendrecv")) {
07475          if (sendonly == -1)
07476             sendonly = 0;
07477          continue;
07478       } else if (strlen(a) > 5 && !strncasecmp(a, "ptime", 5)) {
07479          char *tmp = strrchr(a, ':');
07480          long int framing = 0;
07481          if (tmp) {
07482             tmp++;
07483             framing = strtol(tmp, NULL, 10);
07484             if (framing == LONG_MIN || framing == LONG_MAX) {
07485                framing = 0;
07486                ast_debug(1, "Can't read framing from SDP: %s\n", a);
07487             }
07488          }
07489          if (framing && p->autoframing) {
07490             struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
07491             int codec_n;
07492             int format = 0;
07493             for (codec_n = 0; codec_n < MAX_RTP_PT; codec_n++) {
07494                format = ast_rtp_codec_getformat(codec_n);
07495                if (!format)   /* non-codec or not found */
07496                   continue;
07497                if (option_debug)
07498                   ast_log(LOG_DEBUG, "Setting framing for %d to %ld\n", format, framing);
07499                ast_codec_pref_setsize(pref, format, framing);
07500             }
07501             ast_rtp_codec_setpref(p->rtp, pref);
07502          }
07503          continue;
07504 
07505       } else if (!strncmp(a, red_fmtp, strlen(red_fmtp))) {
07506          /* count numbers of generations in fmtp */
07507          red_cp = &red_fmtp[strlen(red_fmtp)];
07508          strncpy(red_fmtp, a, 100);
07509 
07510          sscanf(red_cp, "%30u", &red_data_pt[red_num_gen]);
07511          red_cp = strtok(red_cp, "/");
07512          while (red_cp && red_num_gen++ < RED_MAX_GENERATION) {
07513             sscanf(red_cp, "%30u", &red_data_pt[red_num_gen]);
07514             red_cp = strtok(NULL, "/");
07515          }
07516          red_cp = red_fmtp;
07517 
07518       } else if (sscanf(a, "rtpmap: %30u %127[^/]/", &codec, mimeSubtype) == 2) {
07519          /* We have a rtpmap to handle */
07520 
07521          if (last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
07522             /* Note: should really look at the 'freq' and '#chans' params too */
07523             /* Note: This should all be done in the context of the m= above */
07524             if (!strncasecmp(mimeSubtype, "H26", 3) || !strncasecmp(mimeSubtype, "MP4", 3)) {         /* Video */
07525                if(ast_rtp_set_rtpmap_type(newvideortp, codec, "video", mimeSubtype, 0) != -1) {
07526                   if (debug)
07527                      ast_verbose("Found video description format %s for ID %d\n", mimeSubtype, codec);
07528                   found_rtpmap_codecs[last_rtpmap_codec] = codec;
07529                   last_rtpmap_codec++;
07530                } else {
07531                   ast_rtp_unset_m_type(newvideortp, codec);
07532                   if (debug) 
07533                      ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
07534                }
07535             } else if (!strncasecmp(mimeSubtype, "T140", 4)) { /* Text */
07536                if (p->trtp) {
07537                   /* ast_verbose("Adding t140 mimeSubtype to textrtp struct\n"); */
07538                   ast_rtp_set_rtpmap_type(newtextrtp, codec, "text", mimeSubtype, 0);
07539                }
07540             } else if (!strncasecmp(mimeSubtype, "RED", 3)) { /* Text with Redudancy */
07541                if (p->trtp) {
07542                   ast_rtp_set_rtpmap_type(newtextrtp, codec, "text", mimeSubtype, 0);
07543                   red_pt = codec;
07544                   sprintf(red_fmtp, "fmtp:%d ", red_pt); 
07545 
07546                   if (debug)
07547                      ast_verbose("Red submimetype has payload type: %d\n", red_pt);
07548                }
07549             } else {                                          /* Must be audio?? */
07550                if(ast_rtp_set_rtpmap_type(newaudiortp, codec, "audio", mimeSubtype,
07551                            ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0) != -1) {
07552                   if (debug)
07553                      ast_verbose("Found audio description format %s for ID %d\n", mimeSubtype, codec);
07554                   found_rtpmap_codecs[last_rtpmap_codec] = codec;
07555                   last_rtpmap_codec++;
07556                } else {
07557                   ast_rtp_unset_m_type(newaudiortp, codec);
07558                   if (debug) 
07559                      ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
07560                }
07561             }
07562          } else {
07563             if (debug)
07564                ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
07565          }
07566 
07567       }
07568    }
07569    
07570    if (udptlportno != -1) {
07571       if (p->t38.state != T38_ENABLED) {
07572          int found = 0, x;
07573       
07574          old = 0;
07575          memset(&p->t38.their_parms, 0, sizeof(p->t38.their_parms));
07576       
07577          /* Scan trough the a= lines for T38 attributes and set apropriate fileds */
07578          iterator = req->sdp_start;
07579          while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
07580             if ((sscanf(a, "T38FaxMaxBuffer:%30d", &x) == 1)) {
07581                found = 1;
07582                ast_debug(3, "MaxBufferSize:%d\n", x);
07583             } else if ((sscanf(a, "T38MaxBitRate:%30d", &x) == 1) || (sscanf(a, "T38FaxMaxRate:%30d", &x) == 1)) {
07584                found = 1;
07585                ast_debug(3, "T38MaxBitRate: %d\n", x);
07586                switch (x) {
07587                case 14400:
07588                   p->t38.their_parms.rate = AST_T38_RATE_14400;
07589                   break;
07590                case 12000:
07591                   p->t38.their_parms.rate = AST_T38_RATE_12000;
07592                   break;
07593                case 9600:
07594                   p->t38.their_parms.rate = AST_T38_RATE_9600;
07595                   break;
07596                case 7200:
07597                   p->t38.their_parms.rate = AST_T38_RATE_7200;
07598                   break;
07599                case 4800:
07600                   p->t38.their_parms.rate = AST_T38_RATE_4800;
07601                   break;
07602                case 2400:
07603                   p->t38.their_parms.rate = AST_T38_RATE_2400;
07604                   break;
07605                }
07606             } else if ((sscanf(a, "T38FaxVersion:%30d", &x) == 1)) {
07607                found = 1;
07608                ast_debug(3, "FaxVersion: %d\n", x);
07609                p->t38.their_parms.version = x;
07610             } else if ((sscanf(a, "T38FaxMaxDatagram:%30d", &x) == 1) || (sscanf(a, "T38MaxDatagram:%30d", &x) == 1)) {
07611                found = 1;
07612                ast_debug(3, "FaxMaxDatagram: %d\n", x);
07613                ast_udptl_set_far_max_datagram(p->udptl, x);
07614             } else if ((strncmp(a, "T38FaxFillBitRemoval", 20) == 0)) {
07615                found = 1;
07616                if (sscanf(a, "T38FaxFillBitRemoval:%30d", &x) == 1) {
07617                   ast_debug(3, "FillBitRemoval: %d\n", x);
07618                   if (x == 1) {
07619                      p->t38.their_parms.fill_bit_removal = TRUE;
07620                   }
07621                } else {
07622                   ast_debug(3, "FillBitRemoval\n");
07623                   p->t38.their_parms.fill_bit_removal = TRUE;
07624                }
07625             } else if ((strncmp(a, "T38FaxTranscodingMMR", 20) == 0)) {
07626                found = 1;
07627                if (sscanf(a, "T38FaxTranscodingMMR:%30d", &x) == 1) {
07628                   ast_debug(3, "Transcoding MMR: %d\n", x);
07629                   if (x == 1) {
07630                      p->t38.their_parms.transcoding_mmr = TRUE;
07631                   }
07632                } else {
07633                   ast_debug(3, "Transcoding MMR\n");
07634                   p->t38.their_parms.transcoding_mmr = TRUE;
07635                }
07636             } else if ((strncmp(a, "T38FaxTranscodingJBIG", 21) == 0)) {
07637                found = 1;
07638                if (sscanf(a, "T38FaxTranscodingJBIG:%30d", &x) == 1) {
07639                   ast_debug(3, "Transcoding JBIG: %d\n", x);
07640                   if (x == 1) {
07641                      p->t38.their_parms.transcoding_jbig = TRUE;
07642                   }
07643                } else {
07644                   ast_debug(3, "Transcoding JBIG\n");
07645                   p->t38.their_parms.transcoding_jbig = TRUE;
07646                }
07647             } else if ((sscanf(a, "T38FaxRateManagement:%255s", s) == 1)) {
07648                found = 1;
07649                ast_debug(3, "RateManagement: %s\n", s);
07650                if (!strcasecmp(s, "localTCF"))
07651                   p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_LOCAL_TCF;
07652                else if (!strcasecmp(s, "transferredTCF"))
07653                   p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF;
07654             } else if ((sscanf(a, "T38FaxUdpEC:%255s", s) == 1)) {
07655                found = 1;
07656                ast_debug(3, "UDP EC: %s\n", s);
07657                if (!strcasecmp(s, "t38UDPRedundancy")) {
07658                   ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
07659                } else if (!strcasecmp(s, "t38UDPFEC")) {
07660                   ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
07661                } else {
07662                   ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
07663                }
07664             }
07665          }
07666 
07667          /* Remote party offers T38, we need to update state */
07668          if ((t38action == SDP_T38_ACCEPT) &&
07669              (p->t38.state == T38_LOCAL_REINVITE)) {
07670             change_t38_state(p, T38_ENABLED);
07671          } else if ((t38action == SDP_T38_INITIATE) &&
07672                p->owner && p->lastinvite) {
07673             change_t38_state(p, T38_PEER_REINVITE); /* T38 Offered in re-invite from remote party */
07674          }
07675       }
07676    } else {
07677       change_t38_state(p, T38_DISABLED);
07678    }
07679 
07680    /* Now gather all of the codecs that we are asked for: */
07681    ast_rtp_get_current_formats(newaudiortp, &peercapability, &peernoncodeccapability);
07682    ast_rtp_get_current_formats(newvideortp, &vpeercapability, &vpeernoncodeccapability);
07683    ast_rtp_get_current_formats(newtextrtp, &tpeercapability, &tpeernoncodeccapability);
07684  
07685    newjointcapability = p->capability & (peercapability | vpeercapability | tpeercapability);
07686    newpeercapability = (peercapability | vpeercapability | tpeercapability);
07687    newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
07688       
07689       
07690    if (debug) {
07691       /* shame on whoever coded this.... */
07692       char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE], s5[SIPBUFSIZE];
07693 
07694       ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s/text=%s, combined - %s\n",
07695              ast_getformatname_multiple(s1, SIPBUFSIZE, p->capability),
07696              ast_getformatname_multiple(s2, SIPBUFSIZE, peercapability),
07697              ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
07698              ast_getformatname_multiple(s4, SIPBUFSIZE, tpeercapability),
07699              ast_getformatname_multiple(s5, SIPBUFSIZE, newjointcapability));
07700 
07701       ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
07702              ast_rtp_lookup_mime_multiple(s1, SIPBUFSIZE, p->noncodeccapability, 0, 0),
07703              ast_rtp_lookup_mime_multiple(s2, SIPBUFSIZE, peernoncodeccapability, 0, 0),
07704              ast_rtp_lookup_mime_multiple(s3, SIPBUFSIZE, newnoncodeccapability, 0, 0));
07705    }
07706    if (!newjointcapability) {
07707       /* If T.38 was not negotiated either, totally bail out... */
07708       if ((p->t38.state == T38_DISABLED) || !udptlportno) {
07709          ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
07710          /* Do NOT Change current setting */
07711          return -1;
07712       } else {
07713          ast_debug(3, "Have T.38 but no audio codecs, accepting offer anyway\n");
07714          return 0;
07715       }
07716    }
07717 
07718    /* We are now ready to change the sip session and p->rtp and p->vrtp with the offered codecs, since
07719       they are acceptable */
07720    p->jointcapability = newjointcapability;          /* Our joint codec profile for this call */
07721    p->peercapability = newpeercapability;            /* The other sides capability in latest offer */
07722    p->jointnoncodeccapability = newnoncodeccapability;   /* DTMF capabilities */
07723 
07724    if (p->trtp && (p->jointcapability & AST_FORMAT_T140RED)) {
07725       p->red = 1; 
07726       rtp_red_init(p->trtp, 300, red_data_pt, 2);
07727    } else {
07728       p->red = 0; 
07729    }
07730 
07731    ast_rtp_pt_copy(p->rtp, newaudiortp);
07732    if (p->vrtp)
07733       ast_rtp_pt_copy(p->vrtp, newvideortp);
07734    if (p->trtp)
07735       ast_rtp_pt_copy(p->trtp, newtextrtp);
07736 
07737    if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
07738       ast_clear_flag(&p->flags[0], SIP_DTMF);
07739       if (newnoncodeccapability & AST_RTP_DTMF) {
07740          /* XXX Would it be reasonable to drop the DSP at this point? XXX */
07741          ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
07742          /* Since RFC2833 is now negotiated we need to change some properties of the RTP stream */
07743          ast_rtp_setdtmf(p->rtp, 1);
07744          ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
07745       } else {
07746          ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
07747       }
07748    }
07749 
07750    /* Setup audio port number */
07751    if (p->rtp && sin.sin_port) {
07752       ast_rtp_set_peer(p->rtp, &sin);
07753       if (debug)
07754          ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
07755    }
07756 
07757    /* Setup video port number */
07758    if (p->vrtp && vsin.sin_port) {
07759       ast_rtp_set_peer(p->vrtp, &vsin);
07760       if (debug) 
07761          ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(vsin.sin_addr), ntohs(vsin.sin_port));
07762    }
07763 
07764    /* Setup text port number */
07765    if (p->trtp && tsin.sin_port) {
07766       ast_rtp_set_peer(p->trtp, &tsin);
07767       if (debug) 
07768          ast_verbose("Peer text RTP is at port %s:%d\n", ast_inet_ntoa(tsin.sin_addr), ntohs(tsin.sin_port));
07769    }
07770 
07771    /* Ok, we're going with this offer */
07772    ast_debug(2, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcapability));
07773 
07774    if (!p->owner)    /* There's no open channel owning us so we can return here. For a re-invite or so, we proceed */
07775       return 0;
07776 
07777    ast_debug(4, "We have an owner, now see if we need to change this call\n");
07778 
07779    if (!(p->owner->nativeformats & p->jointcapability) && (p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
07780       if (debug) {
07781          char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
07782          ast_debug(1, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n", 
07783             ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcapability),
07784             ast_getformatname_multiple(s2, SIPBUFSIZE, p->owner->nativeformats));
07785       }
07786       p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability) | (p->capability & tpeercapability);
07787       ast_set_read_format(p->owner, p->owner->readformat);
07788       ast_set_write_format(p->owner, p->owner->writeformat);
07789    }
07790    
07791    if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) && sin.sin_addr.s_addr && (!sendonly || sendonly == -1)) {
07792       ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
07793       /* Activate a re-invite */
07794       ast_queue_frame(p->owner, &ast_null_frame);
07795       /* Queue Manager Unhold event */
07796       append_history(p, "Unhold", "%s", req->data->str);
07797       if (global_callevents)
07798          manager_event(EVENT_FLAG_CALL, "Hold",
07799                   "Status: Off\r\n"
07800                   "Channel: %s\r\n"
07801                   "Uniqueid: %s\r\n",
07802                   p->owner->name,
07803                   p->owner->uniqueid);
07804       if (global_notifyhold)
07805          sip_peer_hold(p, FALSE);
07806       ast_clear_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD); /* Clear both flags */
07807    } else if (!sin.sin_addr.s_addr || (sendonly && sendonly != -1)) {
07808       int already_on_hold = ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD);
07809       ast_queue_control_data(p->owner, AST_CONTROL_HOLD, 
07810                    S_OR(p->mohsuggest, NULL),
07811                    !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
07812       if (sendonly)
07813          ast_rtp_stop(p->rtp);
07814       /* RTCP needs to go ahead, even if we're on hold!!! */
07815       /* Activate a re-invite */
07816       ast_queue_frame(p->owner, &ast_null_frame);
07817       /* Queue Manager Hold event */
07818       append_history(p, "Hold", "%s", req->data->str);
07819       if (global_callevents && !ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
07820          manager_event(EVENT_FLAG_CALL, "Hold",
07821                   "Status: On\r\n"
07822                   "Channel: %s\r\n"
07823                   "Uniqueid: %s\r\n",
07824                   p->owner->name, 
07825                   p->owner->uniqueid);
07826       }
07827       if (sendonly == 1)   /* One directional hold (sendonly/recvonly) */
07828          ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
07829       else if (sendonly == 2) /* Inactive stream */
07830          ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
07831       else
07832          ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
07833       if (global_notifyhold && !already_on_hold)
07834          sip_peer_hold(p, TRUE);
07835    }
07836    
07837    return 0;
07838 }
07839 
07840 #ifdef LOW_MEMORY
07841 static void ts_ast_rtp_destroy(void *data)
07842 {
07843     struct ast_rtp *tmp = data;
07844     ast_rtp_destroy(tmp);
07845 }
07846 #endif
07847 
07848 /*! \brief Add header to SIP message */
07849 static int add_header(struct sip_request *req, const char *var, const char *value)
07850 {
07851    if (req->headers == SIP_MAX_HEADERS) {
07852       ast_log(LOG_WARNING, "Out of SIP header space\n");
07853       return -1;
07854    }
07855 
07856    if (req->lines) {
07857       ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
07858       return -1;
07859    }
07860 
07861    if (compactheaders)
07862       var = find_alias(var, var);
07863 
07864    ast_str_append(&req->data, 0, "%s: %s\r\n", var, value);
07865    req->header[req->headers] = req->len;
07866 
07867    req->len = req->data->used;
07868    req->headers++;
07869 
07870    return 0;   
07871 }
07872 
07873 /*! \brief Add 'Content-Length' header to SIP message */
07874 static int add_header_contentLength(struct sip_request *req, int len)
07875 {
07876    char clen[10];
07877 
07878    snprintf(clen, sizeof(clen), "%d", len);
07879    return add_header(req, "Content-Length", clen);
07880 }
07881 
07882 /*! \brief Add content (not header) to SIP message */
07883 static int add_line(struct sip_request *req, const char *line)
07884 {
07885    if (req->lines == SIP_MAX_LINES)  {
07886       ast_log(LOG_WARNING, "Out of SIP line space\n");
07887       return -1;
07888    }
07889    if (!req->lines)
07890       /* Add extra empty return */
07891       req->len += ast_str_append(&req->data, 0, "\r\n");
07892    req->line[req->lines] = req->len;
07893    ast_str_append(&req->data, 0, "%s", line);
07894    req->len = req->data->used;
07895    req->lines++;
07896    return 0;   
07897 }
07898 
07899 /*! \brief Copy one header field from one request to another */
07900 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
07901 {
07902    const char *tmp = get_header(orig, field);
07903 
07904    if (!ast_strlen_zero(tmp)) /* Add what we're responding to */
07905       return add_header(req, field, tmp);
07906    ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
07907    return -1;
07908 }
07909 
07910 /*! \brief Copy all headers from one request to another */
07911 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
07912 {
07913    int start = 0;
07914    int copied = 0;
07915    for (;;) {
07916       const char *tmp = __get_header(orig, field, &start);
07917 
07918       if (ast_strlen_zero(tmp))
07919          break;
07920       /* Add what we're responding to */
07921       add_header(req, field, tmp);
07922       copied++;
07923    }
07924    return copied ? 0 : -1;
07925 }
07926 
07927 /*! \brief Copy SIP VIA Headers from the request to the response
07928 \note If the client indicates that it wishes to know the port we received from,
07929    it adds ;rport without an argument to the topmost via header. We need to
07930    add the port number (from our point of view) to that parameter.
07931 \verbatim
07932    We always add ;received=<ip address> to the topmost via header.
07933 \endverbatim
07934    Received: RFC 3261, rport RFC 3581 */
07935 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
07936 {
07937    int copied = 0;
07938    int start = 0;
07939 
07940    for (;;) {
07941       char new[512];
07942       const char *oh = __get_header(orig, field, &start);
07943 
07944       if (ast_strlen_zero(oh))
07945          break;
07946 
07947       if (!copied) { /* Only check for empty rport in topmost via header */
07948          char leftmost[512], *others, *rport;
07949 
07950          /* Only work on leftmost value */
07951          ast_copy_string(leftmost, oh, sizeof(leftmost));
07952          others = strchr(leftmost, ',');
07953          if (others)
07954              *others++ = '\0';
07955 
07956          /* Find ;rport;  (empty request) */
07957          rport = strstr(leftmost, ";rport");
07958          if (rport && *(rport+6) == '=') 
07959             rport = NULL;     /* We already have a parameter to rport */
07960 
07961          /* Check rport if NAT=yes or NAT=rfc3581 (which is the default setting)  */
07962          if (rport && ((ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_ALWAYS) || (ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_RFC3581))) {
07963             /* We need to add received port - rport */
07964             char *end;
07965 
07966             rport = strstr(leftmost, ";rport");
07967 
07968             if (rport) {
07969                end = strchr(rport + 1, ';');
07970                if (end)
07971                   memmove(rport, end, strlen(end) + 1);
07972                else
07973                   *rport = '\0';
07974             }
07975 
07976             /* Add rport to first VIA header if requested */
07977             snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
07978                leftmost, ast_inet_ntoa(p->recv.sin_addr),
07979                ntohs(p->recv.sin_port),
07980                others ? "," : "", others ? others : "");
07981          } else {
07982             /* We should *always* add a received to the topmost via */
07983             snprintf(new, sizeof(new), "%s;received=%s%s%s",
07984                leftmost, ast_inet_ntoa(p->recv.sin_addr),
07985                others ? "," : "", others ? others : "");
07986          }
07987          oh = new;   /* the header to copy */
07988       }  /* else add the following via headers untouched */
07989       add_header(req, field, oh);
07990       copied++;
07991    }
07992    if (!copied) {
07993       ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
07994       return -1;
07995    }
07996    return 0;
07997 }
07998 
07999 /*! \brief Add route header into request per learned route */
08000 static void add_route(struct sip_request *req, struct sip_route *route)
08001 {
08002    char r[SIPBUFSIZE*2], *p;
08003    int n, rem = sizeof(r);
08004 
08005    if (!route)
08006       return;
08007 
08008    p = r;
08009    for (;route ; route = route->next) {
08010       n = strlen(route->hop);
08011       if (rem < n+3) /* we need room for ",<route>" */
08012          break;
08013       if (p != r) {  /* add a separator after fist route */
08014          *p++ = ',';
08015          --rem;
08016       }
08017       *p++ = '<';
08018       ast_copy_string(p, route->hop, rem); /* cannot fail */
08019       p += n;
08020       *p++ = '>';
08021       rem -= (n+2);
08022    }
08023    *p = '\0';
08024    add_header(req, "Route", r);
08025 }
08026 
08027 /*! \brief Set destination from SIP URI */
08028 static void set_destination(struct sip_pvt *p, char *uri)
08029 {
08030    char *h, *maddr, hostname[256];
08031    int port, hn;
08032    struct hostent *hp;
08033    struct ast_hostent ahp;
08034    int debug=sip_debug_test_pvt(p);
08035 
08036    /* Parse uri to h (host) and port - uri is already just the part inside the <> */
08037    /* general form we are expecting is sip[s]:username[:password][;parameter]@host[:port][;...] */
08038 
08039    if (debug)
08040       ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
08041 
08042    /* Find and parse hostname */
08043    h = strchr(uri, '@');
08044    if (h)
08045       ++h;
08046    else {
08047       h = uri;
08048       if (!strncasecmp(h, "sip:", 4))
08049          h += 4;
08050       else if (!strncasecmp(h, "sips:", 5))
08051          h += 5;
08052    }
08053    hn = strcspn(h, ":;>") + 1;
08054    if (hn > sizeof(hostname)) 
08055       hn = sizeof(hostname);
08056    ast_copy_string(hostname, h, hn);
08057    /* XXX bug here if string has been trimmed to sizeof(hostname) */
08058    h += hn - 1;
08059 
08060    /* Is "port" present? if not default to STANDARD_SIP_PORT */
08061    if (*h == ':') {
08062       /* Parse port */
08063       ++h;
08064       port = strtol(h, &h, 10);
08065    }
08066    else
08067       port = STANDARD_SIP_PORT;
08068 
08069    /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
08070    maddr = strstr(h, "maddr=");
08071    if (maddr) {
08072       maddr += 6;
08073       hn = strspn(maddr, "0123456789.") + 1;
08074       if (hn > sizeof(hostname))
08075          hn = sizeof(hostname);
08076       ast_copy_string(hostname, maddr, hn);
08077    }
08078    
08079    hp = ast_gethostbyname(hostname, &ahp);
08080    if (hp == NULL)  {
08081       ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
08082       return;
08083    }
08084    p->sa.sin_family = AF_INET;
08085    memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
08086    p->sa.sin_port = htons(port);
08087    if (debug)
08088       ast_verbose("set_destination: set destination to %s, port %d\n", ast_inet_ntoa(p->sa.sin_addr), port);
08089 }
08090 
08091 /*! \brief Initialize SIP response, based on SIP request */
08092 static int init_resp(struct sip_request *resp, const char *msg)
08093 {
08094    /* Initialize a response */
08095    memset(resp, 0, sizeof(*resp));
08096    resp->method = SIP_RESPONSE;
08097    if (!(resp->data = ast_str_create(SIP_MIN_PACKET)))
08098       return -1;
08099    resp->header[0] = 0;
08100    ast_str_set(&resp->data, 0, "SIP/2.0 %s\r\n", msg);
08101    resp->len = resp->data->used;
08102    resp->headers++;
08103    return 0;
08104 }
08105 
08106 /*! \brief Initialize SIP request */
08107 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
08108 {
08109    /* Initialize a request */
08110    memset(req, 0, sizeof(*req));
08111    if (!(req->data = ast_str_create(SIP_MIN_PACKET)))
08112       return -1;
08113    req->method = sipmethod;
08114    req->header[0] = 0;
08115    ast_str_set(&req->data, 0, "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
08116    req->len = req->data->used;
08117    req->headers++;
08118    return 0;
08119 }
08120 
08121 /*! \brief Test if this response needs a contact header */
08122 static inline int resp_needs_contact(const char *msg, enum sipmethod method) {
08123    /* Requirements for Contact header inclusion in responses generated
08124     * from the header tables found in the following RFCs.  Where the
08125     * Contact header was marked mandatory (m) or optional (o) this
08126     * function returns 1.
08127     *
08128     * - RFC 3261 (ACK, BYE, CANCEL, INVITE, OPTIONS, REGISTER)
08129     * - RFC 2976 (INFO)
08130     * - RFC 3262 (PRACK)
08131     * - RFC 3265 (SUBSCRIBE, NOTIFY)
08132     * - RFC 3311 (UPDATE)
08133     * - RFC 3428 (MESSAGE)
08134     * - RFC 3515 (REFER)
08135     * - RFC 3903 (PUBLISH)
08136     */
08137 
08138    switch (method) {
08139       /* 1xx, 2xx, 3xx, 485 */
08140       case SIP_INVITE:
08141       case SIP_UPDATE:
08142       case SIP_SUBSCRIBE:
08143       case SIP_NOTIFY:
08144          if ((msg[0] >= '1' && msg[0] <= '3') || !strncmp(msg, "485", 3))
08145             return 1;
08146          break;
08147 
08148       /* 2xx, 3xx, 485 */
08149       case SIP_REGISTER:
08150       case SIP_OPTIONS:
08151          if (msg[0] == '2' || msg[0] == '3' || !strncmp(msg, "485", 3))
08152             return 1;
08153          break;
08154 
08155       /* 3xx, 485 */
08156       case SIP_BYE:
08157       case SIP_PRACK:
08158       case SIP_MESSAGE:
08159       case SIP_PUBLISH:
08160          if (msg[0] == '3' || !strncmp(msg, "485", 3))
08161             return 1;
08162          break;
08163 
08164       /* 2xx, 3xx, 4xx, 5xx, 6xx */
08165       case SIP_REFER:
08166          if (msg[0] >= '2' && msg[0] <= '6')
08167             return 1;
08168          break;
08169 
08170       /* contact will not be included for everything else */
08171       case SIP_ACK:
08172       case SIP_CANCEL:
08173       case SIP_INFO:
08174       case SIP_PING:
08175       default:
08176          return 0;
08177    }
08178    return 0;
08179 }
08180 
08181 /*! \brief Prepare SIP response packet */
08182 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
08183 {
08184    char newto[256];
08185    const char *ot;
08186 
08187    init_resp(resp, msg);
08188    copy_via_headers(p, resp, req, "Via");
08189    if (msg[0] == '1' || msg[0] == '2')
08190       copy_all_header(resp, req, "Record-Route");
08191    copy_header(resp, req, "From");
08192    ot = get_header(req, "To");
08193    if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
08194       /* Add the proper tag if we don't have it already.  If they have specified
08195          their tag, use it.  Otherwise, use our own tag */
08196       if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
08197          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
08198       else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
08199          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
08200       else
08201          ast_copy_string(newto, ot, sizeof(newto));
08202       ot = newto;
08203    }
08204    add_header(resp, "To", ot);
08205    copy_header(resp, req, "Call-ID");
08206    copy_header(resp, req, "CSeq");
08207    if (!ast_strlen_zero(global_useragent))
08208       add_header(resp, "Server", global_useragent);
08209    add_header(resp, "Allow", ALLOWED_METHODS);
08210    add_header(resp, "Supported", SUPPORTED_EXTENSIONS);
08211 
08212    /* If this is an invite, add Session-Timers related headers if the feature is active for this session */
08213    if (p->method == SIP_INVITE && p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE) {
08214       char se_hdr[256];
08215       snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval, 
08216          strefresher2str(p->stimer->st_ref));
08217       add_header(resp, "Require", "timer");
08218       add_header(resp, "Session-Expires", se_hdr);
08219    }
08220 
08221    if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
08222       /* For registration responses, we also need expiry and
08223          contact info */
08224       char tmp[256];
08225 
08226       snprintf(tmp, sizeof(tmp), "%d", p->expiry);
08227       add_header(resp, "Expires", tmp);
08228       if (p->expiry) {  /* Only add contact if we have an expiry time */
08229          char contact[SIPBUFSIZE];
08230          snprintf(contact, sizeof(contact), "%s;expires=%d", p->our_contact, p->expiry);
08231          add_header(resp, "Contact", contact);  /* Not when we unregister */
08232       }
08233    } else if (!ast_strlen_zero(p->our_contact) && resp_needs_contact(msg, p->method)) {
08234       add_header(resp, "Contact", p->our_contact);
08235    }
08236 
08237    if (!ast_strlen_zero(p->url)) {
08238       add_header(resp, "Access-URL", p->url);
08239       ast_string_field_set(p, url, NULL);
08240    }
08241 
08242    return 0;
08243 }
08244 
08245 /*! \brief Initialize a SIP request message (not the initial one in a dialog) */
08246 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch)
08247 {
08248    struct sip_request *orig = &p->initreq;
08249    char stripped[80];
08250    char tmp[80];
08251    char newto[256];
08252    const char *c;
08253    const char *ot, *of;
08254    int is_strict = FALSE;     /*!< Strict routing flag */
08255    int is_outbound = ast_test_flag(&p->flags[0], SIP_OUTGOING);   /* Session direction */
08256 
08257    memset(req, 0, sizeof(struct sip_request));
08258    
08259    snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
08260    
08261    if (!seqno) {
08262       p->ocseq++;
08263       seqno = p->ocseq;
08264    }
08265    
08266    /* A CANCEL must have the same branch as the INVITE that it is canceling.
08267     * Similarly, if we need to re-send an INVITE with auth credentials, then we
08268     * need to use the same branch as we did the first time we sent the INVITE.
08269     */
08270    if (sipmethod == SIP_CANCEL || (sipmethod == SIP_INVITE && p->options && !ast_strlen_zero(p->options->auth))) {
08271       p->branch = p->invite_branch;
08272       build_via(p);
08273    } else if (newbranch) {
08274       p->branch ^= ast_random();
08275       build_via(p);
08276    }
08277 
08278    /* Check for strict or loose router */
08279    if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop, ";lr") == NULL) {
08280       is_strict = TRUE;
08281       if (sipdebug)
08282          ast_debug(1, "Strict routing enforced for session %s\n", p->callid);
08283    }
08284    
08285    if (sipmethod == SIP_CANCEL)
08286       c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2); /* Use original URI */
08287    else if (sipmethod == SIP_ACK) {
08288       /* Use URI from Contact: in 200 OK (if INVITE) 
08289       (we only have the contacturi on INVITEs) */
08290       if (!ast_strlen_zero(p->okcontacturi))
08291          c = is_strict ? p->route->hop : p->okcontacturi;
08292       else
08293          c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
08294    } else if (!ast_strlen_zero(p->okcontacturi)) 
08295       c = is_strict ? p->route->hop : p->okcontacturi; /* Use for BYE or REINVITE */
08296    else if (!ast_strlen_zero(p->uri)) 
08297       c = p->uri;
08298    else {
08299       char *n;
08300       /* We have no URI, use To: or From:  header as URI (depending on direction) */
08301       ast_copy_string(stripped, get_header(orig, is_outbound ? "To" : "From"),
08302             sizeof(stripped));
08303       n = get_in_brackets(stripped);
08304       c = remove_uri_parameters(n);
08305    }  
08306    init_req(req, sipmethod, c);
08307 
08308    snprintf(tmp, sizeof(tmp), "%d %s", seqno, sip_methods[sipmethod].text);
08309 
08310    add_header(req, "Via", p->via);
08311    if (p->route) {
08312       set_destination(p, p->route->hop);
08313       add_route(req, is_strict ? p->route->next : p->route);
08314    }
08315    add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
08316 
08317    ot = get_header(orig, "To");
08318    of = get_header(orig, "From");
08319 
08320    /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
08321       as our original request, including tag (or presumably lack thereof) */
08322    if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
08323       /* Add the proper tag if we don't have it already.  If they have specified
08324          their tag, use it.  Otherwise, use our own tag */
08325       if (is_outbound && !ast_strlen_zero(p->theirtag))
08326          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
08327       else if (!is_outbound)
08328          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
08329       else
08330          snprintf(newto, sizeof(newto), "%s", ot);
08331       ot = newto;
08332    }
08333 
08334    if (is_outbound) {
08335       add_header(req, "From", of);
08336       add_header(req, "To", ot);
08337    } else {
08338       add_header(req, "From", ot);
08339       add_header(req, "To", of);
08340    }
08341    /* Do not add Contact for MESSAGE, BYE and Cancel requests */
08342    if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
08343       add_header(req, "Contact", p->our_contact);
08344 
08345    copy_header(req, orig, "Call-ID");
08346    add_header(req, "CSeq", tmp);
08347 
08348    if (!ast_strlen_zero(global_useragent))
08349       add_header(req, "User-Agent", global_useragent);
08350 
08351    if (!ast_strlen_zero(p->rpid))
08352       add_header(req, "Remote-Party-ID", p->rpid);
08353 
08354    if (!ast_strlen_zero(p->url)) {
08355       add_header(req, "Access-URL", p->url);
08356       ast_string_field_set(p, url, NULL);
08357    }
08358 
08359    /* Add Session-Timers related headers if the feature is active for this session.
08360       An exception to this behavior is the ACK request. Since Asterisk never requires 
08361       session-timers support from a remote end-point (UAS) in an INVITE, it must 
08362       not send 'Require: timer' header in the ACK request. 
08363       This should only be added in the INVITE transactions, not MESSAGE or REFER or other
08364       in-dialog messages.
08365    */
08366    if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE 
08367        && sipmethod == SIP_INVITE) {
08368       char se_hdr[256];
08369       snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval, 
08370          strefresher2str(p->stimer->st_ref));
08371       add_header(req, "Require", "timer");
08372       add_header(req, "Session-Expires", se_hdr);
08373       snprintf(se_hdr, sizeof(se_hdr), "%d", st_get_se(p, FALSE));
08374       add_header(req, "Min-SE", se_hdr);
08375    }
08376 
08377    return 0;
08378 }
08379 
08380 /*! \brief Base transmit response function */
08381 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
08382 {
08383    struct sip_request resp;
08384    int seqno = 0;
08385 
08386    if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
08387       ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
08388       return -1;
08389    }
08390    respprep(&resp, p, msg, req);
08391    add_header_contentLength(&resp, 0);
08392    /* If we are cancelling an incoming invite for some reason, add information
08393       about the reason why we are doing this in clear text */
08394    if (p->method == SIP_INVITE && msg[0] != '1' && p->owner && p->owner->hangupcause) {
08395       char buf[10];
08396 
08397       add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
08398       snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
08399       add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
08400    }
08401    return send_response(p, &resp, reliable, seqno);
08402 }
08403 
08404 static int temp_pvt_init(void *data)
08405 {
08406    struct sip_pvt *p = data;
08407 
08408    p->do_history = 0;   /* XXX do we need it ? isn't already all 0 ? */
08409    return ast_string_field_init(p, 512);
08410 }
08411 
08412 static void temp_pvt_cleanup(void *data)
08413 {
08414    struct sip_pvt *p = data;
08415 
08416    ast_string_field_free_memory(p);
08417 
08418    ast_free(data);
08419 }
08420 
08421 /*! \brief Transmit response, no retransmits, using a temporary pvt structure */
08422 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)
08423 {
08424    struct sip_pvt *p = NULL;
08425 
08426    if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
08427       ast_log(LOG_ERROR, "Failed to get temporary pvt\n");
08428       return -1;
08429    }
08430 
08431    /* XXX the structure may be dirty from previous usage.
08432     * Here we should state clearly how we should reinitialize it
08433     * before using it.
08434     * E.g. certainly the threadstorage should be left alone,
08435     * but other thihngs such as flags etc. maybe need cleanup ?
08436     */
08437     
08438    /* Initialize the bare minimum */
08439    p->method = intended_method;
08440 
08441    if (!sin)
08442       p->ourip = internip;
08443    else {
08444       p->sa = *sin;
08445       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
08446    }
08447 
08448    p->branch = ast_random();
08449    make_our_tag(p->tag, sizeof(p->tag));
08450    p->ocseq = INITIAL_CSEQ;
08451 
08452    if (useglobal_nat && sin) {
08453       ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
08454       p->recv = *sin;
08455       do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
08456    }
08457 
08458    ast_string_field_set(p, fromdomain, default_fromdomain);
08459    build_via(p);
08460    ast_string_field_set(p, callid, callid);
08461 
08462    copy_socket_data(&p->socket, &req->socket);
08463 
08464    /* Use this temporary pvt structure to send the message */
08465    __transmit_response(p, msg, req, XMIT_UNRELIABLE);
08466 
08467    /* Free the string fields, but not the pool space */
08468    ast_string_field_init(p, 0);
08469 
08470    return 0;
08471 }
08472 
08473 /*! \brief Transmit response, no retransmits */
08474 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req) 
08475 {
08476    return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
08477 }
08478 
08479 /*! \brief Transmit response, no retransmits */
08480 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported) 
08481 {
08482    struct sip_request resp;
08483    respprep(&resp, p, msg, req);
08484    append_date(&resp);
08485    add_header(&resp, "Unsupported", unsupported);
08486    add_header_contentLength(&resp, 0);
08487    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
08488 }
08489 
08490 /*! \brief Transmit 422 response with Min-SE header (Session-Timers)  */
08491 static int transmit_response_with_minse(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minse_int)
08492 {
08493    struct sip_request resp;
08494    char minse_str[20];
08495 
08496    respprep(&resp, p, msg, req);
08497    append_date(&resp);
08498 
08499    snprintf(minse_str, sizeof(minse_str), "%d", minse_int);
08500    add_header(&resp, "Min-SE", minse_str);
08501 
08502    add_header_contentLength(&resp, 0);
08503    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
08504 }
08505 
08506 
08507 /*! \brief Transmit response, Make sure you get an ACK
08508    This is only used for responses to INVITEs, where we need to make sure we get an ACK
08509 */
08510 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
08511 {
08512    return __transmit_response(p, msg, req, req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL);
08513 }
08514 
08515 /*! \brief Append date to SIP message */
08516 static void append_date(struct sip_request *req)
08517 {
08518    char tmpdat[256];
08519    struct tm tm;
08520    time_t t = time(NULL);
08521 
08522    gmtime_r(&t, &tm);
08523    strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
08524    add_header(req, "Date", tmpdat);
08525 }
08526 
08527 /*! \brief Append date and content length before transmitting response */
08528 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
08529 {
08530    struct sip_request resp;
08531    respprep(&resp, p, msg, req);
08532    append_date(&resp);
08533    add_header_contentLength(&resp, 0);
08534    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
08535 }
08536 
08537 /*! \brief Append Accept header, content length before transmitting response */
08538 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
08539 {
08540    struct sip_request resp;
08541    respprep(&resp, p, msg, req);
08542    add_header(&resp, "Accept", "application/sdp");
08543    add_header_contentLength(&resp, 0);
08544    return send_response(p, &resp, reliable, 0);
08545 }
08546 
08547 /*! \brief Respond with authorization request */
08548 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)
08549 {
08550    struct sip_request resp;
08551    char tmp[512];
08552    int seqno = 0;
08553 
08554    if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
08555       ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
08556       return -1;
08557    }
08558    /* Stale means that they sent us correct authentication, but 
08559       based it on an old challenge (nonce) */
08560    snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", global_realm, randdata, stale ? ", stale=true" : "");
08561    respprep(&resp, p, msg, req);
08562    add_header(&resp, header, tmp);
08563    add_header_contentLength(&resp, 0);
08564    append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
08565    return send_response(p, &resp, reliable, seqno);
08566 }
08567 
08568 /*! \brief Add text body to SIP message */
08569 static int add_text(struct sip_request *req, const char *text)
08570 {
08571    /* XXX Convert \n's to \r\n's XXX */
08572    add_header(req, "Content-Type", "text/plain;charset=UTF-8");
08573    add_header_contentLength(req, strlen(text));
08574    add_line(req, text);
08575    return 0;
08576 }
08577 
08578 /*! \brief Add DTMF INFO tone to sip message 
08579    Mode =   0 for application/dtmf-relay (Cisco)
08580       1 for application/dtmf
08581 */
08582 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode)
08583 {
08584    char tmp[256];
08585    int event;
08586    if (mode) {
08587       /* Application/dtmf short version used by some implementations */
08588       if (digit == '*')
08589          event = 10;
08590       else if (digit == '#')
08591          event = 11;
08592       else if ((digit >= 'A') && (digit <= 'D'))
08593          event = 12 + digit - 'A';
08594       else
08595          event = atoi(&digit);
08596       snprintf(tmp, sizeof(tmp), "%d\r\n", event);
08597       add_header(req, "Content-Type", "application/dtmf");
08598       add_header_contentLength(req, strlen(tmp));
08599       add_line(req, tmp);
08600    } else {
08601       /* Application/dtmf-relay as documented by Cisco */
08602       snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
08603       add_header(req, "Content-Type", "application/dtmf-relay");
08604       add_header_contentLength(req, strlen(tmp));
08605       add_line(req, tmp);
08606    }
08607    return 0;
08608 }
08609 
08610 /*! \brief add XML encoded media control with update 
08611    \note XML: The only way to turn 0 bits of information into a few hundred. (markster) */
08612 static int add_vidupdate(struct sip_request *req)
08613 {
08614    const char *xml_is_a_huge_waste_of_space =
08615       "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
08616       " <media_control>\r\n"
08617       "  <vc_primitive>\r\n"
08618       "   <to_encoder>\r\n"
08619       "    <picture_fast_update>\r\n"
08620       "    </picture_fast_update>\r\n"
08621       "   </to_encoder>\r\n"
08622       "  </vc_primitive>\r\n"
08623       " </media_control>\r\n";
08624    add_header(req, "Content-Type", "application/media_control+xml");
08625    add_header_contentLength(req, strlen(xml_is_a_huge_waste_of_space));
08626    add_line(req, xml_is_a_huge_waste_of_space);
08627    return 0;
08628 }
08629 
08630 /*! \brief Add codec offer to SDP offer/answer body in INVITE or 200 OK */
08631 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
08632               struct ast_str **m_buf, struct ast_str **a_buf,
08633               int debug, int *min_packet_size)
08634 {
08635    int rtp_code;
08636    struct ast_format_list fmt;
08637 
08638 
08639    if (debug)
08640       ast_verbose("Adding codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
08641    if ((rtp_code = ast_rtp_lookup_code(p->rtp, 1, codec)) == -1)
08642       return;
08643 
08644    if (p->rtp) {
08645       struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
08646       fmt = ast_codec_pref_getsize(pref, codec);
08647    } 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 */
08648       return;
08649    ast_str_append(m_buf, 0, " %d", rtp_code);
08650    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
08651           ast_rtp_lookup_mime_subtype(1, codec,
08652                        ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
08653           sample_rate);
08654    if (codec == AST_FORMAT_G729A) {
08655       /* Indicate that we don't support VAD (G.729 annex B) */
08656       ast_str_append(a_buf, 0, "a=fmtp:%d annexb=no\r\n", rtp_code);
08657    } else if (codec == AST_FORMAT_G723_1) {
08658       /* Indicate that we don't support VAD (G.723.1 annex A) */
08659       ast_str_append(a_buf, 0, "a=fmtp:%d annexa=no\r\n", rtp_code);
08660    } else if (codec == AST_FORMAT_ILBC) {
08661       /* Add information about us using only 20/30 ms packetization */
08662       ast_str_append(a_buf, 0, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
08663    }
08664 
08665    if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
08666       *min_packet_size = fmt.cur_ms;
08667 
08668    /* Our first codec packetization processed cannot be zero */
08669    if ((*min_packet_size)==0 && fmt.cur_ms)
08670       *min_packet_size = fmt.cur_ms;
08671 }
08672 
08673 /*! \brief Add video codec offer to SDP offer/answer body in INVITE or 200 OK */
08674 /* This is different to the audio one now so we can add more caps later */
08675 static void add_vcodec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
08676               struct ast_str **m_buf, struct ast_str **a_buf,
08677               int debug, int *min_packet_size)
08678 {
08679    int rtp_code;
08680 
08681    if (!p->vrtp)
08682       return;
08683 
08684    if (debug)
08685       ast_verbose("Adding video codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
08686 
08687    if ((rtp_code = ast_rtp_lookup_code(p->vrtp, 1, codec)) == -1)
08688       return;
08689 
08690    ast_str_append(m_buf, 0, " %d", rtp_code);
08691    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
08692           ast_rtp_lookup_mime_subtype(1, codec, 0), sample_rate);
08693    /* Add fmtp code here */
08694 }
08695 
08696 /*! \brief Add text codec offer to SDP offer/answer body in INVITE or 200 OK */
08697 static void add_tcodec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
08698               struct ast_str **m_buf, struct ast_str **a_buf,
08699               int debug, int *min_packet_size)
08700 {
08701    int rtp_code;
08702 
08703    if (!p->trtp)
08704       return;
08705 
08706    if (debug)
08707       ast_verbose("Adding text codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
08708 
08709    if ((rtp_code = ast_rtp_lookup_code(p->trtp, 1, codec)) == -1)
08710       return;
08711 
08712    ast_str_append(m_buf, 0, " %d", rtp_code);
08713    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
08714           ast_rtp_lookup_mime_subtype(1, codec, 0), sample_rate);
08715    /* Add fmtp code here */
08716 
08717    if (codec == AST_FORMAT_T140RED) {
08718       ast_str_append(a_buf, 0, "a=fmtp:%d %d/%d/%d\r\n", rtp_code, 
08719           ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140),
08720           ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140),
08721           ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140));
08722 
08723    }
08724 }
08725 
08726 
08727 /*! \brief Get Max T.38 Transmission rate from T38 capabilities */
08728 static unsigned int t38_get_rate(enum ast_control_t38_rate rate)
08729 {
08730    switch (rate) {
08731    case AST_T38_RATE_2400:
08732       return 2400;
08733    case AST_T38_RATE_4800:
08734       return 4800;
08735    case AST_T38_RATE_7200:
08736       return 7200;
08737    case AST_T38_RATE_9600:
08738       return 9600;
08739    case AST_T38_RATE_12000:
08740       return 12000;
08741    case AST_T38_RATE_14400:
08742       return 14400;
08743    default:
08744       return 0;
08745    }
08746 }
08747 
08748 /*! \brief Add RFC 2833 DTMF offer to SDP */
08749 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
08750             struct ast_str **m_buf, struct ast_str **a_buf,
08751             int debug)
08752 {
08753    int rtp_code;
08754 
08755    if (debug)
08756       ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype(0, format, 0));
08757    if ((rtp_code = ast_rtp_lookup_code(p->rtp, 0, format)) == -1)
08758       return;
08759 
08760    ast_str_append(m_buf, 0, " %d", rtp_code);
08761    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
08762           ast_rtp_lookup_mime_subtype(0, format, 0),
08763           sample_rate);
08764    if (format == AST_RTP_DTMF)   /* Indicate we support DTMF and FLASH... */
08765       ast_str_append(a_buf, 0, "a=fmtp:%d 0-16\r\n", rtp_code);
08766 }
08767 
08768 /*! \brief Set all IP media addresses for this call 
08769    \note called from add_sdp()
08770 */
08771 static void get_our_media_address(struct sip_pvt *p, int needvideo,
08772    struct sockaddr_in *sin, struct sockaddr_in *vsin, struct sockaddr_in *tsin,
08773    struct sockaddr_in *dest, struct sockaddr_in *vdest)
08774 {
08775    /* First, get our address */
08776    ast_rtp_get_us(p->rtp, sin);
08777    if (p->vrtp)
08778       ast_rtp_get_us(p->vrtp, vsin);
08779    if (p->trtp)
08780       ast_rtp_get_us(p->trtp, tsin);
08781 
08782    /* Now, try to figure out where we want them to send data */
08783    /* Is this a re-invite to move the media out, then use the original offer from caller  */
08784    if (p->redirip.sin_addr.s_addr) {   /* If we have a redirection IP, use it */
08785       dest->sin_port = p->redirip.sin_port;
08786       dest->sin_addr = p->redirip.sin_addr;
08787    } else {
08788       dest->sin_addr = p->ourip.sin_addr;
08789       dest->sin_port = sin->sin_port;
08790    }
08791    if (needvideo) {
08792       /* Determine video destination */
08793       if (p->vredirip.sin_addr.s_addr) {
08794          vdest->sin_addr = p->vredirip.sin_addr;
08795          vdest->sin_port = p->vredirip.sin_port;
08796       } else {
08797          vdest->sin_addr = p->ourip.sin_addr;
08798          vdest->sin_port = vsin->sin_port;
08799       }
08800    }
08801 
08802 }
08803 
08804 /*!
08805  * \note G.722 actually is supposed to specified as 8 kHz, even though it is
08806  * really 16 kHz.  Update this macro for other formats as they are added in
08807  * the future.
08808  */
08809 #define SDP_SAMPLE_RATE(x) 8000
08810 
08811 /*! \brief Add Session Description Protocol message 
08812 
08813     If oldsdp is TRUE, then the SDP version number is not incremented. This mechanism
08814     is used in Session-Timers where RE-INVITEs are used for refreshing SIP sessions 
08815     without modifying the media session in any way. 
08816 */
08817 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38)
08818 {
08819    int len = 0;
08820    int alreadysent = 0;
08821 
08822    struct sockaddr_in sin;
08823    struct sockaddr_in vsin;
08824    struct sockaddr_in tsin;
08825    struct sockaddr_in dest;
08826    struct sockaddr_in udptlsin;
08827    struct sockaddr_in vdest = { 0, };
08828    struct sockaddr_in tdest = { 0, };
08829    struct sockaddr_in udptldest = { 0, };
08830 
08831    /* SDP fields */
08832    char *version =   "v=0\r\n";     /* Protocol version */
08833    char subject[256];            /* Subject of the session */
08834    char owner[256];           /* Session owner/creator */
08835    char connection[256];            /* Connection data */
08836    char *session_time = "t=0 0\r\n";         /* Time the session is active */
08837    char bandwidth[256] = "";        /* Max bitrate */
08838    char *hold = "";
08839    struct ast_str *m_audio = ast_str_alloca(256);  /* Media declaration line for audio */
08840    struct ast_str *m_video = ast_str_alloca(256);  /* Media declaration line for video */
08841    struct ast_str *m_text = ast_str_alloca(256);   /* Media declaration line for text */
08842    struct ast_str *m_modem = ast_str_alloca(256);  /* Media declaration line for modem */
08843    struct ast_str *a_audio = ast_str_alloca(1024); /* Attributes for audio */
08844    struct ast_str *a_video = ast_str_alloca(1024); /* Attributes for video */
08845    struct ast_str *a_text = ast_str_alloca(1024);  /* Attributes for text */
08846    struct ast_str *a_modem = ast_str_alloca(1024); /* Attributes for modem */
08847 
08848    int x;
08849    int capability = 0;
08850    int needaudio = FALSE;
08851    int needvideo = FALSE;
08852    int needtext = FALSE;
08853    int debug = sip_debug_test_pvt(p);
08854    int min_audio_packet_size = 0;
08855    int min_video_packet_size = 0;
08856    int min_text_packet_size = 0;
08857 
08858    char codecbuf[SIPBUFSIZE];
08859    char buf[SIPBUFSIZE];
08860    char dummy_answer[256];
08861 
08862    /* Set the SDP session name */
08863    snprintf(subject, sizeof(subject), "s=%s\r\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
08864 
08865    if (!p->rtp) {
08866       ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
08867       return AST_FAILURE;
08868    }
08869    /* XXX We should not change properties in the SIP dialog until 
08870       we have acceptance of the offer if this is a re-invite */
08871 
08872    /* Set RTP Session ID and version */
08873    if (!p->sessionid) {
08874       p->sessionid = (int)ast_random();
08875       p->sessionversion = p->sessionid;
08876    } else {
08877       if (oldsdp == FALSE)
08878          p->sessionversion++;
08879    }
08880 
08881    /* Check if we need video in this call */
08882    if (add_audio && (capability & AST_FORMAT_VIDEO_MASK) && !p->novideo) {
08883       if (p->vrtp) {
08884          needvideo = TRUE;
08885          ast_debug(2, "This call needs video offers!\n");
08886       } else
08887          ast_debug(2, "This call needs video offers, but there's no video support enabled!\n");
08888    }
08889 
08890    get_our_media_address(p, needvideo, &sin, &vsin, &tsin, &dest, &vdest);
08891 
08892    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));
08893    snprintf(connection, sizeof(connection), "c=IN IP4 %s\r\n", ast_inet_ntoa(dest.sin_addr));
08894 
08895    if (add_audio) {
08896       capability = p->jointcapability;
08897 
08898       /* XXX note, Video and Text are negated - 'true' means 'no' */
08899       ast_debug(1, "** Our capability: %s Video flag: %s Text flag: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability), 
08900            p->novideo ? "True" : "False", p->notext ? "True" : "False");
08901       ast_debug(1, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));
08902 
08903       /* Check if we need audio */
08904       if (capability & AST_FORMAT_AUDIO_MASK)
08905          needaudio = TRUE;
08906 
08907       if (debug) 
08908          ast_verbose("Audio is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(sin.sin_port)); 
08909 
08910       /* Ok, we need video. Let's add what we need for video and set codecs.
08911          Video is handled differently than audio since we can not transcode. */
08912       if (needvideo) {
08913          ast_str_append(&m_video, 0, "m=video %d RTP/AVP", ntohs(vdest.sin_port));
08914 
08915          /* Build max bitrate string */
08916          if (p->maxcallbitrate)
08917             snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
08918          if (debug) 
08919             ast_verbose("Video is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(vdest.sin_port));  
08920       }
08921 
08922       /* Check if we need text in this call */
08923       if((capability & AST_FORMAT_TEXT_MASK) && !p->notext) {
08924          if (sipdebug_text)
08925             ast_verbose("We think we can do text\n");
08926          if (p->trtp) {
08927             if (sipdebug_text)
08928                ast_verbose("And we have a text rtp object\n");
08929             needtext = TRUE;
08930             ast_debug(2, "This call needs text offers! \n");
08931          } else
08932             ast_debug(2, "This call needs text offers, but there's no text support enabled ! \n");
08933       }
08934       
08935       /* Ok, we need text. Let's add what we need for text and set codecs.
08936          Text is handled differently than audio since we can not transcode. */
08937       if (needtext) {
08938          if (sipdebug_text)
08939             ast_verbose("Lets set up the text sdp\n");
08940          /* Determine text destination */
08941          if (p->tredirip.sin_addr.s_addr) {
08942             tdest.sin_addr = p->tredirip.sin_addr;
08943             tdest.sin_port = p->tredirip.sin_port;
08944          } else {
08945             tdest.sin_addr = p->ourip.sin_addr;
08946             tdest.sin_port = tsin.sin_port;
08947          }
08948          ast_str_append(&m_text, 0, "m=text %d RTP/AVP", ntohs(tdest.sin_port));
08949 
08950          if (debug) /* XXX should I use tdest below ? */
08951             ast_verbose("Text is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(tsin.sin_port)); 
08952 
08953       }
08954 
08955       /* Start building generic SDP headers */
08956 
08957       /* We break with the "recommendation" and send our IP, in order that our
08958          peer doesn't have to ast_gethostbyname() us */
08959 
08960       ast_str_append(&m_audio, 0, "m=audio %d RTP/AVP", ntohs(dest.sin_port));
08961 
08962       if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR)
08963          hold = "a=recvonly\r\n";
08964       else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE)
08965          hold = "a=inactive\r\n";
08966       else
08967          hold = "a=sendrecv\r\n";
08968 
08969       /* Now, start adding audio codecs. These are added in this order:
08970          - First what was requested by the calling channel
08971          - Then preferences in order from sip.conf device config for this peer/user
08972          - Then other codecs in capabilities, including video
08973       */
08974 
08975       /* Prefer the audio codec we were requested to use, first, no matter what 
08976          Note that p->prefcodec can include video codecs, so mask them out
08977       */
08978       if (capability & p->prefcodec) {
08979          int codec = p->prefcodec & AST_FORMAT_AUDIO_MASK;
08980 
08981          add_codec_to_sdp(p, codec, SDP_SAMPLE_RATE(codec),
08982                 &m_audio, &a_audio,
08983                 debug, &min_audio_packet_size);
08984          alreadysent |= codec;
08985       }
08986 
08987       /* Start by sending our preferred audio/video codecs */
08988       for (x = 0; x < 32; x++) {
08989          int codec;
08990 
08991          if (!(codec = ast_codec_pref_index(&p->prefs, x)))
08992             break; 
08993 
08994          if (!(capability & codec))
08995             continue;
08996 
08997          if (alreadysent & codec)
08998          continue;
08999 
09000          add_codec_to_sdp(p, codec, SDP_SAMPLE_RATE(codec),
09001                 &m_audio, &a_audio,
09002                 debug, &min_audio_packet_size);
09003          alreadysent |= codec;
09004       }
09005 
09006       /* Now send any other common audio and video codecs, and non-codec formats: */
09007       for (x = 1; x <= (needtext ? AST_FORMAT_TEXT_MASK : (needvideo ? AST_FORMAT_VIDEO_MASK : AST_FORMAT_AUDIO_MASK)); x <<= 1) {
09008          if (!(capability & x))  /* Codec not requested */
09009             continue;
09010 
09011          if (alreadysent & x) /* Already added to SDP */
09012             continue;
09013 
09014          if (x & AST_FORMAT_AUDIO_MASK)
09015             add_codec_to_sdp(p, x, SDP_SAMPLE_RATE(x),
09016                    &m_audio, &a_audio, debug, &min_audio_packet_size);
09017          else if (x & AST_FORMAT_VIDEO_MASK) 
09018             add_vcodec_to_sdp(p, x, 90000,
09019                     &m_video, &a_video, debug, &min_video_packet_size);
09020          else if (x & AST_FORMAT_TEXT_MASK)
09021             add_tcodec_to_sdp(p, x, 1000,
09022                     &m_text, &a_text, debug, &min_text_packet_size);
09023       }
09024 
09025       /* Now add DTMF RFC2833 telephony-event as a codec */
09026       for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
09027          if (!(p->jointnoncodeccapability & x))
09028             continue;
09029 
09030          add_noncodec_to_sdp(p, x, 8000, &m_audio, &a_audio, debug);
09031       }
09032 
09033       ast_debug(3, "-- Done with adding codecs to SDP\n");
09034 
09035       if (!p->owner || !ast_internal_timing_enabled(p->owner))
09036          ast_str_append(&a_audio, 0, "a=silenceSupp:off - - - -\r\n");
09037 
09038       if (min_audio_packet_size)
09039          ast_str_append(&a_audio, 0, "a=ptime:%d\r\n", min_audio_packet_size);
09040 
09041       /* XXX don't think you can have ptime for video */
09042       if (min_video_packet_size)
09043          ast_str_append(&a_video, 0, "a=ptime:%d\r\n", min_video_packet_size);
09044 
09045       /* XXX don't think you can have ptime for text */
09046       if (min_text_packet_size)
09047          ast_str_append(&a_text, 0, "a=ptime:%d\r\n", min_text_packet_size);
09048    }
09049 
09050    if (add_t38) {
09051       ast_udptl_get_us(p->udptl, &udptlsin);
09052 
09053       /* Determine T.38 UDPTL destination */
09054       if (p->udptlredirip.sin_addr.s_addr) {
09055          udptldest.sin_port = p->udptlredirip.sin_port;
09056          udptldest.sin_addr = p->udptlredirip.sin_addr;
09057       } else {
09058          udptldest.sin_addr = p->ourip.sin_addr;
09059          udptldest.sin_port = udptlsin.sin_port;
09060       }
09061 
09062       if (debug)
09063          ast_debug(1, "T.38 UDPTL is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(udptlsin.sin_port));
09064 
09065       /* We break with the "recommendation" and send our IP, in order that our
09066          peer doesn't have to ast_gethostbyname() us */
09067 
09068       ast_str_append(&m_modem, 0, "m=image %d udptl t38\r\n", ntohs(udptldest.sin_port));
09069 
09070       ast_str_append(&a_modem, 0, "a=T38Faxversion:%d\r\n", p->t38.our_parms.version);
09071       ast_str_append(&a_modem, 0, "a=T38MaxBitRate:%d\r\n", t38_get_rate(p->t38.our_parms.rate));
09072       if (p->t38.our_parms.fill_bit_removal) {
09073          ast_str_append(&a_modem, 0, "a=T38FaxFillBitRemoval\r\n");
09074       }
09075       if (p->t38.our_parms.transcoding_mmr) {
09076          ast_str_append(&a_modem, 0, "a=T38FaxTranscodingMMR\r\n");
09077       }
09078       if (p->t38.our_parms.transcoding_jbig) {
09079          ast_str_append(&a_modem, 0, "a=T38FaxTranscodingJBIG\r\n");
09080       }
09081       switch (p->t38.our_parms.rate_management) {
09082       case AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF:
09083          ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:transferredTCF\r\n");
09084          break;
09085       case AST_T38_RATE_MANAGEMENT_LOCAL_TCF:
09086          ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:localTCF\r\n");
09087          break;
09088       }
09089       ast_str_append(&a_modem, 0, "a=T38FaxMaxDatagram:%d\r\n", ast_udptl_get_local_max_datagram(p->udptl));
09090       switch (ast_udptl_get_error_correction_scheme(p->udptl)) {
09091       case UDPTL_ERROR_CORRECTION_NONE:
09092          break;
09093       case UDPTL_ERROR_CORRECTION_FEC:
09094          ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPFEC\r\n");
09095          break;
09096       case UDPTL_ERROR_CORRECTION_REDUNDANCY:
09097          ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPRedundancy\r\n");
09098          break;
09099       }
09100    }
09101 
09102    if (m_audio->len - m_audio->used < 2 || m_video->len - m_video->used < 2 ||
09103        m_text->len - m_text->used < 2 || a_text->len - a_text->used < 2 ||
09104        a_audio->len - a_audio->used < 2 || a_video->len - a_video->used < 2)
09105       ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
09106 
09107    if (needaudio)
09108       ast_str_append(&m_audio, 0, "\r\n");
09109    if (needvideo)
09110       ast_str_append(&m_video, 0, "\r\n");
09111    if (needtext)
09112       ast_str_append(&m_text, 0, "\r\n");
09113 
09114    len = strlen(version) + strlen(subject) + strlen(owner) +
09115       strlen(connection) + strlen(session_time);
09116    if (needaudio)
09117       len += m_audio->used + a_audio->used + strlen(hold);
09118    if (needvideo) /* only if video response is appropriate */
09119       len += m_video->used + a_video->used + strlen(bandwidth) + strlen(hold);
09120    if (needtext) /* only if text response is appropriate */
09121       len += m_text->used + a_text->used + strlen(hold);
09122    if (add_t38)
09123       len += m_modem->used + a_modem->used;
09124 
09125    add_header(resp, "Content-Type", "application/sdp");
09126    add_header_contentLength(resp, len);
09127    add_line(resp, version);
09128    add_line(resp, owner);
09129    add_line(resp, subject);
09130    add_line(resp, connection);
09131    if (needvideo)    /* only if video response is appropriate */
09132       add_line(resp, bandwidth);
09133    add_line(resp, session_time);
09134    if (needaudio) {
09135       add_line(resp, m_audio->str);
09136       add_line(resp, a_audio->str);
09137       add_line(resp, hold);
09138    } else if (p->offered_media[SDP_AUDIO].offered) {
09139       snprintf(dummy_answer, sizeof(dummy_answer), "m=audio 0 RTP/AVP %s\r\n", p->offered_media[SDP_AUDIO].text);
09140       add_line(resp, dummy_answer);
09141    }
09142    if (needvideo) { /* only if video response is appropriate */
09143       add_line(resp, m_video->str);
09144       add_line(resp, a_video->str);
09145       add_line(resp, hold);   /* Repeat hold for the video stream */
09146    } else if (p->offered_media[SDP_VIDEO].offered) {
09147       snprintf(dummy_answer, sizeof(dummy_answer), "m=video 0 RTP/AVP %s\r\n", p->offered_media[SDP_VIDEO].text);
09148       add_line(resp, dummy_answer);
09149    }
09150    if (needtext) { /* only if text response is appropriate */
09151       add_line(resp, m_text->str);
09152       add_line(resp, a_text->str);
09153       add_line(resp, hold);   /* Repeat hold for the text stream */
09154    } else if (p->offered_media[SDP_TEXT].offered) {
09155       snprintf(dummy_answer, sizeof(dummy_answer), "m=text 0 RTP/AVP %s\r\n", p->offered_media[SDP_TEXT].text);
09156       add_line(resp, dummy_answer);
09157    }
09158    if (add_t38) {
09159       add_line(resp, m_modem->str);
09160       add_line(resp, a_modem->str);
09161    } else if (p->offered_media[SDP_IMAGE].offered) {
09162       add_line(resp, "m=image 0 udptl t38\r\n");
09163    }
09164 
09165    /* Update lastrtprx when we send our SDP */
09166    p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
09167 
09168    ast_debug(3, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, capability));
09169 
09170    return AST_SUCCESS;
09171 }
09172 
09173 /*! \brief Used for 200 OK and 183 early media */
09174 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
09175 {
09176    struct sip_request resp;
09177    int seqno;
09178    
09179    if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
09180       ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
09181       return -1;
09182    }
09183    respprep(&resp, p, msg, req);
09184    if (p->udptl) {
09185       add_sdp(&resp, p, 0, 0, 1);
09186    } else 
09187       ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
09188    if (retrans && !p->pendinginvite)
09189       p->pendinginvite = seqno;     /* Buggy clients sends ACK on RINGING too */
09190    return send_response(p, &resp, retrans, seqno);
09191 }
09192 
09193 /*! \brief copy SIP request (mostly used to save request for responses) */
09194 static void copy_request(struct sip_request *dst, const struct sip_request *src)
09195 {
09196    struct ast_str *duplicate = dst->data;
09197 
09198    /* First copy stuff */
09199    memcpy(dst, src, sizeof(*dst));
09200    dst->data = duplicate;
09201 
09202    /* All these + 1's are to account for the need to include the NULL terminator
09203     * Using typical string functions like ast_copy_string or ast_str_set will not
09204     * work in this case because the src's data string is riddled with \0's all over
09205     * the place and so a memcpy is the only way to accurately copy the string
09206     */
09207 
09208    if (!dst->data && !(dst->data = ast_str_create(src->data->used + 1)))
09209       return;
09210    else if (dst->data->len < src->data->used + 1)
09211       ast_str_make_space(&dst->data, src->data->used + 1);
09212       
09213    memcpy(dst->data->str, src->data->str, src->data->used + 1);
09214    dst->data->used = src->data->used;
09215 }
09216 
09217 /*! \brief Used for 200 OK and 183 early media 
09218    \return Will return XMIT_ERROR for network errors.
09219 */
09220 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp)
09221 {
09222    struct sip_request resp;
09223    int seqno;
09224    if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
09225       ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
09226       return -1;
09227    }
09228    respprep(&resp, p, msg, req);
09229    if (p->rtp) {
09230       if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
09231          ast_debug(1, "Setting framing from config on incoming call\n");
09232          ast_rtp_codec_setpref(p->rtp, &p->prefs);
09233       }
09234       try_suggested_sip_codec(p);
09235       if (p->t38.state == T38_ENABLED) {
09236          add_sdp(&resp, p, oldsdp, TRUE, TRUE);
09237       } else {
09238          add_sdp(&resp, p, oldsdp, TRUE, FALSE);
09239       }
09240    } else 
09241       ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
09242    if (reliable && !p->pendinginvite)
09243       p->pendinginvite = seqno;     /* Buggy clients sends ACK on RINGING too */
09244    return send_response(p, &resp, reliable, seqno);
09245 }
09246 
09247 /*! \brief Parse first line of incoming SIP request */
09248 static int determine_firstline_parts(struct sip_request *req) 
09249 {
09250    char *e = ast_skip_blanks(req->data->str);   /* there shouldn't be any */
09251    char *local_rlPart1;
09252 
09253    if (!*e)
09254       return -1;
09255    req->rlPart1 = e - req->data->str;  /* method or protocol */
09256    local_rlPart1 = e;
09257    e = ast_skip_nonblanks(e);
09258    if (*e)
09259       *e++ = '\0';
09260    /* Get URI or status code */
09261    e = ast_skip_blanks(e);
09262    if ( !*e )
09263       return -1;
09264    ast_trim_blanks(e);
09265 
09266    if (!strcasecmp(local_rlPart1, "SIP/2.0") ) { /* We have a response */
09267       if (strlen(e) < 3)   /* status code is 3 digits */
09268          return -1;
09269       req->rlPart2 = e - req->data->str;
09270    } else { /* We have a request */
09271       if ( *e == '<' ) { /* XXX the spec says it must not be in <> ! */
09272          ast_debug(3, "Oops. Bogus uri in <> %s\n", e);
09273          e++;
09274          if (!*e)
09275             return -1; 
09276       }
09277       req->rlPart2 = e - req->data->str;  /* URI */
09278       e = ast_skip_nonblanks(e);
09279       if (*e)
09280          *e++ = '\0';
09281       e = ast_skip_blanks(e);
09282       if (strcasecmp(e, "SIP/2.0") ) {
09283          ast_debug(3, "Skipping packet - Bad request protocol %s\n", e);
09284          return -1;
09285       }
09286    }
09287    return 1;
09288 }
09289 
09290 /*! \brief Transmit reinvite with SDP
09291 \note    A re-invite is basically a new INVITE with the same CALL-ID and TAG as the
09292    INVITE that opened the SIP dialogue 
09293    We reinvite so that the audio stream (RTP) go directly between
09294    the SIP UAs. SIP Signalling stays with * in the path.
09295    
09296    If t38version is TRUE, we send T38 SDP for re-invite from audio/video to
09297    T38 UDPTL transmission on the channel
09298 
09299     If oldsdp is TRUE then the SDP version number is not incremented. This
09300     is needed for Session-Timers so we can send a re-invite to refresh the
09301     SIP session without modifying the media session. 
09302 */
09303 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp)
09304 {
09305    struct sip_request req;
09306    
09307    reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ?  SIP_UPDATE : SIP_INVITE, 0, 1);
09308 
09309    add_header(&req, "Allow", ALLOWED_METHODS);
09310    add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
09311    if (sipdebug) {
09312       if (oldsdp == TRUE)
09313          add_header(&req, "X-asterisk-Info", "SIP re-invite (Session-Timers)");
09314       else
09315          add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
09316    }
09317 
09318    if (p->do_history)
09319       append_history(p, "ReInv", "Re-invite sent");
09320    memset(p->offered_media, 0, sizeof(p->offered_media));
09321 
09322    if (t38version)
09323       add_sdp(&req, p, oldsdp, FALSE, TRUE);
09324    else
09325       add_sdp(&req, p, oldsdp, TRUE, FALSE);
09326 
09327    /* Use this as the basis */
09328    initialize_initreq(p, &req);
09329    p->lastinvite = p->ocseq;
09330    ast_set_flag(&p->flags[0], SIP_OUTGOING);       /* Change direction of this dialog */
09331 
09332    return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
09333 }
09334 
09335 /* \brief Remove URI parameters at end of URI, not in username part though */
09336 static char *remove_uri_parameters(char *uri)
09337 {
09338    char *atsign;
09339    atsign = strchr(uri, '@'); /* First, locate the at sign */
09340    if (!atsign)
09341       atsign = uri;  /* Ok hostname only, let's stick with the rest */
09342    atsign = strchr(atsign, ';'); /* Locate semi colon */
09343    if (atsign)
09344       *atsign = '\0';   /* Kill at the semi colon */
09345    return uri;
09346 }
09347 
09348 /*! \brief Check Contact: URI of SIP message */
09349 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
09350 {
09351    char stripped[SIPBUFSIZE];
09352    char *c;
09353 
09354    ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
09355    c = get_in_brackets(stripped);
09356    /* Cut the URI at the at sign after the @, not in the username part */
09357    c = remove_uri_parameters(c);
09358    if (!ast_strlen_zero(c))
09359       ast_string_field_set(p, uri, c);
09360 
09361 }
09362 
09363 /*! \brief Build contact header - the contact header we send out */
09364 static void build_contact(struct sip_pvt *p)
09365 {
09366    int ourport = ntohs(p->ourip.sin_port);
09367    /* only add port if it's non-standard for the transport type */
09368    if (!sip_standard_port(p->socket.type, ourport)) {
09369       if (p->socket.type == SIP_TRANSPORT_UDP)
09370          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);
09371       else
09372          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));
09373    } else {
09374       if (p->socket.type == SIP_TRANSPORT_UDP)
09375          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));
09376       else
09377          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));
09378    }
09379 }
09380 
09381 /*! \brief Build the Remote Party-ID & From using callingpres options */
09382 static void build_rpid(struct sip_pvt *p)
09383 {
09384    int send_pres_tags = TRUE;
09385    const char *privacy=NULL;
09386    const char *screen=NULL;
09387    char buf[256];
09388    const char *clid = default_callerid;
09389    const char *clin = NULL;
09390    const char *fromdomain;
09391 
09392    if (!ast_strlen_zero(p->rpid) || !ast_strlen_zero(p->rpid_from))  
09393       return;
09394 
09395    if (p->owner && p->owner->cid.cid_num)
09396       clid = p->owner->cid.cid_num;
09397    if (p->owner && p->owner->cid.cid_name)
09398       clin = p->owner->cid.cid_name;
09399    if (ast_strlen_zero(clin))
09400       clin = clid;
09401 
09402    switch (p->callingpres) {
09403    case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
09404       privacy = "off";
09405       screen = "no";
09406       break;
09407    case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
09408       privacy = "off";
09409       screen = "yes";
09410       break;
09411    case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
09412       privacy = "off";
09413       screen = "no";
09414       break;
09415    case AST_PRES_ALLOWED_NETWORK_NUMBER:
09416       privacy = "off";
09417       screen = "yes";
09418       break;
09419    case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
09420       privacy = "full";
09421       screen = "no";
09422       break;
09423    case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
09424       privacy = "full";
09425       screen = "yes";
09426       break;
09427    case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
09428       privacy = "full";
09429       screen = "no";
09430       break;
09431    case AST_PRES_PROHIB_NETWORK_NUMBER:
09432       privacy = "full";
09433       screen = "yes";
09434       break;
09435    case AST_PRES_NUMBER_NOT_AVAILABLE:
09436       send_pres_tags = FALSE;
09437       break;
09438    default:
09439       ast_log(LOG_WARNING, "Unsupported callingpres (%d)\n", p->callingpres);
09440       if ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)
09441          privacy = "full";
09442       else
09443          privacy = "off";
09444       screen = "no";
09445       break;
09446    }
09447    
09448    fromdomain = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr));
09449 
09450    snprintf(buf, sizeof(buf), "\"%s\" <sip:%s@%s>", clin, clid, fromdomain);
09451    if (send_pres_tags)
09452       snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ";privacy=%s;screen=%s", privacy, screen);
09453    ast_string_field_set(p, rpid, buf);
09454 
09455    ast_string_field_build(p, rpid_from, "\"%s\" <sip:%s@%s>;tag=%s", clin,
09456                 S_OR(p->fromuser, clid),
09457                 fromdomain, p->tag);
09458 }
09459 
09460 /*! \brief Initiate new SIP request to peer/user */
09461 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod)
09462 {
09463    struct ast_str *invite = ast_str_alloca(256);
09464    char from[256];
09465    char to[256];
09466    char tmp_n[SIPBUFSIZE/2];  /* build a local copy of 'n' if needed */
09467    char tmp_l[SIPBUFSIZE/2];  /* build a local copy of 'l' if needed */
09468    const char *l = NULL;   /* XXX what is this, exactly ? */
09469    const char *n = NULL;   /* XXX what is this, exactly ? */
09470    const char *d = NULL;   /* domain in from header */
09471    const char *urioptions = "";
09472    int ourport;
09473 
09474    if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
09475       const char *s = p->username;  /* being a string field, cannot be NULL */
09476 
09477       /* Test p->username against allowed characters in AST_DIGIT_ANY
09478          If it matches the allowed characters list, then sipuser = ";user=phone"
09479          If not, then sipuser = ""
09480       */
09481       /* + is allowed in first position in a tel: uri */
09482       if (*s == '+')
09483          s++;
09484       for (; *s; s++) {
09485          if (!strchr(AST_DIGIT_ANYNUM, *s) )
09486             break;
09487       }
09488       /* If we have only digits, add ;user=phone to the uri */
09489       if (!*s)
09490          urioptions = ";user=phone";
09491    }
09492 
09493 
09494    snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
09495 
09496    d = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr));
09497    if (p->owner) {
09498       l = p->owner->cid.cid_num;
09499       n = p->owner->cid.cid_name;
09500    }
09501    /* if we are not sending RPID and user wants his callerid restricted */
09502    if (!ast_test_flag(&p->flags[0], SIP_SENDRPID) &&
09503        ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)) {
09504       l = CALLERID_UNKNOWN;
09505       n = l;
09506       d = FROMDOMAIN_INVALID;
09507    }
09508    if (ast_strlen_zero(l))
09509       l = default_callerid;
09510    if (ast_strlen_zero(n))
09511       n = l;
09512    /* Allow user to be overridden */
09513    if (!ast_strlen_zero(p->fromuser))
09514       l = p->fromuser;
09515    else /* Save for any further attempts */
09516       ast_string_field_set(p, fromuser, l);
09517 
09518    /* Allow user to be overridden */
09519    if (!ast_strlen_zero(p->fromname))
09520       n = p->fromname;
09521    else /* Save for any further attempts */
09522       ast_string_field_set(p, fromname, n);
09523 
09524    if (pedanticsipchecking) {
09525       ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
09526       n = tmp_n;
09527       ast_uri_encode(l, tmp_l, sizeof(tmp_l), 0);
09528       l = tmp_l;
09529    }
09530 
09531    ourport = ntohs(p->ourip.sin_port);
09532    if (!sip_standard_port(p->socket.type, ourport) && ast_strlen_zero(p->fromdomain))
09533       snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=%s", n, l, d, ourport, p->tag);
09534    else
09535       snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, l, d, p->tag);
09536 
09537    /* If we're calling a registered SIP peer, use the fullcontact to dial to the peer */
09538    if (!ast_strlen_zero(p->fullcontact)) {
09539       /* If we have full contact, trust it */
09540       ast_str_append(&invite, 0, "%s", p->fullcontact);
09541    } else {
09542       /* Otherwise, use the username while waiting for registration */
09543       ast_str_append(&invite, 0, "sip:");
09544       if (!ast_strlen_zero(p->username)) {
09545          n = p->username;
09546          if (pedanticsipchecking) {
09547             ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
09548             n = tmp_n;
09549          }
09550          ast_str_append(&invite, 0, "%s@", n);
09551       }
09552       ast_str_append(&invite, 0, "%s", p->tohost);
09553       if (ntohs(p->sa.sin_port) != STANDARD_SIP_PORT)
09554          ast_str_append(&invite, 0, ":%d", ntohs(p->sa.sin_port));
09555       ast_str_append(&invite, 0, "%s", urioptions);
09556    }
09557 
09558    /* If custom URI options have been provided, append them */
09559    if (p->options && !ast_strlen_zero(p->options->uri_options))
09560       ast_str_append(&invite, 0, ";%s", p->options->uri_options);
09561    
09562    /* This is the request URI, which is the next hop of the call
09563       which may or may not be the destination of the call
09564    */
09565    ast_string_field_set(p, uri, invite->str);
09566   
09567    if (!ast_strlen_zero(p->todnid)) {
09568       /*! \todo Need to add back the VXML URL here at some point, possibly use build_string for all this junk */
09569       if (!strchr(p->todnid, '@')) {
09570          /* We have no domain in the dnid */
09571          snprintf(to, sizeof(to), "<sip:%s@%s>%s%s", p->todnid, p->tohost, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
09572       } else {
09573          snprintf(to, sizeof(to), "<sip:%s>%s%s", p->todnid, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
09574       }
09575    } else {
09576       if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) { 
09577          /* If this is a NOTIFY, use the From: tag in the subscribe (RFC 3265) */
09578          snprintf(to, sizeof(to), "<%s%s>;tag=%s", (!strncasecmp(p->uri, "sip:", 4) ? "sip:" : ""), p->uri, p->theirtag);
09579       } else if (p->options && p->options->vxml_url) {
09580          /* If there is a VXML URL append it to the SIP URL */
09581          snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
09582       } else 
09583          snprintf(to, sizeof(to), "<%s>", p->uri);
09584    }
09585 
09586    init_req(req, sipmethod, p->uri);
09587    /* now tmp_n is available so reuse it to build the CSeq */
09588    snprintf(tmp_n, sizeof(tmp_n), "%d %s", ++p->ocseq, sip_methods[sipmethod].text);
09589 
09590    add_header(req, "Via", p->via);
09591    add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
09592    /* This will be a no-op most of the time. However, under certain circumstances,
09593     * NOTIFY messages will use this function for preparing the request and should
09594     * have Route headers present.
09595     */
09596    add_route(req, p->route);
09597 
09598    /* Build Remote Party-ID and From */
09599    if (ast_test_flag(&p->flags[0], SIP_SENDRPID) && (sipmethod == SIP_INVITE)) {
09600       build_rpid(p);
09601       add_header(req, "From", p->rpid_from);
09602    } else 
09603       add_header(req, "From", from);
09604    add_header(req, "To", to);
09605    ast_string_field_set(p, exten, l);
09606    build_contact(p);
09607    add_header(req, "Contact", p->our_contact);
09608    add_header(req, "Call-ID", p->callid);
09609    add_header(req, "CSeq", tmp_n);
09610    if (!ast_strlen_zero(global_useragent))
09611       add_header(req, "User-Agent", global_useragent);
09612    if (!ast_strlen_zero(p->rpid))
09613       add_header(req, "Remote-Party-ID", p->rpid);
09614 }
09615 
09616 /*! \brief Build REFER/INVITE/OPTIONS message and transmit it 
09617    \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
09618  \param p sip_pvt structure
09619  \param sdp unknown 
09620  \param sipmethod unknown 
09621  
09622 */
09623 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init)
09624 {
09625    struct sip_request req;
09626    struct ast_variable *var;
09627    
09628    req.method = sipmethod;
09629    if (init) {/* Bump branch even on initial requests */
09630       p->branch ^= ast_random();
09631       p->invite_branch = p->branch;
09632       build_via(p);
09633    }
09634    if (init > 1)
09635       initreqprep(&req, p, sipmethod);
09636    else
09637       /* If init=1, we should not generate a new branch. If it's 0, we need a new branch. */
09638       reqprep(&req, p, sipmethod, 0, init ? 0 : 1);
09639       
09640    if (p->options && p->options->auth)
09641       add_header(&req, p->options->authheader, p->options->auth);
09642    append_date(&req);
09643    if (sipmethod == SIP_REFER) { /* Call transfer */
09644       if (p->refer) {
09645          char buf[SIPBUFSIZE];
09646          if (!ast_strlen_zero(p->refer->refer_to))
09647             add_header(&req, "Refer-To", p->refer->refer_to);
09648          if (!ast_strlen_zero(p->refer->referred_by)) {
09649             snprintf(buf, sizeof(buf), "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
09650             add_header(&req, "Referred-By", buf);
09651          }
09652       }
09653    }
09654    /* This new INVITE is part of an attended transfer. Make sure that the
09655    other end knows and replace the current call with this new call */
09656    if (p->options && !ast_strlen_zero(p->options->replaces)) {
09657       add_header(&req, "Replaces", p->options->replaces);
09658       add_header(&req, "Require", "replaces");
09659    }
09660 
09661    /* Add Session-Timers related headers */
09662    if (st_get_mode(p) == SESSION_TIMER_MODE_ORIGINATE) {
09663       char i2astr[10];
09664 
09665       if (!p->stimer->st_interval)
09666          p->stimer->st_interval = st_get_se(p, TRUE);
09667 
09668       p->stimer->st_active = TRUE;
09669       
09670       snprintf(i2astr, sizeof(i2astr), "%d", p->stimer->st_interval);
09671       add_header(&req, "Session-Expires", i2astr);
09672       snprintf(i2astr, sizeof(i2astr), "%d", st_get_se(p, FALSE));
09673       add_header(&req, "Min-SE", i2astr);
09674    }
09675 
09676    add_header(&req, "Allow", ALLOWED_METHODS);
09677    add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
09678 
09679    if(p->notify_headers) {
09680       char buf[512];
09681       for (var = p->notify_headers; var; var = var->next) {
09682          ast_copy_string(buf, var->value, sizeof(buf));
09683          add_header(&req, var->name, ast_unescape_semicolon(buf));
09684       }
09685    }
09686    if (p->options && p->options->addsipheaders && p->owner) {
09687       struct ast_channel *chan = p->owner; /* The owner channel */
09688       struct varshead *headp;
09689    
09690       ast_channel_lock(chan);
09691 
09692       headp = &chan->varshead;
09693 
09694       if (!headp)
09695          ast_log(LOG_WARNING, "No Headp for the channel...ooops!\n");
09696       else {
09697          const struct ast_var_t *current;
09698          AST_LIST_TRAVERSE(headp, current, entries) {  
09699             /* SIPADDHEADER: Add SIP header to outgoing call */
09700             if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
09701                char *content, *end;
09702                const char *header = ast_var_value(current);
09703                char *headdup = ast_strdupa(header);
09704 
09705                /* Strip of the starting " (if it's there) */
09706                if (*headdup == '"')
09707                   headdup++;
09708                if ((content = strchr(headdup, ':'))) {
09709                   *content++ = '\0';
09710                   content = ast_skip_blanks(content); /* Skip white space */
09711                   /* Strip the ending " (if it's there) */
09712                   end = content + strlen(content) -1; 
09713                   if (*end == '"')
09714                      *end = '\0';
09715                
09716                   add_header(&req, headdup, content);
09717                   if (sipdebug)
09718                      ast_debug(1, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
09719                }
09720             }
09721          }
09722       }
09723 
09724       ast_channel_unlock(chan);
09725    }
09726    if (sdp) {
09727       memset(p->offered_media, 0, sizeof(p->offered_media));
09728       if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
09729          ast_debug(1, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
09730          add_sdp(&req, p, FALSE, FALSE, TRUE);
09731       } else if (p->rtp) 
09732          add_sdp(&req, p, FALSE, TRUE, FALSE);
09733    } else {
09734       if (!p->notify_headers) {
09735          add_header_contentLength(&req, 0);
09736       }
09737    }
09738 
09739    if (!p->initreq.headers || init > 2)
09740       initialize_initreq(p, &req);
09741    p->lastinvite = p->ocseq;
09742    return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
09743 }
09744 
09745 /*! \brief Used in the SUBSCRIBE notification subsystem (RFC3265) */
09746 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
09747 {
09748    struct ast_str *tmp = ast_str_alloca(4000);
09749    char from[256], to[256];
09750    char *c, *mfrom, *mto;
09751    struct sip_request req;
09752    char hint[AST_MAX_EXTENSION];
09753    char *statestring = "terminated";
09754    const struct cfsubscription_types *subscriptiontype;
09755    enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
09756    char *pidfstate = "--";
09757    char *pidfnote= "Ready";
09758    
09759    memset(from, 0, sizeof(from));
09760    memset(to, 0, sizeof(to));
09761 
09762    switch (state) {
09763    case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
09764       statestring = (global_notifyringing) ? "early" : "confirmed";
09765       local_state = NOTIFY_INUSE;
09766       pidfstate = "busy";
09767       pidfnote = "Ringing";
09768       break;
09769    case AST_EXTENSION_RINGING:
09770       statestring = "early";
09771       local_state = NOTIFY_INUSE;
09772       pidfstate = "busy";
09773       pidfnote = "Ringing";
09774       break;
09775    case AST_EXTENSION_INUSE:
09776       statestring = "confirmed";
09777       local_state = NOTIFY_INUSE;
09778       pidfstate = "busy";
09779       pidfnote = "On the phone";
09780       break;
09781    case AST_EXTENSION_BUSY:
09782       statestring = "confirmed";
09783       local_state = NOTIFY_CLOSED;
09784       pidfstate = "busy";
09785       pidfnote = "On the phone";
09786       break;
09787    case AST_EXTENSION_UNAVAILABLE:
09788       statestring = "terminated";
09789       local_state = NOTIFY_CLOSED;
09790       pidfstate = "away";
09791       pidfnote = "Unavailable";
09792       break;
09793    case AST_EXTENSION_ONHOLD:
09794       statestring = "confirmed";
09795       local_state = NOTIFY_CLOSED;
09796       pidfstate = "busy";
09797       pidfnote = "On hold";
09798       break;
09799    case AST_EXTENSION_NOT_INUSE:
09800    default:
09801       /* Default setting */
09802       break;
09803    }
09804 
09805    subscriptiontype = find_subscription_type(p->subscribed);
09806    
09807    /* Check which device/devices we are watching  and if they are registered */
09808    if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten)) {
09809       char *hint2 = hint, *individual_hint = NULL;
09810       int hint_count = 0, unavailable_count = 0;
09811 
09812       while ((individual_hint = strsep(&hint2, "&"))) {
09813          hint_count++;
09814 
09815          if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
09816             unavailable_count++;
09817       }
09818 
09819       /* If none of the hinted devices are registered, we will
09820        * override notification and show no availability.
09821        */
09822       if (hint_count > 0 && hint_count == unavailable_count) {
09823          local_state = NOTIFY_CLOSED;
09824          pidfstate = "away";
09825          pidfnote = "Not online";
09826       }
09827    }
09828 
09829    ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
09830    c = get_in_brackets(from);
09831    if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
09832       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
09833       return -1;
09834    }
09835    
09836    mfrom = remove_uri_parameters(c);
09837 
09838    ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
09839    c = get_in_brackets(to);
09840    if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
09841       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
09842       return -1;
09843    }
09844    mto = remove_uri_parameters(c);
09845 
09846    reqprep(&req, p, SIP_NOTIFY, 0, 1);
09847 
09848    
09849    add_header(&req, "Event", subscriptiontype->event);
09850    add_header(&req, "Content-Type", subscriptiontype->mediatype);
09851    switch(state) {
09852    case AST_EXTENSION_DEACTIVATED:
09853       if (timeout)
09854          add_header(&req, "Subscription-State", "terminated;reason=timeout");
09855       else {
09856          add_header(&req, "Subscription-State", "terminated;reason=probation");
09857          add_header(&req, "Retry-After", "60");
09858       }
09859       break;
09860    case AST_EXTENSION_REMOVED:
09861       add_header(&req, "Subscription-State", "terminated;reason=noresource");
09862       break;
09863    default:
09864       if (p->expiry)
09865          add_header(&req, "Subscription-State", "active");
09866       else  /* Expired */
09867          add_header(&req, "Subscription-State", "terminated;reason=timeout");
09868    }
09869    switch (p->subscribed) {
09870    case XPIDF_XML:
09871    case CPIM_PIDF_XML:
09872       ast_str_append(&tmp, 0,
09873          "<?xml version=\"1.0\"?>\n"
09874          "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n"
09875          "<presence>\n");
09876       ast_str_append(&tmp, 0, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
09877       ast_str_append(&tmp, 0, "<atom id=\"%s\">\n", p->exten);
09878       ast_str_append(&tmp, 0, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
09879       ast_str_append(&tmp, 0, "<status status=\"%s\" />\n", (local_state ==  NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
09880       ast_str_append(&tmp, 0, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
09881       ast_str_append(&tmp, 0, "</address>\n</atom>\n</presence>\n");
09882       break;
09883    case PIDF_XML: /* Eyebeam supports this format */
09884       ast_str_append(&tmp, 0,
09885          "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
09886          "<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);
09887       ast_str_append(&tmp, 0, "<pp:person><status>\n");
09888       if (pidfstate[0] != '-')
09889          ast_str_append(&tmp, 0, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
09890       ast_str_append(&tmp, 0, "</status></pp:person>\n");
09891       ast_str_append(&tmp, 0, "<note>%s</note>\n", pidfnote); /* Note */
09892       ast_str_append(&tmp, 0, "<tuple id=\"%s\">\n", p->exten); /* Tuple start */
09893       ast_str_append(&tmp, 0, "<contact priority=\"1\">%s</contact>\n", mto);
09894       if (pidfstate[0] == 'b') /* Busy? Still open ... */
09895          ast_str_append(&tmp, 0, "<status><basic>open</basic></status>\n");
09896       else
09897          ast_str_append(&tmp, 0, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
09898       ast_str_append(&tmp, 0, "</tuple>\n</presence>\n");
09899       break;
09900    case DIALOG_INFO_XML: /* SNOM subscribes in this format */
09901       ast_str_append(&tmp, 0, "<?xml version=\"1.0\"?>\n");
09902       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);
09903       if ((state & AST_EXTENSION_RINGING) && global_notifyringing)
09904          ast_str_append(&tmp, 0, "<dialog id=\"%s\" direction=\"recipient\">\n", p->exten);
09905       else
09906          ast_str_append(&tmp, 0, "<dialog id=\"%s\">\n", p->exten);
09907       ast_str_append(&tmp, 0, "<state>%s</state>\n", statestring);
09908       if (state == AST_EXTENSION_ONHOLD) {
09909          ast_str_append(&tmp, 0, "<local>\n<target uri=\"%s\">\n"
09910                                          "<param pname=\"+sip.rendering\" pvalue=\"no\"/>\n"
09911                                          "</target>\n</local>\n", mto);
09912       }
09913       ast_str_append(&tmp, 0, "</dialog>\n</dialog-info>\n");
09914       break;
09915    case NONE:
09916    default:
09917       break;
09918    }
09919 
09920    add_header_contentLength(&req, tmp->used);
09921    add_line(&req, tmp->str);
09922 
09923    p->pendinginvite = p->ocseq;  /* Remember that we have a pending NOTIFY in order not to confuse the NOTIFY subsystem */
09924 
09925    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
09926 }
09927 
09928 /*! \brief Notify user of messages waiting in voicemail (RFC3842)
09929 \note - Notification only works for registered peers with mailbox= definitions
09930    in sip.conf
09931    - We use the SIP Event package message-summary
09932     MIME type defaults to  "application/simple-message-summary";
09933  */
09934 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten)
09935 {
09936    struct sip_request req;
09937    struct ast_str *out = ast_str_alloca(500);
09938    int ourport = ntohs(p->ourip.sin_port);
09939    const char *exten = S_OR(vmexten, default_vmexten);
09940 
09941    initreqprep(&req, p, SIP_NOTIFY);
09942    add_header(&req, "Event", "message-summary");
09943    add_header(&req, "Content-Type", default_notifymime);
09944    ast_str_append(&out, 0, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
09945 
09946    if (!ast_strlen_zero(p->fromdomain)) {
09947       ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, p->fromdomain);
09948    } else if (!sip_standard_port(p->socket.type, ourport)) {
09949       if (p->socket.type == SIP_TRANSPORT_UDP) {
09950          ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr), ourport);
09951       } else {
09952          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));
09953       }
09954    } else {
09955       if (p->socket.type == SIP_TRANSPORT_UDP) {
09956          ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr));
09957       } else {
09958          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));
09959       }
09960    }
09961    /* Cisco has a bug in the SIP stack where it can't accept the
09962       (0/0) notification. This can temporarily be disabled in
09963       sip.conf with the "buggymwi" option */
09964    ast_str_append(&out, 0, "Voice-Message: %d/%d%s\r\n",
09965       newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));
09966 
09967    if (p->subscribed) {
09968       if (p->expiry)
09969          add_header(&req, "Subscription-State", "active");
09970       else  /* Expired */
09971          add_header(&req, "Subscription-State", "terminated;reason=timeout");
09972    }
09973 
09974    add_header_contentLength(&req, out->used);
09975    add_line(&req, out->str);
09976 
09977    if (!p->initreq.headers) 
09978       initialize_initreq(p, &req);
09979    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
09980 }
09981 
09982 /*! \brief Notify a transferring party of the status of transfer (RFC3515) */
09983 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
09984 {
09985    struct sip_request req;
09986    char tmp[SIPBUFSIZE/2];
09987    
09988    reqprep(&req, p, SIP_NOTIFY, 0, 1);
09989    snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
09990    add_header(&req, "Event", tmp);
09991    add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
09992    add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
09993    add_header(&req, "Allow", ALLOWED_METHODS);
09994    add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
09995 
09996    snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
09997    add_header_contentLength(&req, strlen(tmp));
09998    add_line(&req, tmp);
09999 
10000    if (!p->initreq.headers)
10001       initialize_initreq(p, &req);
10002 
10003    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
10004 }
10005 
10006 /*! \brief Notify device with custom headers from sip_notify.conf */
10007 static int transmit_notify_custom(struct sip_pvt *p, struct ast_variable *vars) {
10008    struct sip_request req;
10009    struct ast_variable *var, *newvar;
10010 
10011    initreqprep(&req, p, SIP_NOTIFY);
10012 
10013    /* Copy notify vars and add headers */
10014    p->notify_headers = newvar = ast_variable_new("Subscription-State", "terminated", "");
10015    add_header(&req, newvar->name, newvar->value);
10016    for (var = vars; var; var = var->next) {
10017       char buf[512];
10018       ast_debug(2, "  Adding pair %s=%s\n", var->name, var->value);
10019       ast_copy_string(buf, var->value, sizeof(buf));
10020       add_header(&req, var->name, ast_unescape_semicolon(buf));
10021       newvar->next = ast_variable_new(var->name, var->value, "");
10022       newvar = newvar->next;
10023    }
10024 
10025    if (!p->initreq.headers) { /* Initialize first request before sending */
10026       initialize_initreq(p, &req);
10027    }
10028 
10029    return send_request(p, &req, XMIT_UNRELIABLE, p->ocseq);
10030 }
10031 
10032 static int manager_sipnotify(struct mansession *s, const struct message *m)
10033 {
10034    const char *channame = astman_get_header(m, "Channel");
10035    struct ast_variable *vars = astman_get_variables(m);
10036    struct sip_pvt *p;
10037 
10038    if (ast_strlen_zero(channame)) {
10039       astman_send_error(s, m, "SIPNotify requires a channel name");
10040       return 0;
10041    }
10042 
10043    if (!strncasecmp(channame, "sip/", 4)) {
10044       channame += 4;
10045    }
10046 
10047    if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
10048       astman_send_error(s, m, "Unable to build sip pvt data for notify (memory/socket error)");
10049       return 0;
10050    }
10051 
10052    if (create_addr(p, channame, NULL, 0)) {
10053       /* Maybe they're not registered, etc. */
10054       dialog_unlink_all(p, TRUE, TRUE);
10055       dialog_unref(p, "unref dialog inside for loop" );
10056       /* sip_destroy(p); */
10057       astman_send_error(s, m, "Could not create address");
10058       return 0;
10059    }
10060 
10061    /* Notify is outgoing call */
10062    ast_set_flag(&p->flags[0], SIP_OUTGOING);
10063 
10064    /* Recalculate our side, and recalculate Call ID */
10065    ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
10066    build_via(p);
10067    ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
10068    build_callid_pvt(p);
10069    ao2_t_link(dialogs, p, "Linking in new name");
10070    dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
10071    sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
10072 
10073    if (!transmit_notify_custom(p, vars)) {
10074       astman_send_ack(s, m, "Notify Sent");
10075    } else {
10076       astman_send_error(s, m, "Unable to send notify");
10077    }
10078    ast_variables_destroy(vars);
10079    return 0;
10080 }
10081 
10082 static char mandescr_sipnotify[] =
10083 "Description: Sends a SIP Notify event\n"
10084 "All parameters for this event must be specified in the body of this request\n"
10085 "via multiple Variable: name=value sequences.\n"
10086 "Variables: \n"
10087 "  *Channel: <peername>       Peer to receive the notify. Required.\n"
10088 "  *Variable: <name>=<value>  At least one variable pair must be specified.\n"
10089 "  ActionID: <id>             Action ID for this transaction. Will be returned.\n";
10090 
10091 static const struct _map_x_s regstatestrings[] = {
10092    { REG_STATE_FAILED,     "Failed" },
10093    { REG_STATE_UNREGISTERED, "Unregistered"},
10094    { REG_STATE_REGSENT, "Request Sent"},
10095    { REG_STATE_AUTHSENT, "Auth. Sent"},
10096    { REG_STATE_REGISTERED, "Registered"},
10097    { REG_STATE_REJECTED, "Rejected"},
10098    { REG_STATE_TIMEOUT, "Timeout"},
10099    { REG_STATE_NOAUTH, "No Authentication"},
10100    { -1, NULL } /* terminator */
10101 };
10102 
10103 /*! \brief Convert registration state status to string */
10104 static const char *regstate2str(enum sipregistrystate regstate)
10105 {
10106    return map_x_s(regstatestrings, regstate, "Unknown");
10107 }
10108 
10109 /*! \brief Update registration with SIP Proxy.
10110  * Called from the scheduler when the previous registration expires,
10111  * so we don't have to cancel the pending event.
10112  * We assume the reference so the sip_registry is valid, since it
10113  * is stored in the scheduled event anyways.
10114  */
10115 static int sip_reregister(const void *data) 
10116 {
10117    /* if we are here, we know that we need to reregister. */
10118    struct sip_registry *r= (struct sip_registry *) data;
10119 
10120    /* if we couldn't get a reference to the registry object, punt */
10121    if (!r)
10122       return 0;
10123 
10124    if (r->call && r->call->do_history)
10125       append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
10126    /* Since registry's are only added/removed by the the monitor thread, this
10127       may be overkill to reference/dereference at all here */
10128    if (sipdebug)
10129       ast_log(LOG_NOTICE, "   -- Re-registration for  %s@%s\n", r->username, r->hostname);
10130 
10131    r->expire = -1;
10132    __sip_do_register(r);
10133    registry_unref(r, "unref the re-register scheduled event");
10134    return 0;
10135 }
10136 
10137 /*! \brief Register with SIP proxy */
10138 static int __sip_do_register(struct sip_registry *r)
10139 {
10140    int res;
10141 
10142    res = transmit_register(r, SIP_REGISTER, NULL, NULL);
10143    return res;
10144 }
10145 
10146 /*! \brief Registration timeout, register again
10147  * Registered as a timeout handler during transmit_register(),
10148  * to retransmit the packet if a reply does not come back.
10149  * This is called by the scheduler so the event is not pending anymore when
10150  * we are called.
10151  */
10152 static int sip_reg_timeout(const void *data)
10153 {
10154 
10155    /* if we are here, our registration timed out, so we'll just do it over */
10156    struct sip_registry *r = (struct sip_registry *)data; /* the ref count should have been bumped when the sched item was added */
10157    struct sip_pvt *p;
10158    int res;
10159 
10160    /* if we couldn't get a reference to the registry object, punt */
10161    if (!r)
10162       return 0;
10163 
10164    if (r->dnsmgr) {
10165       /* If the registration has timed out, maybe the IP changed.  Force a refresh. */
10166       ast_dnsmgr_refresh(r->dnsmgr);
10167    }
10168 
10169    ast_log(LOG_NOTICE, "   -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts); 
10170    /* If the initial tranmission failed, we may not have an existing dialog,
10171     * so it is possible that r->call == NULL.
10172     * Otherwise destroy it, as we have a timeout so we don't want it.
10173     */
10174    if (r->call) {
10175       /* Unlink us, destroy old call.  Locking is not relevant here because all this happens
10176          in the single SIP manager thread. */
10177       p = r->call;
10178       sip_pvt_lock(p);
10179       p->needdestroy = 1;
10180       /* Pretend to ACK anything just in case */
10181       __sip_pretend_ack(p);
10182       sip_pvt_unlock(p);
10183 
10184       /* decouple the two objects */
10185       /* p->registry == r, so r has 2 refs, and the unref won't take the object away */
10186       if (p->registry)
10187          p->registry = registry_unref(p->registry, "p->registry unreffed");
10188       r->call = dialog_unref(r->call, "unrefing r->call");
10189    }
10190    /* If we have a limit, stop registration and give up */
10191    if (global_regattempts_max && r->regattempts > global_regattempts_max) {
10192       /* Ok, enough is enough. Don't try any more */
10193       /* We could add an external notification here... 
10194          steal it from app_voicemail :-) */
10195       ast_log(LOG_NOTICE, "   -- Giving up forever trying to register '%s@%s'\n", r->username, r->hostname);
10196       r->regstate = REG_STATE_FAILED;
10197    } else {
10198       r->regstate = REG_STATE_UNREGISTERED;
10199       r->timeout = -1;
10200       res=transmit_register(r, SIP_REGISTER, NULL, NULL);
10201    }
10202    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));
10203    registry_unref(r, "unreffing registry_unref r");
10204    return 0;
10205 }
10206 
10207 /*! \brief Transmit register to SIP proxy or UA
10208  * auth = NULL on the initial registration (from sip_reregister())
10209  */
10210 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
10211 {
10212    struct sip_request req;
10213    char from[256];
10214    char to[256];
10215    char tmp[80];
10216    char addr[80];
10217    struct sip_pvt *p;
10218    struct sip_peer *peer;
10219    int res;
10220    char *fromdomain;
10221 
10222    /* exit if we are already in process with this registrar ?*/
10223    if (r == NULL || ((auth == NULL) && (r->regstate == REG_STATE_REGSENT || r->regstate == REG_STATE_AUTHSENT))) {
10224       if (r) {
10225          ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
10226       }
10227       return 0;
10228    }
10229 
10230    if (r->dnsmgr == NULL) {
10231       char transport[MAXHOSTNAMELEN];
10232       peer = find_peer(r->hostname, NULL, TRUE, FINDPEERS, FALSE);
10233       snprintf(transport, sizeof(transport), "_sip._%s", get_transport(r->transport)); /* have to use static get_transport function */
10234       ast_dnsmgr_lookup(peer ? peer->tohost : r->hostname, &r->us, &r->dnsmgr, global_srvlookup ? transport : NULL);
10235       if (peer) {
10236          unref_peer(peer, "removing peer ref for dnsmgr_lookup");
10237       }
10238    }
10239 
10240    if (r->call) { /* We have a registration */
10241       if (!auth) {
10242          ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
10243          return 0;
10244       } else {
10245          p = dialog_ref(r->call, "getting a copy of the r->call dialog in transmit_register");
10246          make_our_tag(p->tag, sizeof(p->tag));  /* create a new local tag for every register attempt */
10247          ast_string_field_set(p, theirtag, NULL);  /* forget their old tag, so we don't match tags when getting response */
10248       }
10249    } else {
10250       /* Build callid for registration if we haven't registered before */
10251       struct sip_peer *peer = NULL;
10252 
10253       if (!r->callid_valid) {
10254          build_callid_registry(r, internip.sin_addr, default_fromdomain);
10255          r->callid_valid = TRUE;
10256       }
10257       /* Allocate SIP dialog for registration */
10258       if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER, NULL))) {
10259          ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
10260          return 0;
10261       }
10262       
10263       if (p->do_history)
10264          append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
10265 
10266       if (!ast_strlen_zero(r->peername)) {
10267          if (!(peer = find_peer(r->peername, NULL, 1, FINDPEERS, FALSE))) {
10268             ast_log(LOG_WARNING, "Could not find peer %s in transmit_register\n", r->peername);
10269          }
10270       }
10271       ref_proxy(p, obproxy_get(p, peer)); /* it is ok to pass a NULL peer into obproxy_get() */
10272       if (peer) {
10273          unref_peer(peer, "transmit_registration: from find_peer operation");
10274       }
10275       /* Use port number specified if no SRV record was found */
10276       if (!r->us.sin_port && r->portno)
10277          r->us.sin_port = htons(r->portno);
10278 
10279       /* Find address to hostname */
10280       if (create_addr(p, r->hostname, &r->us, 0)) {
10281          /* we have what we hope is a temporary network error,
10282           * probably DNS.  We need to reschedule a registration try */
10283          dialog_unlink_all(p, TRUE, TRUE);
10284          p = dialog_unref(p, "unref dialog after unlink_all");
10285          if (r->timeout > -1) {
10286             AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
10287                               registry_unref(_data, "del for REPLACE of registry ptr"), 
10288                               registry_unref(r, "object ptr dec when SCHED_REPLACE add failed"),
10289                               registry_addref(r,"add for REPLACE registry ptr"));
10290             ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
10291          } else {
10292             r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, registry_addref(r, "add for REPLACE registry ptr"));
10293             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);
10294          }
10295          r->regattempts++;
10296          return 0;
10297       }
10298 
10299       /* Copy back Call-ID in case create_addr changed it */
10300       ast_string_field_set(r, callid, p->callid);
10301       if (!r->dnsmgr && r->portno) {
10302          p->sa.sin_port = htons(r->portno);
10303          p->recv.sin_port = htons(r->portno);
10304       } else { /* Set registry port to the port set from the peer definition/srv or default */
10305          r->portno = ntohs(p->sa.sin_port);
10306       }
10307       ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Registration is outgoing call */
10308       r->call = dialog_ref(p, "copying dialog into registry r->call");     /* Save pointer to SIP dialog */
10309       p->registry = registry_addref(r, "transmit_register: addref to p->registry in transmit_register"); /* Add pointer to registry in packet */
10310       if (!ast_strlen_zero(r->secret)) /* Secret (password) */
10311          ast_string_field_set(p, peersecret, r->secret);
10312       if (!ast_strlen_zero(r->md5secret))
10313          ast_string_field_set(p, peermd5secret, r->md5secret);
10314       /* User name in this realm  
10315       - if authuser is set, use that, otherwise use username */
10316       if (!ast_strlen_zero(r->authuser)) {   
10317          ast_string_field_set(p, peername, r->authuser);
10318          ast_string_field_set(p, authname, r->authuser);
10319       } else if (!ast_strlen_zero(r->username)) {
10320          ast_string_field_set(p, peername, r->username);
10321          ast_string_field_set(p, authname, r->username);
10322          ast_string_field_set(p, fromuser, r->username);
10323       }
10324       if (!ast_strlen_zero(r->username))
10325          ast_string_field_set(p, username, r->username);
10326       /* Save extension in packet */
10327       if (!ast_strlen_zero(r->callback))
10328          ast_string_field_set(p, exten, r->callback);
10329 
10330       /* Set transport and port so the correct contact is built */
10331       set_socket_transport(&p->socket, r->transport);
10332       if (r->transport == SIP_TRANSPORT_TLS || r->transport == SIP_TRANSPORT_TCP) {
10333          p->socket.port = sip_tcp_desc.local_address.sin_port;
10334       }
10335 
10336       /*
10337         check which address we should use in our contact header 
10338         based on whether the remote host is on the external or
10339         internal network so we can register through nat
10340        */
10341       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
10342       build_contact(p);
10343    }
10344 
10345    /* set up a timeout */
10346    if (auth == NULL)  {
10347       if (r->timeout > -1)
10348          ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
10349       AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
10350                         registry_unref(_data,"reg ptr unrefed from del in SCHED_REPLACE"),
10351                         registry_unref(r,"reg ptr unrefed from add failure in SCHED_REPLACE"),
10352                         registry_addref(r,"reg ptr reffed from add in SCHED_REPLACE"));
10353       ast_debug(1, "Scheduled a registration timeout for %s id  #%d \n", r->hostname, r->timeout);
10354    }
10355 
10356    if ((fromdomain = strchr(r->username, '@'))) {
10357       /* the domain name is just behind '@' */
10358       fromdomain++ ;
10359       /* We have a domain in the username for registration */
10360       snprintf(from, sizeof(from), "<sip:%s>;tag=%s", r->username, p->tag);
10361       if (!ast_strlen_zero(p->theirtag))
10362          snprintf(to, sizeof(to), "<sip:%s>;tag=%s", r->username, p->theirtag);
10363       else
10364          snprintf(to, sizeof(to), "<sip:%s>", r->username);
10365 
10366       /* If the registration username contains '@', then the domain should be used as
10367          the equivalent of "fromdomain" for the registration */
10368       if (ast_strlen_zero(p->fromdomain)) {
10369          ast_string_field_set(p, fromdomain, fromdomain);
10370       }
10371    } else {
10372       snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->tag);
10373       if (!ast_strlen_zero(p->theirtag))
10374          snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->theirtag);
10375       else
10376          snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, p->tohost);
10377    }
10378    
10379    /* Fromdomain is what we are registering to, regardless of actual
10380       host name from SRV */
10381    if (!ast_strlen_zero(p->fromdomain)) {
10382       if (r->portno && r->portno != STANDARD_SIP_PORT)
10383          snprintf(addr, sizeof(addr), "sip:%s:%d", p->fromdomain, r->portno);
10384       else
10385          snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
10386    } else {
10387       if (r->portno && r->portno != STANDARD_SIP_PORT)
10388          snprintf(addr, sizeof(addr), "sip:%s:%d", r->hostname, r->portno);
10389       else
10390          snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
10391    }
10392    ast_string_field_set(p, uri, addr);
10393 
10394    p->branch ^= ast_random();
10395 
10396    init_req(&req, sipmethod, addr);
10397 
10398    /* Add to CSEQ */
10399    snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
10400    p->ocseq = r->ocseq;
10401 
10402    build_via(p);
10403    add_header(&req, "Via", p->via);
10404    add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
10405    add_header(&req, "From", from);
10406    add_header(&req, "To", to);
10407    add_header(&req, "Call-ID", p->callid);
10408    add_header(&req, "CSeq", tmp);
10409    if (!ast_strlen_zero(global_useragent))
10410       add_header(&req, "User-Agent", global_useragent);
10411 
10412    
10413    if (auth)   /* Add auth header */
10414       add_header(&req, authheader, auth);
10415    else if (!ast_strlen_zero(r->nonce)) {
10416       char digest[1024];
10417 
10418       /* We have auth data to reuse, build a digest header.
10419        * Note, this is not always useful because some parties do not
10420        * like nonces to be reused (for good reasons!) so they will
10421        * challenge us anyways.
10422        */
10423       if (sipdebug)
10424          ast_debug(1, "   >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
10425       ast_string_field_set(p, realm, r->realm);
10426       ast_string_field_set(p, nonce, r->nonce);
10427       ast_string_field_set(p, domain, r->domain);
10428       ast_string_field_set(p, opaque, r->opaque);
10429       ast_string_field_set(p, qop, r->qop);
10430       p->noncecount = ++r->noncecount;
10431 
10432       memset(digest, 0, sizeof(digest));
10433       if(!build_reply_digest(p, sipmethod, digest, sizeof(digest)))
10434          add_header(&req, "Authorization", digest);
10435       else
10436          ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
10437    
10438    }
10439 
10440    snprintf(tmp, sizeof(tmp), "%d", r->expiry);
10441    add_header(&req, "Expires", tmp);
10442    add_header(&req, "Contact", p->our_contact);
10443    add_header_contentLength(&req, 0);
10444 
10445    initialize_initreq(p, &req);
10446    if (sip_debug_test_pvt(p)) {
10447       ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
10448    }
10449    r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
10450    r->regattempts++; /* Another attempt */
10451    ast_debug(4, "REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
10452    res = send_request(p, &req, XMIT_CRITICAL, p->ocseq);
10453    dialog_unref(p, "p is finished here at the end of transmit_register");
10454    return res;
10455 }
10456 
10457 /*! \brief Transmit text with SIP MESSAGE method */
10458 static int transmit_message_with_text(struct sip_pvt *p, const char *text)
10459 {
10460    struct sip_request req;
10461    
10462    reqprep(&req, p, SIP_MESSAGE, 0, 1);
10463    add_text(&req, text);
10464    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
10465 }
10466 
10467 /*! \brief Allocate SIP refer structure */
10468 static int sip_refer_allocate(struct sip_pvt *p)
10469 {
10470    p->refer = ast_calloc(1, sizeof(struct sip_refer)); 
10471    return p->refer ? 1 : 0;
10472 }
10473 
10474 /*! \brief Transmit SIP REFER message (initiated by the transfer() dialplan application
10475    \note this is currently broken as we have no way of telling the dialplan
10476    engine whether a transfer succeeds or fails.
10477    \todo Fix the transfer() dialplan function so that a transfer may fail
10478 */
10479 static int transmit_refer(struct sip_pvt *p, const char *dest)
10480 {
10481    struct sip_request req = { 
10482       .headers = 0,  
10483    };
10484    char from[256];
10485    const char *of;
10486    char *c;
10487    char referto[256];
10488    char *ttag, *ftag;
10489    char *theirtag = ast_strdupa(p->theirtag);
10490 
10491    if (sipdebug)
10492       ast_debug(1, "SIP transfer of %s to %s\n", p->callid, dest);
10493 
10494    /* Are we transfering an inbound or outbound call ? */
10495    if (ast_test_flag(&p->flags[0], SIP_OUTGOING))  {
10496       of = get_header(&p->initreq, "To");
10497       ttag = theirtag;
10498       ftag = p->tag;
10499    } else {
10500       of = get_header(&p->initreq, "From");
10501       ftag = theirtag;
10502       ttag = p->tag;
10503    }
10504 
10505    ast_copy_string(from, of, sizeof(from));
10506    of = get_in_brackets(from);
10507    ast_string_field_set(p, from, of);
10508    if (!strncasecmp(of, "sip:", 4))
10509       of += 4;
10510    else if (!strncasecmp(of, "sips:", 5))
10511       of += 5;
10512    else
10513       ast_log(LOG_NOTICE, "From address missing 'sip(s):', using it anyway\n");
10514    /* Get just the username part */
10515    if ((c = strchr(dest, '@')))
10516       c = NULL;
10517    else if ((c = strchr(of, '@')))
10518       *c++ = '\0';
10519    if (c) 
10520       snprintf(referto, sizeof(referto), "<sip:%s@%s>", dest, c);
10521    else
10522       snprintf(referto, sizeof(referto), "<sip:%s>", dest);
10523 
10524    /* save in case we get 407 challenge */
10525    sip_refer_allocate(p);
10526    ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
10527    ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
10528    p->refer->status = REFER_SENT;   /* Set refer status */
10529 
10530    reqprep(&req, p, SIP_REFER, 0, 1);
10531 
10532    add_header(&req, "Refer-To", referto);
10533    add_header(&req, "Allow", ALLOWED_METHODS);
10534    add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
10535    if (!ast_strlen_zero(p->our_contact))
10536       add_header(&req, "Referred-By", p->our_contact);
10537 
10538    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
10539 
10540    /* We should propably wait for a NOTIFY here until we ack the transfer */
10541    /* Maybe fork a new thread and wait for a STATUS of REFER_200OK on the refer status before returning to app_transfer */
10542 
10543    /*! \todo In theory, we should hang around and wait for a reply, before
10544    returning to the dial plan here. Don't know really how that would
10545    affect the transfer() app or the pbx, but, well, to make this
10546    useful we should have a STATUS code on transfer().
10547    */
10548 }
10549 
10550 
10551 /*! \brief Send SIP INFO dtmf message, see Cisco documentation on cisco.com */
10552 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
10553 {
10554    struct sip_request req;
10555    
10556    reqprep(&req, p, SIP_INFO, 0, 1);
10557    add_digit(&req, digit, duration, (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO));
10558    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
10559 }
10560 
10561 /*! \brief Send SIP INFO with video update request */
10562 static int transmit_info_with_vidupdate(struct sip_pvt *p)
10563 {
10564    struct sip_request req;
10565    
10566    reqprep(&req, p, SIP_INFO, 0, 1);
10567    add_vidupdate(&req);
10568    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
10569 }
10570 
10571 /*! \brief Transmit generic SIP request 
10572    returns XMIT_ERROR if transmit failed with a critical error (don't retry)
10573 */
10574 static int transmit_request(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
10575 {
10576    struct sip_request resp;
10577    
10578    if (sipmethod == SIP_ACK)
10579       p->invitestate = INV_CONFIRMED;
10580 
10581    reqprep(&resp, p, sipmethod, seqno, newbranch);
10582    if (sipmethod == SIP_CANCEL && p->answered_elsewhere) 
10583       add_header(&resp, "Reason", "SIP;cause=200;text=\"Call completed elsewhere\"");
10584 
10585    add_header_contentLength(&resp, 0);
10586    return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
10587 }
10588 
10589 /*! \brief return the request and response heade for a 401 or 407 code */
10590 static void auth_headers(enum sip_auth_type code, char **header, char **respheader)
10591 {
10592    if (code == WWW_AUTH) {       /* 401 */
10593       *header = "WWW-Authenticate";
10594       *respheader = "Authorization";
10595    } else if (code == PROXY_AUTH) { /* 407 */
10596       *header = "Proxy-Authenticate";
10597       *respheader = "Proxy-Authorization";
10598    } else {
10599       ast_verbose("-- wrong response code %d\n", code);
10600       *header = *respheader = "Invalid";
10601    }
10602 }
10603 
10604 /*! \brief Transmit SIP request, auth added */
10605 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
10606 {
10607    struct sip_request resp;
10608    
10609    reqprep(&resp, p, sipmethod, seqno, newbranch);
10610    if (!ast_strlen_zero(p->realm)) {
10611       char digest[1024];
10612 
10613       memset(digest, 0, sizeof(digest));
10614       if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
10615          char *dummy, *response;
10616          enum sip_auth_type code = p->options ? p->options->auth_type : PROXY_AUTH; /* XXX force 407 if unknown */
10617          auth_headers(code, &dummy, &response);
10618          add_header(&resp, response, digest);
10619       } else
10620          ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
10621    }
10622    /* If we are hanging up and know a cause for that, send it in clear text to make
10623       debugging easier. */
10624    if (sipmethod == SIP_BYE)  {
10625       char buf[10];
10626 
10627       add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->hangupcause));
10628       snprintf(buf, sizeof(buf), "%d", p->hangupcause);
10629       add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
10630    }
10631 
10632    add_header_contentLength(&resp, 0);
10633    return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);   
10634 }
10635 
10636 /*! \brief Remove registration data from realtime database or AST/DB when registration expires */
10637 static void destroy_association(struct sip_peer *peer)
10638 {
10639    int realtimeregs = ast_check_realtime("sipregs");
10640    char *tablename = (realtimeregs) ? "sipregs" : "sippeers";
10641 
10642    if (!sip_cfg.ignore_regexpire) {
10643       if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
10644          ast_update_realtime(tablename, "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", peer->deprecated_username ? "username" : "defaultuser", "", "regserver", "", "useragent", "", "lastms", "", SENTINEL);
10645       } else {
10646          ast_db_del("SIP/Registry", peer->name);
10647       }
10648    }
10649 }
10650 
10651 static void set_socket_transport(struct sip_socket *socket, int transport)
10652 {
10653    /* if the transport type changes, clear all socket data */
10654    if (socket->type != transport) {
10655       socket->fd = -1;
10656       socket->type = transport;
10657       if (socket->tcptls_session) {
10658          ao2_ref(socket->tcptls_session, -1);
10659          socket->tcptls_session = NULL;
10660       }
10661    }
10662 }
10663 
10664 /*! \brief Expire registration of SIP peer */
10665 static int expire_register(const void *data)
10666 {
10667    struct sip_peer *peer = (struct sip_peer *)data;
10668 
10669    if (!peer)     /* Hmmm. We have no peer. Weird. */
10670       return 0;
10671 
10672    peer->expire = -1;
10673    memset(&peer->addr, 0, sizeof(peer->addr));
10674 
10675    destroy_association(peer); /* remove registration data from storage */
10676    set_socket_transport(&peer->socket, peer->default_outbound_transport);
10677 
10678    manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
10679    register_peer_exten(peer, FALSE);   /* Remove regexten */
10680    ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
10681 
10682    /* Do we need to release this peer from memory? 
10683       Only for realtime peers and autocreated peers
10684    */
10685    if (peer->is_realtime)
10686       ast_debug(3, "-REALTIME- peer expired registration. Name: %s. Realtime peer objects now %d\n", peer->name, rpeerobjs);
10687 
10688    if (peer->selfdestruct ||
10689        ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
10690       ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
10691       if (peer->addr.sin_addr.s_addr) {
10692          ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
10693       }
10694    }
10695 
10696    unref_peer(peer, "removing peer ref for expire_register");
10697 
10698    return 0;
10699 }
10700 
10701 /*! \brief Poke peer (send qualify to check if peer is alive and well) */
10702 static int sip_poke_peer_s(const void *data)
10703 {
10704    struct sip_peer *peer = (struct sip_peer *)data;
10705 
10706    peer->pokeexpire = -1;
10707 
10708    sip_poke_peer(peer, 0);
10709 
10710    unref_peer(peer, "removing poke peer ref");
10711 
10712    return 0;
10713 }
10714 
10715 /*! \brief Get registration details from Asterisk DB */
10716 static void reg_source_db(struct sip_peer *peer)
10717 {
10718    char data[256];
10719    struct in_addr in;
10720    int expire;
10721    int port;
10722    char *scan, *addr, *port_str, *expiry_str, *username, *contact;
10723 
10724    if (peer->rt_fromcontact) 
10725       return;
10726    if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data)))
10727       return;
10728 
10729    scan = data;
10730    addr = strsep(&scan, ":");
10731    port_str = strsep(&scan, ":");
10732    expiry_str = strsep(&scan, ":");
10733    username = strsep(&scan, ":");
10734    contact = scan;   /* Contact include sip: and has to be the last part of the database entry as long as we use : as a separator */
10735 
10736    if (!inet_aton(addr, &in))
10737       return;
10738 
10739    if (port_str)
10740       port = atoi(port_str);
10741    else
10742       return;
10743 
10744    if (expiry_str)
10745       expire = atoi(expiry_str);
10746    else
10747       return;
10748 
10749    if (username)
10750       ast_copy_string(peer->username, username, sizeof(peer->username));
10751    if (contact)
10752       ast_copy_string(peer->fullcontact, contact, sizeof(peer->fullcontact));
10753 
10754    ast_debug(2, "SIP Seeding peer from astdb: '%s' at %s@%s:%d for %d\n",
10755        peer->name, peer->username, ast_inet_ntoa(in), port, expire);
10756 
10757    memset(&peer->addr, 0, sizeof(peer->addr));
10758    peer->addr.sin_family = AF_INET;
10759    peer->addr.sin_addr = in;
10760    peer->addr.sin_port = htons(port);
10761    if (sipsock < 0) {
10762       /* SIP isn't up yet, so schedule a poke only, pretty soon */
10763       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ast_random() % 5000 + 1, sip_poke_peer_s, peer,
10764             unref_peer(_data, "removing poke peer ref"),
10765             unref_peer(peer, "removing poke peer ref"),
10766             ref_peer(peer, "adding poke peer ref"));
10767    } else {
10768       sip_poke_peer(peer, 0);
10769    }
10770    AST_SCHED_REPLACE_UNREF(peer->expire, sched, (expire + 10) * 1000, expire_register, peer,
10771          unref_peer(_data, "remove registration ref"),
10772          unref_peer(peer, "remove registration ref"),
10773          ref_peer(peer, "add registration ref"));
10774    register_peer_exten(peer, TRUE);
10775 }
10776 
10777 /*! \brief Save contact header for 200 OK on INVITE */
10778 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
10779 {
10780    char contact[SIPBUFSIZE]; 
10781    char *c;
10782 
10783    /* Look for brackets */
10784    ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
10785    c = get_in_brackets(contact);
10786 
10787    /* Save full contact to call pvt for later bye or re-invite */
10788    ast_string_field_set(pvt, fullcontact, c);
10789 
10790    /* Save URI for later ACKs, BYE or RE-invites */
10791    ast_string_field_set(pvt, okcontacturi, c);
10792 
10793    /* We should return false for URI:s we can't handle,
10794       like tel:, mailto:,ldap: etc */
10795    return TRUE;      
10796 }
10797 
10798 static int __set_address_from_contact(const char *fullcontact, struct sockaddr_in *sin, int tcp)
10799 {
10800    struct hostent *hp;
10801    struct ast_hostent ahp;
10802    int port;
10803    char *host, *pt;
10804    char contact_buf[256];
10805    char contact2_buf[256];
10806    char *contact, *contact2;
10807 
10808    /* Work on a copy */
10809    ast_copy_string(contact_buf, fullcontact, sizeof(contact_buf));
10810    ast_copy_string(contact2_buf, fullcontact, sizeof(contact2_buf));
10811    contact = contact_buf;
10812    contact2 = contact2_buf;
10813 
10814    /* We have only the part in <brackets> here so we just need to parse a SIP URI.*/
10815    if (tcp) {
10816       if (parse_uri(contact, "sips:", &contact, NULL, &host, &pt, NULL, NULL)) {
10817          if (parse_uri(contact2, "sip:", &contact, NULL, &host, &pt, NULL, NULL))
10818             ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", contact);
10819       }
10820       port = !ast_strlen_zero(pt) ? atoi(pt) : STANDARD_TLS_PORT;
10821    } else {
10822       if (parse_uri(contact, "sip:", &contact, NULL, &host, &pt, NULL, NULL))
10823          ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", contact);
10824       port = !ast_strlen_zero(pt) ? atoi(pt) : STANDARD_SIP_PORT;
10825    }
10826 
10827    /* XXX This could block for a long time XXX */
10828    /* We should only do this if it's a name, not an IP */
10829    hp = ast_gethostbyname(host, &ahp);
10830    if (!hp)  {
10831       ast_log(LOG_WARNING, "Invalid host name in Contact: (can't resolve in DNS) : '%s'\n", host);
10832       return -1;
10833    }
10834    sin->sin_family = AF_INET;
10835    memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
10836    sin->sin_port = htons(port);
10837 
10838    return 0;
10839 }
10840 
10841 /*! \brief Change the other partys IP address based on given contact */
10842 static int set_address_from_contact(struct sip_pvt *pvt)
10843 {
10844    if (ast_test_flag(&pvt->flags[0], SIP_NAT_ROUTE)) {
10845       /* NAT: Don't trust the contact field.  Just use what they came to us
10846          with. */
10847       pvt->sa = pvt->recv;
10848       return 0;
10849    }
10850 
10851    return __set_address_from_contact(pvt->fullcontact, &pvt->sa, pvt->socket.type == SIP_TRANSPORT_TLS ? 1 : 0);
10852 }
10853 
10854 /*! \brief Parse contact header and save registration (peer registration) */
10855 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
10856 {
10857    char contact[SIPBUFSIZE];
10858    char data[SIPBUFSIZE];
10859    const char *expires = get_header(req, "Expires");
10860    int expire = atoi(expires);
10861    char *curi, *host, *pt, *curi2, *transport;
10862    int port;
10863    int transport_type;
10864    const char *useragent;
10865    struct hostent *hp;
10866    struct ast_hostent ahp;
10867    struct sockaddr_in oldsin, testsin;
10868 
10869 
10870    ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
10871 
10872    if (ast_strlen_zero(expires)) {  /* No expires header, try look in Contact: */
10873       char *s = strcasestr(contact, ";expires=");
10874       if (s) {
10875          expires = strsep(&s, ";"); /* trim ; and beyond */
10876          if (sscanf(expires + 9, "%30d", &expire) != 1)
10877             expire = default_expiry;
10878       } else {
10879          /* Nothing has been specified */
10880          expire = default_expiry;
10881       }
10882    }
10883 
10884    copy_socket_data(&pvt->socket, &req->socket);
10885 
10886    /* Look for brackets */
10887    curi = contact;
10888    if (strchr(contact, '<') == NULL)   /* No <, check for ; and strip it */
10889       strsep(&curi, ";");  /* This is Header options, not URI options */
10890    curi = get_in_brackets(contact);
10891    curi2 = ast_strdupa(curi);
10892 
10893    /* if they did not specify Contact: or Expires:, they are querying
10894       what we currently have stored as their contact address, so return
10895       it
10896    */
10897    if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
10898       /* If we have an active registration, tell them when the registration is going to expire */
10899       if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact))
10900          pvt->expiry = ast_sched_when(sched, peer->expire);
10901       return PARSE_REGISTER_QUERY;
10902    } else if (!strcasecmp(curi, "*") || !expire) { /* Unregister this peer */
10903       /* This means remove all registrations and return OK */
10904       memset(&peer->addr, 0, sizeof(peer->addr));
10905       set_socket_transport(&peer->socket, peer->default_outbound_transport);
10906 
10907       AST_SCHED_DEL_UNREF(sched, peer->expire,
10908             unref_peer(peer, "remove register expire ref"));
10909 
10910       destroy_association(peer);
10911 
10912       register_peer_exten(peer, FALSE);   /* Remove extension from regexten= setting in sip.conf */
10913       peer->fullcontact[0] = '\0';
10914       peer->useragent[0] = '\0';
10915       peer->sipoptions = 0;
10916       peer->lastms = 0;
10917       pvt->expiry = 0;
10918 
10919       ast_verb(3, "Unregistered SIP '%s'\n", peer->name);
10920 
10921       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\n", peer->name);
10922       return PARSE_REGISTER_UPDATE;
10923    }
10924 
10925    /* Store whatever we got as a contact from the client */
10926    ast_copy_string(peer->fullcontact, curi, sizeof(peer->fullcontact));
10927 
10928    /* For the 200 OK, we should use the received contact */
10929    ast_string_field_build(pvt, our_contact, "<%s>", curi);
10930 
10931    /* Make sure it's a SIP URL */
10932    if (pvt->socket.type == SIP_TRANSPORT_TLS) {
10933       if (parse_uri(curi, "sips:", &curi, NULL, &host, &pt, NULL, &transport)) {
10934          if (parse_uri(curi2, "sip:", &curi, NULL, &host, &pt, NULL, &transport))
10935             ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:) trying to use anyway\n");
10936       }
10937       port = !ast_strlen_zero(pt) ? atoi(pt) : STANDARD_TLS_PORT;
10938    } else {
10939       if (parse_uri(curi, "sip:", &curi, NULL, &host, &pt, NULL, &transport))
10940          ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:) trying to use anyway\n");
10941       port = !ast_strlen_zero(pt) ? atoi(pt) : STANDARD_SIP_PORT;
10942    }
10943 
10944    /* handle the transport type specified in Contact header. */
10945    if ((transport_type = get_transport_str2enum(transport))) {
10946       /* if the port is not specified but the transport is, make sure to set the
10947        * default port to match the specified transport.  This may or may not be the
10948        * same transport used by the pvt struct for the Register dialog. */
10949       if (ast_strlen_zero(pt)) {
10950          port = (transport_type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT;
10951       }
10952    } else {
10953       transport_type = pvt->socket.type;
10954    }
10955 
10956    /* if the peer's socket type is different than the Registration
10957     * transport type, change it.  If it got this far, it is a
10958     * supported type, but check just in case */
10959    if ((peer->socket.type != transport_type) && (peer->transports & transport_type)) {
10960       set_socket_transport(&peer->socket, transport_type);
10961    }
10962 
10963    oldsin = peer->addr;
10964 
10965    /* If we were already linked into the peers_by_ip container unlink ourselves so nobody can find us */
10966    if (peer->addr.sin_addr.s_addr) {
10967       ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
10968    }
10969 
10970    /* Check that they're allowed to register at this IP */
10971    /* XXX This could block for a long time XXX */
10972    hp = ast_gethostbyname(host, &ahp);
10973    if (!hp)  {
10974       ast_log(LOG_WARNING, "Invalid host '%s'\n", host);
10975       *peer->fullcontact = '\0';
10976       ast_string_field_set(pvt, our_contact, "");
10977       return PARSE_REGISTER_FAILED;
10978    }
10979    memcpy(&testsin.sin_addr, hp->h_addr, sizeof(testsin.sin_addr));
10980    if (  ast_apply_ha(global_contact_ha, &testsin) != AST_SENSE_ALLOW ||
10981          ast_apply_ha(peer->contactha, &testsin) != AST_SENSE_ALLOW) {
10982       ast_log(LOG_WARNING, "Host '%s' disallowed by rule\n", host);
10983       *peer->fullcontact = '\0';
10984       ast_string_field_set(pvt, our_contact, "");
10985       return PARSE_REGISTER_FAILED;
10986    }
10987 
10988    if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE)) {
10989       peer->addr.sin_family = AF_INET;
10990       memcpy(&peer->addr.sin_addr, hp->h_addr, sizeof(peer->addr.sin_addr));
10991       peer->addr.sin_port = htons(port);
10992    } else {
10993       /* Don't trust the contact field.  Just use what they came to us
10994          with */
10995       peer->addr = pvt->recv;
10996    }
10997 
10998    /* if the Contact header information copied into peer->addr matches the
10999     * received address, and the transport types are the same, then copy socket
11000     * data into the peer struct */
11001    if ((peer->socket.type == pvt->socket.type) &&
11002       (peer->addr.sin_addr.s_addr == pvt->recv.sin_addr.s_addr) &&
11003       (peer->addr.sin_port == pvt->recv.sin_port)){
11004 
11005       copy_socket_data(&peer->socket, &pvt->socket);
11006    }
11007 
11008    /* Now that our address has been updated put ourselves back into the container for lookups */
11009    ao2_t_link(peers_by_ip, peer, "ao2_link into peers_by_ip table");
11010 
11011    /* Save SIP options profile */
11012    peer->sipoptions = pvt->sipoptions;
11013 
11014    if (!ast_strlen_zero(curi) && ast_strlen_zero(peer->username))
11015       ast_copy_string(peer->username, curi, sizeof(peer->username));
11016 
11017    AST_SCHED_DEL_UNREF(sched, peer->expire,
11018          unref_peer(peer, "remove register expire ref"));
11019 
11020    if (expire > max_expiry)
11021       expire = max_expiry;
11022    if (expire < min_expiry)
11023       expire = min_expiry;
11024    if (peer->is_realtime && !ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
11025       peer->expire = -1;
11026    } else {
11027       peer->expire = ast_sched_add(sched, (expire + 10) * 1000, expire_register,
11028             ref_peer(peer, "add registration ref"));
11029       if (peer->expire == -1) {
11030          unref_peer(peer, "remote registration ref");
11031       }
11032    }
11033    pvt->expiry = expire;
11034    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);
11035    /* Saving TCP connections is useless, we won't be able to reconnect 
11036       XXX WHY???? XXX
11037       \todo check this
11038    */
11039    if (!peer->rt_fromcontact && (peer->socket.type & SIP_TRANSPORT_UDP))
11040       ast_db_put("SIP/Registry", peer->name, data);
11041    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));
11042 
11043    /* Is this a new IP address for us? */
11044    if (VERBOSITY_ATLEAST(2) && inaddrcmp(&peer->addr, &oldsin)) {
11045       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));
11046    }
11047    sip_poke_peer(peer, 0);
11048    register_peer_exten(peer, 1);
11049    
11050    /* Save User agent */
11051    useragent = get_header(req, "User-Agent");
11052    if (strcasecmp(useragent, peer->useragent)) {   /* XXX copy if they are different ? */
11053       ast_copy_string(peer->useragent, useragent, sizeof(peer->useragent));
11054       ast_verb(4, "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
11055    }
11056    return PARSE_REGISTER_UPDATE;
11057 }
11058 
11059 /*! \brief Remove route from route list */
11060 static void free_old_route(struct sip_route *route)
11061 {
11062    struct sip_route *next;
11063 
11064    while (route) {
11065       next = route->next;
11066       ast_free(route);
11067       route = next;
11068    }
11069 }
11070 
11071 /*! \brief List all routes - mostly for debugging */
11072 static void list_route(struct sip_route *route)
11073 {
11074    if (!route)
11075       ast_verbose("list_route: no route\n");
11076    else {
11077       for (;route; route = route->next)
11078          ast_verbose("list_route: hop: <%s>\n", route->hop);
11079    }
11080 }
11081 
11082 /*! \brief Build route list from Record-Route header */
11083 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
11084 {
11085    struct sip_route *thishop, *head, *tail;
11086    int start = 0;
11087    int len;
11088    const char *rr, *contact, *c;
11089 
11090    /* Once a persistant route is set, don't fool with it */
11091    if (p->route && p->route_persistant) {
11092       ast_debug(1, "build_route: Retaining previous route: <%s>\n", p->route->hop);
11093       return;
11094    }
11095 
11096    if (p->route) {
11097       free_old_route(p->route);
11098       p->route = NULL;
11099    }
11100 
11101    /* We only want to create the route set the first time this is called */
11102    p->route_persistant = 1;
11103    
11104    /* Build a tailq, then assign it to p->route when done.
11105     * If backwards, we add entries from the head so they end up
11106     * in reverse order. However, we do need to maintain a correct
11107     * tail pointer because the contact is always at the end.
11108     */
11109    head = NULL;
11110    tail = head;
11111    /* 1st we pass through all the hops in any Record-Route headers */
11112    for (;;) {
11113       /* Each Record-Route header */
11114       rr = __get_header(req, "Record-Route", &start);
11115       if (*rr == '\0')
11116          break;
11117       for (; (rr = strchr(rr, '<')) ; rr += len) { /* Each route entry */
11118          ++rr;
11119          len = strcspn(rr, ">") + 1;
11120          /* Make a struct route */
11121          if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
11122             /* ast_calloc is not needed because all fields are initialized in this block */
11123             ast_copy_string(thishop->hop, rr, len);
11124             ast_debug(2, "build_route: Record-Route hop: <%s>\n", thishop->hop);
11125             /* Link in */
11126             if (backwards) {
11127                /* Link in at head so they end up in reverse order */
11128                thishop->next = head;
11129                head = thishop;
11130                /* If this was the first then it'll be the tail */
11131                if (!tail)
11132                   tail = thishop;
11133             } else {
11134                thishop->next = NULL;
11135                /* Link in at the end */
11136                if (tail)
11137                   tail->next = thishop;
11138                else
11139                   head = thishop;
11140                tail = thishop;
11141             }
11142          }
11143       }
11144    }
11145 
11146    /* Only append the contact if we are dealing with a strict router */
11147    if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop, ";lr") == NULL) ) {
11148       /* 2nd append the Contact: if there is one */
11149       /* Can be multiple Contact headers, comma separated values - we just take the first */
11150       contact = get_header(req, "Contact");
11151       if (!ast_strlen_zero(contact)) {
11152          ast_debug(2, "build_route: Contact hop: %s\n", contact);
11153          /* Look for <: delimited address */
11154          c = strchr(contact, '<');
11155          if (c) {
11156             /* Take to > */
11157             ++c;
11158             len = strcspn(c, ">") + 1;
11159          } else {
11160             /* No <> - just take the lot */
11161             c = contact;
11162             len = strlen(contact) + 1;
11163          }
11164          if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
11165             /* ast_calloc is not needed because all fields are initialized in this block */
11166             ast_copy_string(thishop->hop, c, len);
11167             thishop->next = NULL;
11168             /* Goes at the end */
11169             if (tail)
11170                tail->next = thishop;
11171             else
11172                head = thishop;
11173          }
11174       }
11175    }
11176 
11177    /* Store as new route */
11178    p->route = head;
11179 
11180    /* For debugging dump what we ended up with */
11181    if (sip_debug_test_pvt(p))
11182       list_route(p->route);
11183 }
11184 
11185 /*! \brief builds the sip_pvt's randdata field which is used for the nonce
11186  *  challenge.  When forceupdate is not set, the nonce is only updated if
11187  *  the current one is stale.  In this case, a stalenonce is one which
11188  *  has already received a response, if a nonce has not received a response
11189  *  it is not always necessary or beneficial to create a new one. */
11190 
11191 static void set_nonce_randdata(struct sip_pvt *p, int forceupdate)
11192 {
11193    if (p->stalenonce || forceupdate || ast_strlen_zero(p->randdata)) {
11194       ast_string_field_build(p, randdata, "%08lx", ast_random()); /* Create nonce for challenge */
11195       p->stalenonce = 0;
11196    }
11197 }
11198 
11199 AST_THREADSTORAGE(check_auth_buf);
11200 #define CHECK_AUTH_BUF_INITLEN   256
11201 
11202 /*! \brief  Check user authorization from peer definition 
11203    Some actions, like REGISTER and INVITEs from peers require
11204    authentication (if peer have secret set) 
11205     \return 0 on success, non-zero on error
11206 */
11207 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
11208                 const char *secret, const char *md5secret, int sipmethod,
11209                 char *uri, enum xmittype reliable, int ignore)
11210 {
11211    const char *response;
11212    char *reqheader, *respheader;
11213    const char *authtoken;
11214    char a1_hash[256];
11215    char resp_hash[256]="";
11216    char *c;
11217    int  wrongnonce = FALSE;
11218    int  good_response;
11219    const char *usednonce = p->randdata;
11220    struct ast_str *buf;
11221    int res;
11222 
11223    /* table of recognised keywords, and their value in the digest */
11224    enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
11225    struct x {
11226       const char *key;
11227       const char *s;
11228    } *i, keys[] = {
11229       [K_RESP] = { "response=", "" },
11230       [K_URI] = { "uri=", "" },
11231       [K_USER] = { "username=", "" },
11232       [K_NONCE] = { "nonce=", "" },
11233       [K_LAST] = { NULL, NULL}
11234    };
11235 
11236    /* Always OK if no secret */
11237    if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
11238       return AUTH_SUCCESSFUL;
11239 
11240    /* Always auth with WWW-auth since we're NOT a proxy */
11241    /* Using proxy-auth in a B2BUA may block proxy authorization in the same transaction */
11242    response = "401 Unauthorized";
11243 
11244    /*
11245     * Note the apparent swap of arguments below, compared to other
11246     * usages of auth_headers().
11247     */
11248    auth_headers(WWW_AUTH, &respheader, &reqheader);
11249 
11250    authtoken =  get_header(req, reqheader);  
11251    if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
11252       /* This is a retransmitted invite/register/etc, don't reconstruct authentication
11253          information */
11254       if (!reliable) {
11255          /* Resend message if this was NOT a reliable delivery.   Otherwise the
11256             retransmission should get it */
11257          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
11258          /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
11259          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11260       }
11261       return AUTH_CHALLENGE_SENT;
11262    } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
11263       /* We have no auth, so issue challenge and request authentication */
11264       set_nonce_randdata(p, 1); /* Create nonce for challenge */
11265       transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
11266       /* Schedule auto destroy in 32 seconds */
11267       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11268       return AUTH_CHALLENGE_SENT;
11269    } 
11270 
11271    /* --- We have auth, so check it */
11272 
11273    /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
11274       an example in the spec of just what it is you're doing a hash on. */
11275 
11276    if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN)))
11277       return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
11278 
11279    /* Make a copy of the response and parse it */
11280    res = ast_str_set(&buf, 0, "%s", authtoken);
11281 
11282    if (res == AST_DYNSTR_BUILD_FAILED)
11283       return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
11284 
11285    c = buf->str;
11286 
11287    while(c && *(c = ast_skip_blanks(c)) ) { /* lookup for keys */
11288       for (i = keys; i->key != NULL; i++) {
11289          const char *separator = ",";  /* default */
11290 
11291          if (strncasecmp(c, i->key, strlen(i->key)) != 0)
11292             continue;
11293          /* Found. Skip keyword, take text in quotes or up to the separator. */
11294          c += strlen(i->key);
11295          if (*c == '"') { /* in quotes. Skip first and look for last */
11296             c++;
11297             separator = "\"";
11298          }
11299          i->s = c;
11300          strsep(&c, separator);
11301          break;
11302       }
11303       if (i->key == NULL) /* not found, jump after space or comma */
11304          strsep(&c, " ,");
11305    }
11306 
11307    /* Verify that digest username matches  the username we auth as */
11308    if (strcmp(username, keys[K_USER].s)) {
11309       ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
11310          username, keys[K_USER].s);
11311       /* Oops, we're trying something here */
11312       return AUTH_USERNAME_MISMATCH;
11313    }
11314 
11315    /* Verify nonce from request matches our nonce, and the nonce has not already been responded to.
11316     * If this check fails, send 401 with new nonce */
11317    if (strcasecmp(p->randdata, keys[K_NONCE].s) || p->stalenonce) { /* XXX it was 'n'casecmp ? */
11318       wrongnonce = TRUE;
11319       usednonce = keys[K_NONCE].s;
11320    } else {
11321       p->stalenonce = 1; /* now, since the nonce has a response, mark it as stale so it can't be sent or responded to again */
11322    }
11323 
11324    if (!ast_strlen_zero(md5secret))
11325       ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
11326    else {
11327       char a1[256];
11328       snprintf(a1, sizeof(a1), "%s:%s:%s", username, global_realm, secret);
11329       ast_md5_hash(a1_hash, a1);
11330    }
11331 
11332    /* compute the expected response to compare with what we received */
11333    {
11334       char a2[256];
11335       char a2_hash[256];
11336       char resp[256];
11337 
11338       snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
11339             S_OR(keys[K_URI].s, uri));
11340       ast_md5_hash(a2_hash, a2);
11341       snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
11342       ast_md5_hash(resp_hash, resp);
11343    }
11344 
11345    good_response = keys[K_RESP].s &&
11346          !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
11347    if (wrongnonce) {
11348       if (good_response) {
11349          if (sipdebug)
11350             ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "To"));
11351          /* We got working auth token, based on stale nonce . */
11352          set_nonce_randdata(p, 0);
11353          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
11354       } else {
11355          /* Everything was wrong, so give the device one more try with a new challenge */
11356          if (!req->ignore) {
11357             if (sipdebug)
11358                ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
11359             set_nonce_randdata(p, 1);
11360          } else {
11361             if (sipdebug)
11362                ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", get_header(req, "To"));
11363          }
11364          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
11365       }
11366 
11367       /* Schedule auto destroy in 32 seconds */
11368       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11369       return AUTH_CHALLENGE_SENT;
11370    } 
11371    if (good_response) {
11372       append_history(p, "AuthOK", "Auth challenge succesful for %s", username);
11373       return AUTH_SUCCESSFUL;
11374    }
11375 
11376    /* Ok, we have a bad username/secret pair */
11377    /* Tell the UAS not to re-send this authentication data, because
11378       it will continue to fail
11379    */
11380 
11381    return AUTH_SECRET_FAILED;
11382 }
11383 
11384 /*! \brief Change onhold state of a peer using a pvt structure */
11385 static void sip_peer_hold(struct sip_pvt *p, int hold)
11386 {
11387    struct sip_peer *peer = find_peer(p->peername, NULL, 1, FINDALLDEVICES, FALSE);
11388 
11389    if (!peer)
11390       return;
11391 
11392    /* If they put someone on hold, increment the value... otherwise decrement it */
11393    ast_atomic_fetchadd_int(&peer->onHold, (hold ? +1 : -1));
11394 
11395    /* Request device state update */
11396    ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
11397    unref_peer(peer, "sip_peer_hold: from find_peer operation");
11398    
11399    return;
11400 }
11401 
11402 /*! \brief Receive MWI events that we have subscribed to */
11403 static void mwi_event_cb(const struct ast_event *event, void *userdata)
11404 {
11405    struct sip_peer *peer = userdata;
11406 
11407    ao2_lock(peer);
11408    sip_send_mwi_to_peer(peer, event, 0);
11409    ao2_unlock(peer);
11410 }
11411 
11412 /*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem
11413 \note If you add an "hint" priority to the extension in the dial plan,
11414    you will get notifications on device state changes */
11415 static int cb_extensionstate(char *context, char* exten, int state, void *data)
11416 {
11417    struct sip_pvt *p = data;
11418 
11419    sip_pvt_lock(p);
11420 
11421    switch(state) {
11422    case AST_EXTENSION_DEACTIVATED:  /* Retry after a while */
11423    case AST_EXTENSION_REMOVED:   /* Extension is gone */
11424       if (p->autokillid > -1 && sip_cancel_destroy(p))   /* Remove subscription expiry for renewals */
11425          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
11426       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);  /* Delete subscription in 32 secs */
11427       ast_verb(2, "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
11428       p->stateid = -1;
11429       p->subscribed = NONE;
11430       append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
11431       break;
11432    default: /* Tell user */
11433       p->laststate = state;
11434       break;
11435    }
11436    if (p->subscribed != NONE) {  /* Only send state NOTIFY if we know the format */
11437       if (!p->pendinginvite) {
11438          transmit_state_notify(p, state, 1, FALSE);
11439       } else {
11440          /* We already have a NOTIFY sent that is not answered. Queue the state up.
11441             if many state changes happen meanwhile, we will only send a notification of the last one */
11442          ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
11443       }
11444    }
11445    ast_verb(2, "Extension Changed %s[%s] new state %s for Notify User %s %s\n", exten, context, ast_extension_state2str(state), p->username,
11446          ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
11447 
11448    sip_pvt_unlock(p);
11449 
11450    return 0;
11451 }
11452 
11453 /*! \brief Send a fake 401 Unauthorized response when the administrator
11454   wants to hide the names of local devices  from fishers
11455  */
11456 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable)
11457 {
11458    /* We have to emulate EXACTLY what we'd get with a good peer
11459     * and a bad password, or else we leak information. */
11460    const char *response = "407 Proxy Authentication Required";
11461    const char *reqheader = "Proxy-Authorization";
11462    const char *respheader = "Proxy-Authenticate";
11463    const char *authtoken;
11464    struct ast_str *buf;
11465    char *c;
11466 
11467    /* table of recognised keywords, and their value in the digest */
11468    enum keys { K_NONCE, K_LAST };
11469    struct x {
11470       const char *key;
11471       const char *s;
11472    } *i, keys[] = {
11473       [K_NONCE] = { "nonce=", "" },
11474       [K_LAST] = { NULL, NULL}
11475    };
11476 
11477    if (sipmethod == SIP_REGISTER || sipmethod == SIP_SUBSCRIBE) {
11478       response = "401 Unauthorized";
11479       reqheader = "Authorization";
11480       respheader = "WWW-Authenticate";
11481    }
11482    authtoken = get_header(req, reqheader);
11483    if (req->ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
11484       /* This is a retransmitted invite/register/etc, don't reconstruct authentication
11485        * information */
11486       transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
11487       /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
11488       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11489       return;
11490    } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
11491       /* We have no auth, so issue challenge and request authentication */
11492       set_nonce_randdata(p, 1);
11493       transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
11494       /* Schedule auto destroy in 32 seconds */
11495       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11496       return;
11497    }
11498 
11499    if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
11500       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
11501       return;
11502    }
11503 
11504    /* Make a copy of the response and parse it */
11505    if (ast_str_set(&buf, 0, "%s", authtoken) == AST_DYNSTR_BUILD_FAILED) {
11506       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
11507       return;
11508    }
11509 
11510    c = buf->str;
11511 
11512    while (c && *(c = ast_skip_blanks(c))) { /* lookup for keys */
11513       for (i = keys; i->key != NULL; i++) {
11514          const char *separator = ",";  /* default */
11515 
11516          if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
11517             continue;
11518          }
11519          /* Found. Skip keyword, take text in quotes or up to the separator. */
11520          c += strlen(i->key);
11521          if (*c == '"') { /* in quotes. Skip first and look for last */
11522             c++;
11523             separator = "\"";
11524          }
11525          i->s = c;
11526          strsep(&c, separator);
11527          break;
11528       }
11529       if (i->key == NULL) { /* not found, jump after space or comma */
11530          strsep(&c, " ,");
11531       }
11532    }
11533 
11534    /* Verify nonce from request matches our nonce.  If not, send 401 with new nonce */
11535    if (strcasecmp(p->randdata, keys[K_NONCE].s)) {
11536       if (!req->ignore) {
11537          set_nonce_randdata(p, 1);
11538       }
11539       transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
11540 
11541       /* Schedule auto destroy in 32 seconds */
11542       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11543    } else {
11544       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
11545    }
11546 }
11547 
11548 /*!
11549  * Terminate the uri at the first ';' or space.
11550  * Technically we should ignore escaped space per RFC3261 (19.1.1 etc)
11551  * but don't do it for the time being. Remember the uri format is:
11552  *\verbatim
11553  *
11554  * sip:user:password@host:port;uri-parameters?headers
11555  * sips:user:password@host:port;uri-parameters?headers
11556  *
11557  *\endverbatim
11558  */
11559 static char *terminate_uri(char *uri)
11560 {
11561    char *t = uri;
11562    while (*t && *t > ' ' && *t != ';')
11563       t++;
11564    *t = '\0';
11565    return uri;
11566 }
11567 
11568 /*! \brief Verify registration of user 
11569    - Registration is done in several steps, first a REGISTER without auth
11570      to get a challenge (nonce) then a second one with auth
11571    - Registration requests are only matched with peers that are marked as "dynamic"
11572  */
11573 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
11574                      struct sip_request *req, char *uri)
11575 {
11576    enum check_auth_result res = AUTH_NOT_FOUND;
11577    struct sip_peer *peer;
11578    char tmp[256];
11579    char *name, *c;
11580    char *domain;
11581 
11582    terminate_uri(uri);  /* warning, overwrite the string */
11583 
11584    ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
11585    if (pedanticsipchecking)
11586       ast_uri_decode(tmp);
11587 
11588    c = get_in_brackets(tmp);
11589    c = remove_uri_parameters(c);
11590 
11591    if (!strncasecmp(c, "sip:", 4)) {
11592       name = c + 4;
11593    } else if (!strncasecmp(c, "sips:", 5)) {
11594       name = c + 5;
11595    } else {
11596       name = c;
11597       ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_inet_ntoa(sin->sin_addr));
11598    }
11599 
11600    /* XXX here too we interpret a missing @domain as a name-only
11601     * URI, whereas the RFC says this is a domain-only uri.
11602     */
11603    /* Strip off the domain name */
11604    if ((c = strchr(name, '@'))) {
11605       *c++ = '\0';
11606       domain = c;
11607       if ((c = strchr(domain, ':')))   /* Remove :port */
11608          *c = '\0';
11609       if (!AST_LIST_EMPTY(&domain_list)) {
11610          if (!check_sip_domain(domain, NULL, 0)) {
11611             transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
11612             return AUTH_UNKNOWN_DOMAIN;
11613          }
11614       }
11615    }
11616    c = strchr(name, ';');  /* Remove any Username parameters */
11617    if (c)
11618       *c = '\0';
11619 
11620    ast_string_field_set(p, exten, name);
11621    build_contact(p);
11622    peer = find_peer(name, NULL, TRUE, FINDPEERS, FALSE);
11623    if (!(peer && ast_apply_ha(peer->ha, sin))) {
11624       /* Peer fails ACL check */
11625       if (peer) {
11626          unref_peer(peer, "register_verify: unref_peer: from find_peer operation");
11627          peer = NULL;
11628          res = AUTH_ACL_FAILED;
11629       } else
11630          res = AUTH_NOT_FOUND;
11631    }
11632 
11633    if (peer) {
11634       /* Set Frame packetization */
11635       if (p->rtp) {
11636          ast_rtp_codec_setpref(p->rtp, &peer->prefs);
11637          p->autoframing = peer->autoframing;
11638       }
11639       if (!peer->host_dynamic) {
11640          ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
11641          res = AUTH_PEER_NOT_DYNAMIC;
11642       } else {
11643          ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT);
11644          if (ast_test_flag(&p->flags[1], SIP_PAGE2_REGISTERTRYING))
11645             transmit_response(p, "100 Trying", req);
11646          if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri, XMIT_UNRELIABLE, req->ignore))) {
11647             if (sip_cancel_destroy(p))
11648                ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
11649 
11650             if (check_request_transport(peer, req)) {
11651                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
11652                transmit_response_with_date(p, "403 Forbidden", req);
11653                res = AUTH_BAD_TRANSPORT;
11654             } else {
11655 
11656                /* We have a successful registration attempt with proper authentication,
11657                   now, update the peer */
11658                switch (parse_register_contact(p, peer, req)) {
11659                case PARSE_REGISTER_FAILED:
11660                   ast_log(LOG_WARNING, "Failed to parse contact info\n");
11661                   transmit_response_with_date(p, "400 Bad Request", req);
11662                   peer->lastmsgssent = -1;
11663                   res = 0;
11664                   break;
11665                case PARSE_REGISTER_QUERY:
11666                   transmit_response_with_date(p, "200 OK", req);
11667                   peer->lastmsgssent = -1;
11668                   res = 0;
11669                   break;
11670                case PARSE_REGISTER_UPDATE:
11671                   update_peer(peer, p->expiry);
11672                   /* Say OK and ask subsystem to retransmit msg counter */
11673                   transmit_response_with_date(p, "200 OK", req);
11674                   if (!ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY))
11675                      peer->lastmsgssent = -1;
11676                   res = 0;
11677                   break;
11678                }
11679             }
11680 
11681          } 
11682       }
11683    }
11684    if (!peer && autocreatepeer) {
11685       /* Create peer if we have autocreate mode enabled */
11686       peer = temp_peer(name);
11687       if (peer) {
11688          ao2_t_link(peers, peer, "link peer into peer table");
11689          if (peer->addr.sin_addr.s_addr) {
11690             ao2_t_link(peers_by_ip, peer, "link peer into peers-by-ip table");
11691          }
11692          
11693          if (sip_cancel_destroy(p))
11694             ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
11695          switch (parse_register_contact(p, peer, req)) {
11696          case PARSE_REGISTER_FAILED:
11697             ast_log(LOG_WARNING, "Failed to parse contact info\n");
11698             transmit_response_with_date(p, "400 Bad Request", req);
11699             peer->lastmsgssent = -1;
11700             res = 0;
11701             break;
11702          case PARSE_REGISTER_QUERY:
11703             transmit_response_with_date(p, "200 OK", req);
11704             peer->lastmsgssent = -1;
11705             res = 0;
11706             break;
11707          case PARSE_REGISTER_UPDATE:
11708             /* Say OK and ask subsystem to retransmit msg counter */
11709             transmit_response_with_date(p, "200 OK", req);
11710             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));
11711             peer->lastmsgssent = -1;
11712             res = 0;
11713             break;
11714          }
11715       }
11716    }
11717    if (!peer && global_alwaysauthreject) {
11718       /* If we found a peer, we transmit a 100 Trying.  Therefore, if we're
11719        * trying to avoid leaking information, we MUST also transmit the same
11720        * response when we DON'T find a peer. */
11721       transmit_response(p, "100 Trying", req);
11722       /* Insert a fake delay between the 100 and the subsequent failure. */
11723       sched_yield();
11724    }
11725    if (!res) {
11726       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
11727    }
11728    if (res < 0) {
11729       switch (res) {
11730       case AUTH_SECRET_FAILED:
11731          /* Wrong password in authentication. Go away, don't try again until you fixed it */
11732          transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
11733          if (global_authfailureevents)
11734             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", 
11735                name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
11736          break;
11737       case AUTH_USERNAME_MISMATCH:
11738          /* Username and digest username does not match.
11739             Asterisk uses the From: username for authentication. We need the
11740             devices to use the same authentication user name until we support
11741             proper authentication by digest auth name */
11742       case AUTH_NOT_FOUND:
11743       case AUTH_PEER_NOT_DYNAMIC:
11744       case AUTH_ACL_FAILED:
11745          if (global_alwaysauthreject) {
11746             transmit_fake_auth_response(p, SIP_REGISTER, &p->initreq, XMIT_UNRELIABLE);
11747          } else {
11748             /* URI not found */
11749             if (res == AUTH_PEER_NOT_DYNAMIC) {
11750                transmit_response(p, "403 Forbidden", &p->initreq);
11751                if (global_authfailureevents)
11752                   manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Rejected\r\nCause: AUTH_PEER_NOT_DYNAMIC\r\nAddress: %s\r\nPort: %d\r\n", 
11753                      name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
11754                }
11755             else
11756                transmit_response(p, "404 Not found", &p->initreq);
11757                if (global_authfailureevents)
11758                   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", 
11759                            (res == AUTH_USERNAME_MISMATCH) ? "AUTH_USERNAME_MISMATCH" : "URI_NOT_FOUND", name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
11760          }
11761          break;
11762       case AUTH_BAD_TRANSPORT:
11763       default:
11764          break;
11765       }
11766    }
11767    if (peer)
11768       unref_peer(peer, "register_verify: unref_peer: tossing stack peer pointer at end of func");
11769 
11770    return res;
11771 }
11772 
11773 /*! \brief Translate referring cause */
11774 static void sip_set_redirstr(struct sip_pvt *p, char *reason) {
11775 
11776    if (!strcmp(reason, "unknown")) {
11777       ast_string_field_set(p, redircause, "UNKNOWN");
11778    } else if (!strcmp(reason, "user-busy")) {
11779       ast_string_field_set(p, redircause, "BUSY");
11780    } else if (!strcmp(reason, "no-answer")) {
11781       ast_string_field_set(p, redircause, "NOANSWER");
11782    } else if (!strcmp(reason, "unavailable")) {
11783       ast_string_field_set(p, redircause, "UNREACHABLE");
11784    } else if (!strcmp(reason, "unconditional")) {
11785       ast_string_field_set(p, redircause, "UNCONDITIONAL");
11786    } else if (!strcmp(reason, "time-of-day")) {
11787       ast_string_field_set(p, redircause, "UNKNOWN");
11788    } else if (!strcmp(reason, "do-not-disturb")) {
11789       ast_string_field_set(p, redircause, "UNKNOWN");
11790    } else if (!strcmp(reason, "deflection")) {
11791       ast_string_field_set(p, redircause, "UNKNOWN");
11792    } else if (!strcmp(reason, "follow-me")) {
11793       ast_string_field_set(p, redircause, "UNKNOWN");
11794    } else if (!strcmp(reason, "out-of-service")) {
11795       ast_string_field_set(p, redircause, "UNREACHABLE");
11796    } else if (!strcmp(reason, "away")) {
11797       ast_string_field_set(p, redircause, "UNREACHABLE");
11798    } else {
11799       ast_string_field_set(p, redircause, "UNKNOWN");
11800    }
11801 }
11802 
11803 /*! \brief Get referring dnis */
11804 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq)
11805 {
11806    char tmp[256], *exten, *rexten, *rdomain;
11807    char *params, *reason = NULL;
11808    struct sip_request *req;
11809    
11810    req = oreq ? oreq : &p->initreq;
11811 
11812    ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
11813    if (ast_strlen_zero(tmp))
11814       return 0;
11815 
11816    params = strchr(tmp, ';');
11817 
11818    exten = get_in_brackets(tmp);
11819    if (!strncasecmp(exten, "sip:", 4)) {
11820       exten += 4;
11821    } else if (!strncasecmp(exten, "sips:", 5)) {
11822       exten += 5;
11823    } else {
11824       ast_log(LOG_WARNING, "Huh?  Not an RDNIS SIP header (%s)?\n", exten);
11825       return -1;
11826    }
11827 
11828    /* Get diversion-reason param if present */
11829    if (params) {
11830       *params = '\0';   /* Cut off parameters  */
11831       params++;
11832       while (*params == ';' || *params == ' ')
11833          params++;
11834       /* Check if we have a reason parameter */
11835       if ((reason = strcasestr(params, "reason="))) {
11836          reason+=7;
11837          /* Remove enclosing double-quotes */
11838          if (*reason == '"') 
11839             ast_strip_quoted(reason, "\"", "\"");
11840          if (!ast_strlen_zero(reason)) {
11841             sip_set_redirstr(p, reason);
11842             if (p->owner) {
11843                pbx_builtin_setvar_helper(p->owner, "__PRIREDIRECTREASON", p->redircause);
11844                pbx_builtin_setvar_helper(p->owner, "__SIPREDIRECTREASON", reason);
11845             }
11846          }
11847       }
11848    }
11849 
11850    rdomain = exten;
11851    rexten = strsep(&rdomain, "@");  /* trim anything after @ */
11852    if (p->owner) 
11853       pbx_builtin_setvar_helper(p->owner, "__SIPRDNISDOMAIN", rdomain);
11854 
11855    if (sip_debug_test_pvt(p))
11856       ast_verbose("RDNIS for this call is is %s (reason %s)\n", exten, reason ? reason : "");
11857 
11858    ast_string_field_set(p, rdnis, rexten);
11859 
11860    return 0;
11861 }
11862 
11863 /*! \brief Find out who the call is for.
11864    We use the request uri as a destination. 
11865    This code assumes authentication has been done, so that the
11866    device (peer/user) context is already set.
11867    \return 0 on success (found a matching extension),
11868    1 for pickup extension or overlap dialling support (if we support it),
11869    -1 on error.
11870 */
11871 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
11872 {
11873    char tmp[256] = "", *uri, *a;
11874    char tmpf[256] = "", *from = NULL;
11875    struct sip_request *req;
11876    char *colon;
11877    char *decoded_uri;
11878    
11879    req = oreq;
11880    if (!req)
11881       req = &p->initreq;
11882 
11883    /* Find the request URI */
11884    if (req->rlPart2)
11885       ast_copy_string(tmp, REQ_OFFSET_TO_STR(req, rlPart2), sizeof(tmp));
11886    
11887    if (pedanticsipchecking)
11888       ast_uri_decode(tmp);
11889 
11890    uri = get_in_brackets(tmp);
11891    
11892    if (!strncasecmp(uri, "sip:", 4)) {
11893       uri += 4;
11894    } else if (!strncasecmp(uri, "sips:", 5)) {
11895       uri += 5;
11896    } else {
11897       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", uri);
11898       return -1;
11899    }
11900 
11901    /* Now find the From: caller ID and name */
11902    /* XXX Why is this done in get_destination? Isn't it already done?
11903       Needs to be checked 
11904         */
11905    ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
11906    if (!ast_strlen_zero(tmpf)) {
11907       if (pedanticsipchecking)
11908          ast_uri_decode(tmpf);
11909       from = get_in_brackets(tmpf);
11910    } 
11911    
11912    if (!ast_strlen_zero(from)) {
11913       if (!strncasecmp(from, "sip:", 4)) {
11914          from += 4;
11915       } else if (!strncasecmp(from, "sips:", 5)) {
11916          from += 5;
11917       } else {
11918          ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", from);
11919          return -1;
11920       }
11921       if ((a = strchr(from, '@')))
11922          *a++ = '\0';
11923       else
11924          a = from;   /* just a domain */
11925       from = strsep(&from, ";"); /* Remove userinfo options */
11926       a = strsep(&a, ";");    /* Remove URI options */
11927       ast_string_field_set(p, fromdomain, a);
11928    }
11929 
11930    /* Skip any options and find the domain */
11931 
11932    /* Get the target domain */
11933    if ((a = strchr(uri, '@'))) {
11934       *a++ = '\0';
11935    } else { /* No username part */
11936       a = uri;
11937       uri = "s";  /* Set extension to "s" */
11938    }
11939    colon = strchr(a, ':'); /* Remove :port */
11940    if (colon)
11941       *colon = '\0';
11942 
11943    uri = strsep(&uri, ";");   /* Remove userinfo options */
11944    a = strsep(&a, ";");    /* Remove URI options */
11945 
11946    ast_string_field_set(p, domain, a);
11947 
11948    if (!AST_LIST_EMPTY(&domain_list)) {
11949       char domain_context[AST_MAX_EXTENSION];
11950 
11951       domain_context[0] = '\0';
11952       if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
11953          if (!allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
11954             ast_debug(1, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
11955             return -2;
11956          }
11957       }
11958       /* If we have a context defined, overwrite the original context */
11959       if (!ast_strlen_zero(domain_context))
11960          ast_string_field_set(p, context, domain_context);
11961    }
11962 
11963    /* If the request coming in is a subscription and subscribecontext has been specified use it */
11964    if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext))
11965       ast_string_field_set(p, context, p->subscribecontext);
11966 
11967    if (sip_debug_test_pvt(p))
11968       ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
11969 
11970    /* If this is a subscription we actually just need to see if a hint exists for the extension */
11971    if (req->method == SIP_SUBSCRIBE) {
11972       char hint[AST_MAX_EXTENSION];
11973       return (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten) ? 0 : -1);
11974    } else {
11975       decoded_uri = ast_strdupa(uri);
11976       ast_uri_decode(decoded_uri);
11977       /* Check the dialplan for the username part of the request URI,
11978          the domain will be stored in the SIPDOMAIN variable
11979          Since extensions.conf can have unescaped characters, try matching a decoded
11980          uri in addition to the non-decoded uri
11981          Return 0 if we have a matching extension */
11982       if (ast_exists_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from)) || ast_exists_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from)) ||
11983           !strcmp(decoded_uri, ast_pickup_ext())) {
11984          if (!oreq)
11985             ast_string_field_set(p, exten, decoded_uri);
11986          return 0;
11987       } 
11988    }
11989 
11990    /* Return 1 for pickup extension or overlap dialling support (if we support it) */
11991    if((ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) && 
11992        ast_canmatch_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))) ||
11993        !strncmp(decoded_uri, ast_pickup_ext(), strlen(decoded_uri))) {
11994       return 1;
11995    }
11996    
11997    return -1;
11998 }
11999 
12000 /*! \brief Lock dialog lock and find matching pvt lock  
12001    \return a reference, remember to release it when done 
12002 */
12003 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag) 
12004 {
12005    struct sip_pvt *sip_pvt_ptr;
12006    struct sip_pvt tmp_dialog = {
12007       .callid = callid,
12008    };
12009 
12010    if (totag)
12011       ast_debug(4, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
12012 
12013    /* Search dialogs and find the match */
12014    
12015    sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find of dialog in dialogs table");
12016    if (sip_pvt_ptr) {
12017       /* Go ahead and lock it (and its owner) before returning */
12018       sip_pvt_lock(sip_pvt_ptr);
12019       if (pedanticsipchecking) {
12020          unsigned char frommismatch = 0, tomismatch = 0;
12021 
12022          if (ast_strlen_zero(fromtag)) {
12023             sip_pvt_unlock(sip_pvt_ptr);
12024             ast_debug(4, "Matched %s call for callid=%s - no from tag specified, pedantic check fails\n",
12025                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
12026             return NULL;
12027          }
12028 
12029          if (ast_strlen_zero(totag)) {
12030             sip_pvt_unlock(sip_pvt_ptr);
12031             ast_debug(4, "Matched %s call for callid=%s - no to tag specified, pedantic check fails\n",
12032                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
12033             return NULL;
12034          }
12035          /* RFC 3891
12036           * > 3.  User Agent Server Behavior: Receiving a Replaces Header
12037           * > The Replaces header contains information used to match an existing
12038           * > SIP dialog (call-id, to-tag, and from-tag).  Upon receiving an INVITE
12039           * > with a Replaces header, the User Agent (UA) attempts to match this
12040           * > information with a confirmed or early dialog.  The User Agent Server
12041           * > (UAS) matches the to-tag and from-tag parameters as if they were tags
12042           * > present in an incoming request.  In other words, the to-tag parameter
12043           * > is compared to the local tag, and the from-tag parameter is compared
12044           * > to the remote tag.
12045           *
12046           * Thus, the totag is always compared to the local tag, regardless if
12047           * this our call is an incoming or outgoing call.
12048           */
12049          frommismatch = !!strcmp(fromtag, sip_pvt_ptr->theirtag);
12050          tomismatch = !!strcmp(totag, sip_pvt_ptr->tag);
12051          if (frommismatch || tomismatch) {
12052             sip_pvt_unlock(sip_pvt_ptr);
12053             if (frommismatch) {
12054                ast_debug(4, "Matched %s call for callid=%s - But the pedantic check rejected the match; their tag is %s Our tag is %s\n",
12055                        sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid, 
12056                        fromtag, sip_pvt_ptr->theirtag);
12057             }
12058             if (tomismatch) {
12059                ast_debug(4, "Matched %s call for callid=%s - pedantic to tag check fails; their tag is %s our tag is %s\n",
12060                     sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid, 
12061                     totag, sip_pvt_ptr->tag);
12062             }
12063             return NULL;
12064          }
12065       }
12066       
12067       if (totag)
12068          ast_debug(4, "Matched %s call - their tag is %s Our tag is %s\n",
12069                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING",
12070                  sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
12071 
12072       /* deadlock avoidance... */
12073       while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
12074          sip_pvt_unlock(sip_pvt_ptr);
12075          usleep(1);
12076          sip_pvt_lock(sip_pvt_ptr);
12077       }
12078    }
12079    
12080    return sip_pvt_ptr;
12081 }
12082 
12083 /*! \brief Call transfer support (the REFER method) 
12084  *    Extracts Refer headers into pvt dialog structure */
12085 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
12086 {
12087 
12088    const char *p_referred_by = NULL;
12089    char *h_refer_to = NULL; 
12090    char *h_referred_by = NULL;
12091    char *refer_to;
12092    const char *p_refer_to;
12093    char *referred_by_uri = NULL;
12094    char *ptr;
12095    struct sip_request *req = NULL;
12096    const char *transfer_context = NULL;
12097    struct sip_refer *referdata;
12098 
12099 
12100    req = outgoing_req;
12101    referdata = transferer->refer;
12102 
12103    if (!req)
12104       req = &transferer->initreq;
12105 
12106    p_refer_to = get_header(req, "Refer-To");
12107    if (ast_strlen_zero(p_refer_to)) {
12108       ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
12109       return -2;  /* Syntax error */
12110    }
12111    h_refer_to = ast_strdupa(p_refer_to);
12112    refer_to = get_in_brackets(h_refer_to);
12113    if (pedanticsipchecking)
12114       ast_uri_decode(refer_to);
12115 
12116    if (!strncasecmp(refer_to, "sip:", 4)) {
12117       refer_to += 4;       /* Skip sip: */
12118    } else if (!strncasecmp(refer_to, "sips:", 5)) {
12119       refer_to += 5;
12120    } else {
12121       ast_log(LOG_WARNING, "Can't transfer to non-sip: URI.  (Refer-to: %s)?\n", refer_to);
12122       return -3;
12123    }
12124 
12125    /* Get referred by header if it exists */
12126    p_referred_by = get_header(req, "Referred-By");
12127 
12128    /* Give useful transfer information to the dialplan */
12129    if (transferer->owner) {
12130       struct ast_channel *peer = ast_bridged_channel(transferer->owner);
12131       if (peer) {
12132          pbx_builtin_setvar_helper(peer, "SIPREFERRINGCONTEXT", transferer->context);
12133          pbx_builtin_setvar_helper(peer, "SIPREFERREDBYHDR", p_referred_by);
12134       }
12135    }
12136 
12137    if (!ast_strlen_zero(p_referred_by)) {
12138       char *lessthan;
12139       h_referred_by = ast_strdupa(p_referred_by);
12140       if (pedanticsipchecking)
12141          ast_uri_decode(h_referred_by);
12142 
12143       /* Store referrer's caller ID name */
12144       ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
12145       if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
12146          *(lessthan - 1) = '\0'; /* Space */
12147       }
12148 
12149       referred_by_uri = get_in_brackets(h_referred_by);
12150       if (!strncasecmp(referred_by_uri, "sip:", 4)) {
12151          referred_by_uri += 4;      /* Skip sip: */
12152       } else if (!strncasecmp(referred_by_uri, "sips:", 5)) {
12153          referred_by_uri += 5;      /* Skip sips: */
12154       } else {
12155          ast_log(LOG_WARNING, "Huh?  Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
12156          referred_by_uri = NULL;
12157       }
12158    }
12159 
12160    /* Check for arguments in the refer_to header */
12161    if ((ptr = strcasestr(refer_to, "replaces="))) {
12162       char *to = NULL, *from = NULL;
12163       
12164       /* This is an attended transfer */
12165       referdata->attendedtransfer = 1;
12166       ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
12167       ast_uri_decode(referdata->replaces_callid);
12168       if ((ptr = strchr(referdata->replaces_callid, ';')))  /* Find options */ {
12169          *ptr++ = '\0';
12170       }
12171       
12172       if (ptr) {
12173          /* Find the different tags before we destroy the string */
12174          to = strcasestr(ptr, "to-tag=");
12175          from = strcasestr(ptr, "from-tag=");
12176       }
12177       
12178       /* Grab the to header */
12179       if (to) {
12180          ptr = to + 7;
12181          if ((to = strchr(ptr, '&')))
12182             *to = '\0';
12183          if ((to = strchr(ptr, ';')))
12184             *to = '\0';
12185          ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
12186       }
12187       
12188       if (from) {
12189          ptr = from + 9;
12190          if ((to = strchr(ptr, '&')))
12191             *to = '\0';
12192          if ((to = strchr(ptr, ';')))
12193             *to = '\0';
12194          ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
12195       }
12196       
12197       if (!pedanticsipchecking)
12198          ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
12199       else
12200          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>" );
12201    }
12202    
12203    if ((ptr = strchr(refer_to, '@'))) {   /* Separate domain */
12204       char *urioption = NULL, *domain;
12205       *ptr++ = '\0';
12206 
12207       if ((urioption = strchr(ptr, ';'))) /* Separate urioptions */
12208          *urioption++ = '\0';
12209       
12210       domain = ptr;
12211       if ((ptr = strchr(domain, ':'))) /* Remove :port */
12212          *ptr = '\0';
12213       
12214       /* Save the domain for the dial plan */
12215       ast_copy_string(referdata->refer_to_domain, domain, sizeof(referdata->refer_to_domain));
12216       if (urioption)
12217          ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
12218    }
12219 
12220    if ((ptr = strchr(refer_to, ';')))  /* Remove options */
12221       *ptr = '\0';
12222    ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
12223    
12224    if (referred_by_uri) {
12225       if ((ptr = strchr(referred_by_uri, ';')))    /* Remove options */
12226          *ptr = '\0';
12227       ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
12228    } else {
12229       referdata->referred_by[0] = '\0';
12230    }
12231 
12232    /* Determine transfer context */
12233    if (transferer->owner)  /* Mimic behaviour in res_features.c */
12234       transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
12235 
12236    /* By default, use the context in the channel sending the REFER */
12237    if (ast_strlen_zero(transfer_context)) {
12238       transfer_context = S_OR(transferer->owner->macrocontext,
12239                S_OR(transferer->context, default_context));
12240    }
12241 
12242    ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
12243    
12244    /* Either an existing extension or the parking extension */
12245    if (referdata->attendedtransfer || ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
12246       if (sip_debug_test_pvt(transferer)) {
12247          ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
12248       }
12249       /* We are ready to transfer to the extension */
12250       return 0;
12251    } 
12252    if (sip_debug_test_pvt(transferer))
12253       ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
12254 
12255    /* Failure, we can't find this extension */
12256    return -1;
12257 }
12258 
12259 
12260 /*! \brief Call transfer support (old way, deprecated by the IETF)--*/
12261 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
12262 {
12263    char tmp[256] = "", *c, *a;
12264    struct sip_request *req = oreq ? oreq : &p->initreq;
12265    struct sip_refer *referdata = NULL;
12266    const char *transfer_context = NULL;
12267    
12268    if (!p->refer && !sip_refer_allocate(p))
12269       return -1;
12270 
12271    referdata = p->refer;
12272 
12273    ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
12274    c = get_in_brackets(tmp);
12275 
12276    if (pedanticsipchecking)
12277       ast_uri_decode(c);
12278 
12279    if (!strncasecmp(c, "sip:", 4)) {
12280       c += 4;
12281    } else if (!strncasecmp(c, "sips:", 5)) {
12282       c += 5;
12283    } else {
12284       ast_log(LOG_WARNING, "Huh?  Not a SIP header in Also: transfer (%s)?\n", c);
12285       return -1;
12286    }
12287 
12288    if ((a = strchr(c, ';')))  /* Remove arguments */
12289       *a = '\0';
12290    
12291    if ((a = strchr(c, '@'))) {   /* Separate Domain */
12292       *a++ = '\0';
12293       ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
12294    }
12295    
12296    if (sip_debug_test_pvt(p))
12297       ast_verbose("Looking for %s in %s\n", c, p->context);
12298 
12299    if (p->owner)  /* Mimic behaviour in res_features.c */
12300       transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
12301 
12302    /* By default, use the context in the channel sending the REFER */
12303    if (ast_strlen_zero(transfer_context)) {
12304       transfer_context = S_OR(p->owner->macrocontext,
12305                S_OR(p->context, default_context));
12306    }
12307    if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
12308       /* This is a blind transfer */
12309       ast_debug(1, "SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
12310       ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
12311       ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
12312       ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
12313       referdata->refer_call = dialog_unref(referdata->refer_call, "unreffing referdata->refer_call");
12314       /* Set new context */
12315       ast_string_field_set(p, context, transfer_context);
12316       return 0;
12317    } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
12318       return 1;
12319    }
12320 
12321    return -1;
12322 }
12323 
12324 /*! \brief check received= and rport= in a SIP response.
12325  * If we get a response with received= and/or rport= in the Via:
12326  * line, use them as 'p->ourip' (see RFC 3581 for rport,
12327  * and RFC 3261 for received).
12328  * Using these two fields SIP can produce the correct
12329  * address and port in the SIP headers without the need for STUN.
12330  * The address part is also reused for the media sessions.
12331  * Note that ast_sip_ouraddrfor() still rewrites p->ourip
12332  * if you specify externip/seternaddr/stunaddr.
12333  */
12334 static attribute_unused void check_via_response(struct sip_pvt *p, struct sip_request *req)
12335 {
12336    char via[256];
12337    char *cur, *opts;
12338 
12339    ast_copy_string(via, get_header(req, "Via"), sizeof(via));
12340 
12341    /* Work on the leftmost value of the topmost Via header */
12342    opts = strchr(via, ',');
12343    if (opts)
12344       *opts = '\0';
12345 
12346    /* parse all relevant options */
12347    opts = strchr(via, ';');
12348    if (!opts)
12349       return;  /* no options to parse */
12350    *opts++ = '\0';
12351    while ( (cur = strsep(&opts, ";")) ) {
12352       if (!strncmp(cur, "rport=", 6)) {
12353          int port = strtol(cur+6, NULL, 10);
12354          /* XXX add error checking */
12355          p->ourip.sin_port = ntohs(port);
12356       } else if (!strncmp(cur, "received=", 9)) {
12357          if (ast_parse_arg(cur+9, PARSE_INADDR, &p->ourip))
12358             ;  /* XXX add error checking */
12359       }
12360    }
12361 }
12362 
12363 /*! \brief check Via: header for hostname, port and rport request/answer */
12364 static void check_via(struct sip_pvt *p, struct sip_request *req)
12365 {
12366    char via[512];
12367    char *c, *pt;
12368    struct hostent *hp;
12369    struct ast_hostent ahp;
12370 
12371    ast_copy_string(via, get_header(req, "Via"), sizeof(via));
12372 
12373    /* Work on the leftmost value of the topmost Via header */
12374    c = strchr(via, ',');
12375    if (c)
12376       *c = '\0';
12377 
12378    /* Check for rport */
12379    c = strstr(via, ";rport");
12380    if (c && (c[6] != '=')) /* rport query, not answer */
12381       ast_set_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT);
12382 
12383    c = strchr(via, ';');
12384    if (c) 
12385       *c = '\0';
12386 
12387    c = strchr(via, ' ');
12388    if (c) {
12389       *c = '\0';
12390       c = ast_skip_blanks(c+1);
12391       if (strcasecmp(via, "SIP/2.0/UDP") && strcasecmp(via, "SIP/2.0/TCP") && strcasecmp(via, "SIP/2.0/TLS")) {
12392          ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
12393          return;
12394       }
12395       pt = strchr(c, ':');
12396       if (pt)
12397          *pt++ = '\0';  /* remember port pointer */
12398       hp = ast_gethostbyname(c, &ahp);
12399       if (!hp) {
12400          ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
12401          return;
12402       }
12403       memset(&p->sa, 0, sizeof(p->sa));
12404       p->sa.sin_family = AF_INET;
12405       memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
12406       p->sa.sin_port = htons(pt ? atoi(pt) : STANDARD_SIP_PORT);
12407 
12408       if (sip_debug_test_pvt(p)) {
12409          const struct sockaddr_in *dst = sip_real_dst(p);
12410          ast_verbose("Sending to %s : %d (%s)\n", ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), sip_nat_mode(p));
12411       }
12412    }
12413 }
12414 
12415 /*! \brief  Get caller id name from SIP headers */
12416 static char *get_calleridname(const char *input, char *output, size_t outputsize)
12417 {
12418    const char *end = strchr(input, '<');  /* first_bracket */
12419    const char *tmp = strchr(input, '"');  /* first quote */
12420    int bytes = 0;
12421    int maxbytes = outputsize - 1;
12422 
12423    if (!end || end == input)  /* we require a part in brackets */
12424       return NULL;
12425 
12426    end--; /* move just before "<" */
12427 
12428    if (tmp && tmp <= end) {
12429       /* The quote (tmp) precedes the bracket (end+1).
12430        * Find the matching quote and return the content.
12431        */
12432       end = strchr(tmp+1, '"');
12433       if (!end)
12434          return NULL;
12435       bytes = (int) (end - tmp);
12436       /* protect the output buffer */
12437       if (bytes > maxbytes)
12438          bytes = maxbytes;
12439       ast_copy_string(output, tmp + 1, bytes);
12440    } else {
12441       /* No quoted string, or it is inside brackets. */
12442       /* clear the empty characters in the begining*/
12443       input = ast_skip_blanks(input);
12444       /* clear the empty characters in the end */
12445       while(*end && *end < 33 && end > input)
12446          end--;
12447       if (end >= input) {
12448          bytes = (int) (end - input) + 2;
12449          /* protect the output buffer */
12450          if (bytes > maxbytes)
12451             bytes = maxbytes;
12452          ast_copy_string(output, input, bytes);
12453       } else
12454          return NULL;
12455    }
12456    return output;
12457 }
12458 
12459 /*! \brief  Get caller id number from Remote-Party-ID header field 
12460  * Returns true if number should be restricted (privacy setting found)
12461  * output is set to NULL if no number found
12462  */
12463 static int get_rpid_num(const char *input, char *output, int maxlen)
12464 {
12465    char *start;
12466    char *end;
12467 
12468    start = strchr(input, ':');
12469    if (!start) {
12470       output[0] = '\0';
12471       return 0;
12472    }
12473    start++;
12474 
12475    /* we found "number" */
12476    ast_copy_string(output, start, maxlen);
12477    output[maxlen-1] = '\0';
12478 
12479    end = strchr(output, '@');
12480    if (end)
12481       *end = '\0';
12482    else
12483       output[0] = '\0';
12484    if (strstr(input, "privacy=full") || strstr(input, "privacy=uri"))
12485       return AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
12486 
12487    return 0;
12488 }
12489 
12490 /*!
12491  * duplicate a list of channel variables, \return the copy.
12492  */
12493 static struct ast_variable *copy_vars(struct ast_variable *src)
12494 {
12495    struct ast_variable *res = NULL, *tmp, *v = NULL;
12496 
12497    for (v = src ; v ; v = v->next) {
12498       if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
12499          tmp->next = res;
12500          res = tmp;
12501       }
12502    }
12503    return res;
12504 }
12505 
12506 /*! \brief helper function for check_{user|peer}_ok() */
12507 static void replace_cid(struct sip_pvt *p, const char *rpid_num, const char *calleridname)
12508 {
12509    /* replace callerid if rpid found, and not restricted */
12510    if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
12511       char *tmp = ast_strdupa(rpid_num); /* XXX the copy can be done later */
12512       if (!ast_strlen_zero(calleridname))
12513          ast_string_field_set(p, cid_name, calleridname);
12514       if (ast_is_shrinkable_phonenumber(tmp))
12515          ast_shrink_phone_number(tmp);
12516       ast_string_field_set(p, cid_num, tmp);
12517    }
12518 }
12519 
12520 /*! \brief Validate device authentication */
12521 static enum check_auth_result check_peer_ok(struct sip_pvt *p, char *of,
12522    struct sip_request *req, int sipmethod, struct sockaddr_in *sin,
12523    struct sip_peer **authpeer,
12524    enum xmittype reliable,
12525    char *rpid_num, char *calleridname, char *uri2)
12526 {
12527    enum check_auth_result res;
12528    int debug=sip_debug_test_addr(sin);
12529    struct sip_peer *peer;
12530 
12531    if (sipmethod == SIP_SUBSCRIBE) {
12532       /* For subscribes, match on device name only; for other methods,
12533       * match on IP address-port of the incoming request.
12534       */
12535       peer = find_peer(of, NULL, TRUE, FINDALLDEVICES, FALSE);
12536    } else {
12537       /* First find devices based on username (avoid all type=peer's) */
12538       peer = find_peer(of, NULL, TRUE, FINDUSERS, FALSE);
12539 
12540       /* Then find devices based on IP */
12541       if (!peer) {
12542          peer = find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE);
12543       }
12544 
12545       /* If the peer is still not found, try the address and port from the
12546        * contact header.  If the transport type is TCP or TLS it is not possible
12547        * to find the peer using p->recv. Because of the way TCP works, the received
12548        * packet's destination port will not match the one the peer table is
12549        * built with. */
12550       if (!peer && (p->socket.type != SIP_TRANSPORT_UDP)) {
12551          struct sockaddr_in tmpsin;
12552          char contact[SIPBUFSIZE];
12553          char *tmp;
12554          memcpy(&tmpsin, &p->recv, sizeof(tmpsin));
12555          ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
12556          tmp = get_in_brackets(contact);
12557          __set_address_from_contact(tmp, &tmpsin, 1);
12558          peer = find_peer(NULL, &tmpsin, TRUE, FINDPEERS, FALSE);
12559       }
12560    }
12561 
12562    if (!peer) {
12563       if (debug)
12564          ast_verbose("No matching peer for '%s' from '%s:%d'\n",
12565             of, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
12566       return AUTH_DONT_KNOW;
12567    }
12568    if (!ast_apply_ha(peer->ha, sin)) {
12569       ast_debug(2, "Found peer '%s' for '%s', but fails host access\n", peer->name, of);
12570       unref_peer(peer, "unref_peer: check_peer_ok: from find_peer call, early return of AUTH_ACL_FAILED");
12571       return AUTH_ACL_FAILED;
12572    }
12573    if (debug)
12574       ast_verbose("Found peer '%s' for '%s' from %s:%d\n",
12575          peer->name, of, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
12576 
12577    /* XXX what about p->prefs = peer->prefs; ? */
12578    /* Set Frame packetization */
12579    if (p->rtp) {
12580       ast_rtp_codec_setpref(p->rtp, &peer->prefs);
12581       p->autoframing = peer->autoframing;
12582    }
12583 
12584    /* Take the peer */
12585    ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
12586    ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
12587 
12588    if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && p->udptl) {
12589       set_t38_capabilities(p);
12590    }
12591 
12592    /* Copy SIP extensions profile to peer */
12593    /* XXX is this correct before a successful auth ? */
12594    if (p->sipoptions)
12595       peer->sipoptions = p->sipoptions;
12596 
12597    replace_cid(p, rpid_num, calleridname);
12598    do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE));
12599 
12600    ast_string_field_set(p, peersecret, peer->secret);
12601    ast_string_field_set(p, peermd5secret, peer->md5secret);
12602    ast_string_field_set(p, subscribecontext, peer->subscribecontext);
12603    ast_string_field_set(p, mohinterpret, peer->mohinterpret);
12604    ast_string_field_set(p, mohsuggest, peer->mohsuggest);
12605    ast_string_field_set(p, parkinglot, peer->parkinglot);
12606    if (peer->callingpres)  /* Peer calling pres setting will override RPID */
12607       p->callingpres = peer->callingpres;
12608    if (peer->maxms && peer->lastms)
12609       p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
12610    else
12611       p->timer_t1 = peer->timer_t1;
12612  
12613    /* Set timer B to control transaction timeouts */
12614    if (peer->timer_b)
12615       p->timer_b = peer->timer_b;
12616    else
12617       p->timer_b = 64 * p->timer_t1;
12618  
12619    if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
12620       /* Pretend there is no required authentication */
12621       ast_string_field_set(p, peersecret, NULL);
12622       ast_string_field_set(p, peermd5secret, NULL);
12623    }
12624    if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, req->ignore))) {
12625       ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
12626       ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
12627       /* If we have a call limit, set flag */
12628       if (peer->call_limit)
12629          ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
12630       ast_string_field_set(p, peername, peer->name);
12631       ast_string_field_set(p, authname, peer->name);
12632 
12633       if (sipmethod == SIP_INVITE) {
12634          /* copy channel vars */
12635          p->chanvars = copy_vars(peer->chanvars);
12636       }
12637 
12638       if (authpeer) {
12639          ao2_t_ref(peer, 1, "copy pointer into (*authpeer)");
12640          (*authpeer) = peer;  /* Add a ref to the object here, to keep it in memory a bit longer if it is realtime */
12641       }
12642 
12643       if (!ast_strlen_zero(peer->username)) {
12644          ast_string_field_set(p, username, peer->username);
12645          /* Use the default username for authentication on outbound calls */
12646          /* XXX this takes the name from the caller... can we override ? */
12647          ast_string_field_set(p, authname, peer->username);
12648       }
12649       if (!ast_strlen_zero(peer->cid_num)) {
12650          char *tmp = ast_strdupa(peer->cid_num);
12651          if (ast_is_shrinkable_phonenumber(tmp))
12652             ast_shrink_phone_number(tmp);
12653          ast_string_field_set(p, cid_num, tmp);
12654       }
12655       if (!ast_strlen_zero(peer->cid_name)) 
12656          ast_string_field_set(p, cid_name, peer->cid_name);
12657       ast_string_field_set(p, fullcontact, peer->fullcontact);
12658       if (!ast_strlen_zero(peer->context))
12659          ast_string_field_set(p, context, peer->context);
12660       ast_string_field_set(p, peersecret, peer->secret);
12661       ast_string_field_set(p, peermd5secret, peer->md5secret);
12662       ast_string_field_set(p, language, peer->language);
12663       ast_string_field_set(p, accountcode, peer->accountcode);
12664       p->amaflags = peer->amaflags;
12665       p->callgroup = peer->callgroup;
12666       p->pickupgroup = peer->pickupgroup;
12667       p->capability = peer->capability;
12668       p->prefs = peer->prefs;
12669       p->jointcapability = peer->capability;
12670       if (p->peercapability)
12671          p->jointcapability &= p->peercapability;
12672       p->maxcallbitrate = peer->maxcallbitrate;
12673       if (!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) &&
12674             (!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
12675                !(p->capability & AST_FORMAT_VIDEO_MASK)) &&
12676             p->vrtp) {
12677          ast_rtp_destroy(p->vrtp);
12678          p->vrtp = NULL;
12679       }
12680       if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) || !(p->capability & AST_FORMAT_TEXT_MASK)) && p->trtp) {
12681          ast_rtp_destroy(p->trtp);
12682          p->trtp = NULL;
12683       }
12684       if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
12685           (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
12686          p->noncodeccapability |= AST_RTP_DTMF;
12687       else
12688          p->noncodeccapability &= ~AST_RTP_DTMF;
12689       p->jointnoncodeccapability = p->noncodeccapability;
12690    }
12691    unref_peer(peer, "check_peer_ok: unref_peer: tossing temp ptr to peer from find_peer");
12692    return res;
12693 }
12694 
12695 
12696 /*! \brief  Check if matching user or peer is defined 
12697    Match user on From: user name and peer on IP/port
12698    This is used on first invite (not re-invites) and subscribe requests 
12699     \return 0 on success, non-zero on failure
12700 */
12701 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
12702                      int sipmethod, char *uri, enum xmittype reliable,
12703                      struct sockaddr_in *sin, struct sip_peer **authpeer)
12704 {
12705    char from[256];
12706    char *dummy;   /* dummy return value for parse_uri */
12707    char *domain;  /* dummy return value for parse_uri */
12708    char *of, *of2;
12709    char rpid_num[50];
12710    const char *rpid;
12711    enum check_auth_result res;
12712    char calleridname[50];
12713    char *uri2 = ast_strdupa(uri);
12714 
12715    terminate_uri(uri2); /* trim extra stuff */
12716 
12717    ast_copy_string(from, get_header(req, "From"), sizeof(from));
12718    if (pedanticsipchecking)
12719       ast_uri_decode(from);
12720    /* XXX here tries to map the username for invite things */
12721    memset(calleridname, 0, sizeof(calleridname));
12722    get_calleridname(from, calleridname, sizeof(calleridname));
12723    if (calleridname[0])
12724       ast_string_field_set(p, cid_name, calleridname);
12725 
12726    rpid = get_header(req, "Remote-Party-ID");
12727    memset(rpid_num, 0, sizeof(rpid_num));
12728    if (!ast_strlen_zero(rpid)) 
12729       p->callingpres = get_rpid_num(rpid, rpid_num, sizeof(rpid_num));
12730 
12731    of = get_in_brackets(from);
12732    if (ast_strlen_zero(p->exten)) {
12733       char *t = uri2;
12734       if (!strncasecmp(t, "sip:", 4))
12735          t+= 4;
12736       else if (!strncasecmp(t, "sips:", 5))
12737          t += 5;
12738       ast_string_field_set(p, exten, t);
12739       t = strchr(p->exten, '@');
12740       if (t)
12741          *t = '\0';
12742       if (ast_strlen_zero(p->our_contact))
12743          build_contact(p);
12744    }
12745    /* save the URI part of the From header */
12746    ast_string_field_set(p, from, of);
12747 
12748    of2 = ast_strdupa(of);
12749 
12750    /* ignore all fields but name */
12751    if (p->socket.type == SIP_TRANSPORT_TLS) {
12752       if (parse_uri(of, "sips:", &of, &dummy, &domain, &dummy, &dummy, NULL)) {
12753          if (parse_uri(of2, "sip:", &of, &dummy, &domain, &dummy, &dummy, NULL))
12754             ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
12755       }
12756    } else {
12757       if (parse_uri(of, "sip:", &of, &dummy, &domain, &dummy, &dummy, NULL))
12758          ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
12759    }
12760 
12761    if (ast_strlen_zero(of)) {
12762       /* XXX note: the original code considered a missing @host
12763        * as a username-only URI. The SIP RFC (19.1.1) says that
12764        * this is wrong, and it should be considered as a domain-only URI.
12765        * For backward compatibility, we keep this block, but it is
12766        * really a mistake and should go away.
12767        */
12768       of = domain;
12769    } else {
12770       char *tmp = ast_strdupa(of);
12771       /* We need to be able to handle auth-headers looking like
12772          <sip:8164444422;phone-context=+1@1.2.3.4:5060;user=phone;tag=SDadkoa01-gK0c3bdb43>
12773       */
12774       tmp = strsep(&tmp, ";");
12775       if (ast_is_shrinkable_phonenumber(tmp))
12776          ast_shrink_phone_number(tmp);
12777       ast_string_field_set(p, cid_num, tmp);
12778    }
12779 
12780    if (global_match_auth_username) {
12781       /*
12782        * XXX This is experimental code to grab the search key from the
12783        * Auth header's username instead of the 'From' name, if available.
12784        * Do not enable this block unless you understand the side effects (if any!)
12785        * Note, the search for "username" should be done in a more robust way.
12786        * Note2, at the moment we check both fields, though maybe we should
12787        * pick one or another depending on the request ? XXX
12788        */
12789       const char *hdr = get_header(req, "Authorization");
12790       if (ast_strlen_zero(hdr))
12791          hdr = get_header(req, "Proxy-Authorization");
12792 
12793       if ( !ast_strlen_zero(hdr) && (hdr = strstr(hdr, "username=\"")) ) {
12794          ast_copy_string(from, hdr + strlen("username=\""), sizeof(from));
12795          of = from;
12796          of = strsep(&of, "\"");
12797       }
12798    }
12799 
12800    res = check_peer_ok(p, of, req, sipmethod, sin,
12801          authpeer, reliable, rpid_num, calleridname, uri2);
12802    if (res != AUTH_DONT_KNOW)
12803       return res;
12804 
12805    /* Finally, apply the guest policy */
12806    if (global_allowguest) {
12807       replace_cid(p, rpid_num, calleridname);
12808       res = AUTH_SUCCESSFUL;
12809    } else if (global_alwaysauthreject)
12810       res = AUTH_FAKE_AUTH; /* reject with fake authorization request */
12811    else
12812       res = AUTH_SECRET_FAILED; /* we don't want any guests, authentication will fail */
12813 
12814 
12815    if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT)) {
12816       ast_set_flag(&p->flags[0], SIP_NAT_ROUTE);
12817    }
12818 
12819    return res;
12820 }
12821 
12822 /*! \brief  Find user 
12823    If we get a match, this will add a reference pointer to the user object in ASTOBJ, that needs to be unreferenced
12824 */
12825 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin)
12826 {
12827    return check_user_full(p, req, sipmethod, uri, reliable, sin, NULL);
12828 }
12829 
12830 /*! \brief  Get text out of a SIP MESSAGE packet */
12831 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline)
12832 {
12833    int x;
12834    int y;
12835 
12836    buf[0] = '\0';
12837    /*XXX isn't strlen(buf) going to always be 0? */
12838    y = len - strlen(buf) - 5;
12839    if (y < 0)
12840       y = 0;
12841    for (x = 0; x < req->lines; x++) {
12842       char *line = REQ_OFFSET_TO_STR(req, line[x]);
12843       strncat(buf, line, y); /* safe */
12844       y -= strlen(line) + 1;
12845       if (y < 0)
12846          y = 0;
12847       if (y != 0 && addnewline)
12848          strcat(buf, "\n"); /* safe */
12849    }
12850    return 0;
12851 }
12852 
12853 
12854 /*! \brief  Receive SIP MESSAGE method messages
12855 \note We only handle messages within current calls currently 
12856    Reference: RFC 3428 */
12857 static void receive_message(struct sip_pvt *p, struct sip_request *req)
12858 {
12859    char buf[1400];   
12860    struct ast_frame f;
12861    const char *content_type = get_header(req, "Content-Type");
12862 
12863    if (strncmp(content_type, "text/plain", strlen("text/plain"))) { /* No text/plain attachment */
12864       transmit_response(p, "415 Unsupported Media Type", req); /* Good enough, or? */
12865       if (!p->owner)
12866          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12867       return;
12868    }
12869 
12870    if (get_msg_text(buf, sizeof(buf), req, FALSE)) {
12871       ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
12872       transmit_response(p, "202 Accepted", req);
12873       if (!p->owner)
12874          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12875       return;
12876    }
12877 
12878    if (p->owner) {
12879       if (sip_debug_test_pvt(p))
12880          ast_verbose("SIP Text message received: '%s'\n", buf);
12881       memset(&f, 0, sizeof(f));
12882       f.frametype = AST_FRAME_TEXT;
12883       f.subclass = 0;
12884       f.offset = 0;
12885       f.data.ptr = buf;
12886       f.datalen = strlen(buf);
12887       ast_queue_frame(p->owner, &f);
12888       transmit_response(p, "202 Accepted", req); /* We respond 202 accepted, since we relay the message */
12889       return;
12890    }
12891 
12892    /* Message outside of a call, we do not support that */
12893    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);
12894    transmit_response(p, "405 Method Not Allowed", req);
12895    sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12896    return;
12897 }
12898 
12899 /*! \brief  CLI Command to show calls within limits set by call_limit */
12900 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
12901 {
12902 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
12903 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
12904    char ilimits[40];
12905    char iused[40];
12906    int showall = FALSE;
12907    struct ao2_iterator i;
12908    struct sip_peer *peer;
12909    
12910    switch (cmd) {
12911    case CLI_INIT:
12912       e->command = "sip show inuse";
12913       e->usage =
12914          "Usage: sip show inuse [all]\n"
12915          "       List all SIP devices usage counters and limits.\n"
12916          "       Add option \"all\" to show all devices, not only those with a limit.\n";
12917       return NULL;
12918    case CLI_GENERATE:
12919       return NULL;
12920    }
12921 
12922    if (a->argc < 3) 
12923       return CLI_SHOWUSAGE;
12924 
12925    if (a->argc == 4 && !strcmp(a->argv[3], "all")) 
12926       showall = TRUE;
12927    
12928    ast_cli(a->fd, FORMAT, "* Peer name", "In use", "Limit");
12929 
12930    i = ao2_iterator_init(peers, 0);
12931 
12932    while ((peer = ao2_t_iterator_next(&i, "iterate thru peer table"))) {
12933       ao2_lock(peer);
12934       if (peer->call_limit)
12935          snprintf(ilimits, sizeof(ilimits), "%d", peer->call_limit);
12936       else 
12937          ast_copy_string(ilimits, "N/A", sizeof(ilimits));
12938       snprintf(iused, sizeof(iused), "%d/%d/%d", peer->inUse, peer->inRinging, peer->onHold);
12939       if (showall || peer->call_limit)
12940          ast_cli(a->fd, FORMAT2, peer->name, iused, ilimits);
12941       ao2_unlock(peer);
12942       unref_peer(peer, "toss iterator pointer");
12943    }
12944 
12945    return CLI_SUCCESS;
12946 #undef FORMAT
12947 #undef FORMAT2
12948 }
12949 
12950 
12951 /*! \brief Convert transfer mode to text string */
12952 static char *transfermode2str(enum transfermodes mode)
12953 {
12954    if (mode == TRANSFER_OPENFORALL)
12955       return "open";
12956    else if (mode == TRANSFER_CLOSED)
12957       return "closed";
12958    return "strict";
12959 }
12960 
12961 static struct _map_x_s natmodes[] = {
12962    { SIP_NAT_NEVER,        "No"},
12963    { SIP_NAT_ROUTE,        "Route"},
12964    { SIP_NAT_ALWAYS,       "Always"},
12965    { SIP_NAT_RFC3581,      "RFC3581"},
12966    { -1,                   NULL}, /* terminator */
12967 };
12968 
12969 /*! \brief  Convert NAT setting to text string */
12970 static const char *nat2str(int nat)
12971 {
12972    return map_x_s(natmodes, nat, "Unknown");
12973 }
12974 
12975 #ifdef NOTUSED
12976 /* OEJ: This is not used, but may be useful in the future, so I don't want to 
12977    delete it. Keeping it enabled generates compiler warnings.
12978  */
12979 
12980 static struct _map_x_s natcfgmodes[] = {
12981    { SIP_NAT_NEVER,        "never"},
12982    { SIP_NAT_ROUTE,        "route"},
12983    { SIP_NAT_ALWAYS,       "yes"},
12984    { SIP_NAT_RFC3581,      "no"},
12985    { -1,                   NULL}, /* terminator */
12986 };
12987 
12988 /*! \brief  Convert NAT setting to text string appropriate for config files */
12989 static const char *nat2strconfig(int nat)
12990 {
12991    return map_x_s(natcfgmodes, nat, "Unknown");
12992 }
12993 #endif
12994 
12995 /*! \brief  Report Peer status in character string
12996  *  \return 0 if peer is unreachable, 1 if peer is online, -1 if unmonitored
12997  */
12998 
12999 
13000 /* Session-Timer Modes */
13001 static struct _map_x_s stmodes[] = {
13002         { SESSION_TIMER_MODE_ACCEPT,    "Accept"},
13003         { SESSION_TIMER_MODE_ORIGINATE, "Originate"},
13004         { SESSION_TIMER_MODE_REFUSE,    "Refuse"},
13005         { -1,                           NULL},
13006 };
13007 
13008 static const char *stmode2str(enum st_mode m)
13009 {
13010    return map_x_s(stmodes, m, "Unknown");
13011 }
13012 
13013 static enum st_mode str2stmode(const char *s)
13014 {
13015    return map_s_x(stmodes, s, -1);
13016 }
13017 
13018 /* Session-Timer Refreshers */
13019 static struct _map_x_s strefreshers[] = {
13020         { SESSION_TIMER_REFRESHER_AUTO,     "auto"},
13021         { SESSION_TIMER_REFRESHER_UAC,      "uac"},
13022         { SESSION_TIMER_REFRESHER_UAS,      "uas"},
13023         { -1,                               NULL},
13024 };
13025 
13026 static const char *strefresher2str(enum st_refresher r)
13027 {
13028    return map_x_s(strefreshers, r, "Unknown");
13029 }
13030 
13031 static enum st_refresher str2strefresher(const char *s)
13032 {
13033    return map_s_x(strefreshers, s, -1);
13034 }
13035 
13036 
13037 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
13038 {
13039    int res = 0;
13040    if (peer->maxms) {
13041       if (peer->lastms < 0) {
13042          ast_copy_string(status, "UNREACHABLE", statuslen);
13043       } else if (peer->lastms > peer->maxms) {
13044          snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
13045          res = 1;
13046       } else if (peer->lastms) {
13047          snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
13048          res = 1;
13049       } else {
13050          ast_copy_string(status, "UNKNOWN", statuslen);
13051       }
13052    } else { 
13053       ast_copy_string(status, "Unmonitored", statuslen);
13054       /* Checking if port is 0 */
13055       res = -1;
13056    }
13057    return res;
13058 }
13059 
13060 /*! \brief return Yes or No depending on the argument.
13061  * This is used in many places in CLI command, having a function to generate
13062  * this helps maintaining a consistent output (and possibly emitting the
13063  * output in other languages, at some point).
13064  */
13065 static const char *cli_yesno(int x)
13066 {
13067    return x ? "Yes" : "No";
13068 }
13069 
13070 /*! \brief  Show active TCP connections */
13071 static char *sip_show_tcp(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13072 {
13073    struct sip_threadinfo *th;
13074 
13075 #define FORMAT2 "%-30.30s %3.6s %9.9s %6.6s\n"
13076 #define FORMAT  "%-30.30s %-6d %-9.9s %-6.6s\n"
13077 
13078    switch (cmd) {
13079    case CLI_INIT:
13080       e->command = "sip show tcp";
13081       e->usage =
13082          "Usage: sip show tcp\n"
13083          "       Lists all active TCP/TLS sessions.\n";
13084       return NULL;
13085    case CLI_GENERATE:
13086       return NULL;
13087    }
13088 
13089    if (a->argc != 3)
13090       return CLI_SHOWUSAGE;
13091 
13092    ast_cli(a->fd, FORMAT2, "Host", "Port", "Transport", "Type");
13093    AST_LIST_LOCK(&threadl);
13094    AST_LIST_TRAVERSE(&threadl, th, list) {
13095       ast_cli(a->fd, FORMAT, ast_inet_ntoa(th->tcptls_session->remote_address.sin_addr), 
13096          ntohs(th->tcptls_session->remote_address.sin_port), 
13097          get_transport(th->type), 
13098          (th->tcptls_session->client ? "Client" : "Server"));
13099 
13100    }
13101    AST_LIST_UNLOCK(&threadl);
13102    return CLI_SUCCESS;
13103 #undef FORMAT
13104 #undef FORMAT2
13105 }
13106 
13107 /*! \brief  CLI Command 'SIP Show Users' */
13108 static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13109 {
13110    regex_t regexbuf;
13111    int havepattern = FALSE;
13112    struct ao2_iterator user_iter;
13113    struct sip_peer *user;
13114 
13115 #define FORMAT  "%-25.25s  %-15.15s  %-15.15s  %-15.15s  %-5.5s%-10.10s\n"
13116 
13117    switch (cmd) {
13118    case CLI_INIT:
13119       e->command = "sip show users";
13120       e->usage =
13121          "Usage: sip show users [like <pattern>]\n"
13122          "       Lists all known SIP users.\n"
13123          "       Optional regular expression pattern is used to filter the user list.\n";
13124       return NULL;
13125    case CLI_GENERATE:
13126       return NULL;
13127    }
13128 
13129    switch (a->argc) {
13130    case 5:
13131       if (!strcasecmp(a->argv[3], "like")) {
13132          if (regcomp(&regexbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
13133             return CLI_SHOWUSAGE;
13134          havepattern = TRUE;
13135       } else
13136          return CLI_SHOWUSAGE;
13137    case 3:
13138       break;
13139    default:
13140       return CLI_SHOWUSAGE;
13141    }
13142 
13143    ast_cli(a->fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "NAT");
13144 
13145    user_iter = ao2_iterator_init(peers, 0);
13146    while ((user = ao2_iterator_next(&user_iter))) {
13147       ao2_lock(user);
13148       if (!(user->type & SIP_TYPE_USER)) {
13149          ao2_unlock(user);
13150          unref_peer(user, "sip show users");
13151          continue;
13152       }
13153 
13154       if (havepattern && regexec(&regexbuf, user->name, 0, NULL, 0)) {
13155          ao2_unlock(user);
13156          unref_peer(user, "sip show users");
13157          continue;
13158       }
13159 
13160       ast_cli(a->fd, FORMAT, user->name, 
13161          user->secret, 
13162          user->accountcode,
13163          user->context,
13164          cli_yesno(user->ha != NULL),
13165          nat2str(ast_test_flag(&user->flags[0], SIP_NAT)));
13166       ao2_unlock(user);
13167       unref_peer(user, "sip show users");
13168    }
13169 
13170    if (havepattern)
13171       regfree(&regexbuf);
13172 
13173    return CLI_SUCCESS;
13174 #undef FORMAT
13175 }
13176 
13177 /*! \brief Manager Action SIPShowRegistry description */
13178 static char mandescr_show_registry[] =
13179 "Description: Lists all registration requests and status\n"
13180 "Registrations will follow as separate events. followed by a final event called\n"
13181 "RegistrationsComplete.\n"
13182 "Variables: \n"
13183 "  ActionID: <id>       Action ID for this transaction. Will be returned.\n";
13184 
13185 /*! \brief Show SIP registrations in the manager API */
13186 static int manager_show_registry(struct mansession *s, const struct message *m)
13187 {
13188    const char *id = astman_get_header(m, "ActionID");
13189    char idtext[256] = "";
13190    int total = 0;
13191 
13192    if (!ast_strlen_zero(id))
13193       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
13194 
13195    astman_send_listack(s, m, "Registrations will follow", "start");
13196 
13197    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
13198       ASTOBJ_RDLOCK(iterator);
13199       astman_append(s,
13200          "Event: RegistryEntry\r\n"
13201          "Host: %s\r\n"
13202          "Port: %d\r\n"
13203          "Username: %s\r\n"
13204          "Refresh: %d\r\n"
13205          "State: %s\r\n"
13206          "RegistrationTime: %ld\r\n"
13207          "\r\n", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT,
13208                  iterator->username, iterator->refresh, regstate2str(iterator->regstate), (long) iterator->regtime.tv_sec);
13209       ASTOBJ_UNLOCK(iterator);
13210       total++;
13211    } while(0));
13212 
13213    astman_append(s,
13214       "Event: RegistrationsComplete\r\n"
13215       "EventList: Complete\r\n"
13216       "ListItems: %d\r\n"
13217       "%s"
13218       "\r\n", total, idtext);
13219    
13220    return 0;
13221 }
13222 
13223 static char mandescr_show_peers[] = 
13224 "Description: Lists SIP peers in text format with details on current status.\n"
13225 "Peerlist will follow as separate events, followed by a final event called\n"
13226 "PeerlistComplete.\n"
13227 "Variables: \n"
13228 "  ActionID: <id> Action ID for this transaction. Will be returned.\n";
13229 
13230 /*! \brief  Show SIP peers in the manager API */
13231 /*    Inspired from chan_iax2 */
13232 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
13233 {
13234    const char *id = astman_get_header(m, "ActionID");
13235    const char *a[] = {"sip", "show", "peers"};
13236    char idtext[256] = "";
13237    int total = 0;
13238 
13239    if (!ast_strlen_zero(id))
13240       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
13241 
13242    astman_send_listack(s, m, "Peer status list will follow", "start");
13243    /* List the peers in separate manager events */
13244    _sip_show_peers(-1, &total, s, m, 3, a);
13245    /* Send final confirmation */
13246    astman_append(s,
13247    "Event: PeerlistComplete\r\n"
13248    "EventList: Complete\r\n"
13249    "ListItems: %d\r\n"
13250    "%s"
13251    "\r\n", total, idtext);
13252    return 0;
13253 }
13254 
13255 /*! \brief  CLI Show Peers command */
13256 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13257 {
13258    switch (cmd) {
13259    case CLI_INIT:
13260       e->command = "sip show peers";
13261       e->usage =
13262          "Usage: sip show peers [like <pattern>]\n"
13263          "       Lists all known SIP peers.\n"
13264          "       Optional regular expression pattern is used to filter the peer list.\n";
13265       return NULL;
13266    case CLI_GENERATE:
13267       return NULL;
13268    }
13269 
13270    return _sip_show_peers(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
13271 }
13272 
13273 int peercomparefunc(const void *a, const void *b);
13274 
13275 int peercomparefunc(const void *a, const void *b)
13276 {
13277    struct sip_peer **ap = (struct sip_peer **)a;
13278    struct sip_peer **bp = (struct sip_peer **)b;
13279    return strcmp((*ap)->name, (*bp)->name);
13280 }
13281 
13282 
13283 /*! \brief Execute sip show peers command */
13284 static char *_sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
13285 {
13286    regex_t regexbuf;
13287    int havepattern = FALSE;
13288    struct sip_peer *peer;
13289    struct ao2_iterator i;
13290    
13291 /* the last argument is left-aligned, so we don't need a size anyways */
13292 #define FORMAT2 "%-25.25s  %-15.15s %-3.3s %-3.3s %-3.3s %-8s %-10s %s\n"
13293 #define FORMAT  "%-25.25s  %-15.15s %-3.3s %-3.3s %-3.3s %-8d %-10s %s\n"
13294 
13295    char name[256];
13296    int total_peers = 0;
13297    int peers_mon_online = 0;
13298    int peers_mon_offline = 0;
13299    int peers_unmon_offline = 0;
13300    int peers_unmon_online = 0;
13301    const char *id;
13302    char idtext[256] = "";
13303    int realtimepeers;
13304    int objcount = ao2_container_count(peers);
13305    struct sip_peer **peerarray;
13306    int k;
13307    
13308    
13309    realtimepeers = ast_check_realtime("sippeers");
13310    peerarray = ast_calloc(sizeof(struct sip_peer *), objcount);
13311 
13312    if (s) { /* Manager - get ActionID */
13313       id = astman_get_header(m, "ActionID");
13314       if (!ast_strlen_zero(id))
13315          snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
13316    }
13317 
13318    switch (argc) {
13319    case 5:
13320       if (!strcasecmp(argv[3], "like")) {
13321          if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
13322             return CLI_SHOWUSAGE;
13323          havepattern = TRUE;
13324       } else
13325          return CLI_SHOWUSAGE;
13326    case 3:
13327       break;
13328    default:
13329       return CLI_SHOWUSAGE;
13330    }
13331 
13332    if (!s) /* Normal list */
13333       ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Nat", "ACL", "Port", "Status", (realtimepeers ? "Realtime" : ""));
13334    
13335 
13336    i = ao2_iterator_init(peers, 0);
13337    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {  
13338       ao2_lock(peer);
13339 
13340       if (!(peer->type & SIP_TYPE_PEER)) {
13341          ao2_unlock(peer);
13342          unref_peer(peer, "unref peer because it's actually a user");
13343          continue;
13344       }
13345 
13346       if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0)) {
13347          objcount--;
13348          ao2_unlock(peer);
13349          unref_peer(peer, "toss iterator peer ptr before continue");
13350          continue;
13351       }
13352 
13353       peerarray[total_peers++] = peer;
13354       ao2_unlock(peer);
13355    }
13356    
13357    qsort(peerarray, total_peers, sizeof(struct sip_peer *), peercomparefunc);
13358 
13359    for(k=0; k < total_peers; k++) {
13360       char status[20] = "";
13361       char srch[2000];
13362       char pstatus;
13363       peer = peerarray[k];
13364       
13365       ao2_lock(peer);
13366       if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0)) {
13367          ao2_unlock(peer);
13368          unref_peer(peer, "toss iterator peer ptr before continue");
13369          continue;
13370       }
13371 
13372       if (!ast_strlen_zero(peer->username) && !s)
13373          snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
13374       else
13375          ast_copy_string(name, peer->name, sizeof(name));
13376       
13377       pstatus = peer_status(peer, status, sizeof(status));
13378       if (pstatus == 1)
13379          peers_mon_online++;
13380       else if (pstatus == 0)
13381          peers_mon_offline++;
13382       else {
13383          if (peer->addr.sin_port == 0)
13384             peers_unmon_offline++;
13385          else
13386             peers_unmon_online++;
13387       }
13388 
13389       snprintf(srch, sizeof(srch), FORMAT, name,
13390          peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
13391          peer->host_dynamic ? " D " : "   ",    /* Dynamic or not? */
13392          ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? " N " : "   ", /* NAT=yes? */
13393          peer->ha ? " A " : "   ",  /* permit/deny */
13394          ntohs(peer->addr.sin_port), status,
13395          realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
13396 
13397       if (!s)  {/* Normal CLI list */
13398          ast_cli(fd, FORMAT, name, 
13399          peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
13400          peer->host_dynamic ? " D " : "   ",    /* Dynamic or not? */
13401          ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? " N " : "   ", /* NAT=yes? */
13402          peer->ha ? " A " : "   ",       /* permit/deny */
13403          
13404          ntohs(peer->addr.sin_port), status,
13405          realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
13406       } else { /* Manager format */
13407          /* The names here need to be the same as other channels */
13408          astman_append(s, 
13409          "Event: PeerEntry\r\n%s"
13410          "Channeltype: SIP\r\n"
13411          "ObjectName: %s\r\n"
13412          "ChanObjectType: peer\r\n" /* "peer" or "user" */
13413          "IPaddress: %s\r\n"
13414          "IPport: %d\r\n"
13415          "Dynamic: %s\r\n"
13416          "Natsupport: %s\r\n"
13417          "VideoSupport: %s\r\n"
13418          "TextSupport: %s\r\n"
13419          "ACL: %s\r\n"
13420          "Status: %s\r\n"
13421          "RealtimeDevice: %s\r\n\r\n", 
13422          idtext,
13423          peer->name, 
13424          peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "-none-",
13425          ntohs(peer->addr.sin_port), 
13426          peer->host_dynamic ? "yes" : "no",  /* Dynamic or not? */
13427          ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? "yes" : "no",  /* NAT=yes? */
13428          ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no",  /* VIDEOSUPPORT=yes? */
13429          ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "yes" : "no",   /* TEXTSUPPORT=yes? */
13430          peer->ha ? "yes" : "no",       /* permit/deny */
13431          status,
13432          realtimepeers ? (peer->is_realtime ? "yes":"no") : "no");
13433       }
13434       ao2_unlock(peer);
13435       unref_peer(peer, "toss iterator peer ptr");
13436    }
13437    
13438    if (!s)
13439       ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
13440               total_peers, peers_mon_online, peers_mon_offline, peers_unmon_online, peers_unmon_offline);
13441 
13442    if (havepattern)
13443       regfree(&regexbuf);
13444 
13445    if (total)
13446       *total = total_peers;
13447    
13448    ast_free(peerarray);
13449    
13450    return CLI_SUCCESS;
13451 #undef FORMAT
13452 #undef FORMAT2
13453 }
13454 
13455 static int peer_dump_func(void *userobj, void *arg, int flags)
13456 {
13457    struct sip_peer *peer = userobj;
13458    int refc = ao2_t_ref(userobj, 0, "");
13459    int *fd = arg;
13460    
13461    ast_cli(*fd, "name: %s\ntype: peer\nobjflags: %d\nrefcount: %d\n\n", 
13462           peer->name, 0, refc);
13463    return 0;
13464 }
13465 
13466 static int dialog_dump_func(void *userobj, void *arg, int flags)
13467 {
13468    struct sip_pvt *pvt = userobj;
13469    int refc = ao2_t_ref(userobj, 0, "");
13470    int *fd = arg;
13471    
13472    ast_cli(*fd, "name: %s\ntype: dialog\nobjflags: %d\nrefcount: %d\n\n", 
13473           pvt->callid, 0, refc);
13474    return 0;
13475 }
13476 
13477 
13478 /*! \brief List all allocated SIP Objects (realtime or static) */
13479 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13480 {
13481    char tmp[256];
13482    
13483    switch (cmd) {
13484    case CLI_INIT:
13485       e->command = "sip show objects";
13486       e->usage =
13487          "Usage: sip show objects\n"
13488          "       Lists status of known SIP objects\n";
13489       return NULL;
13490    case CLI_GENERATE:
13491       return NULL;
13492    }  
13493 
13494    if (a->argc != 3)
13495       return CLI_SHOWUSAGE;
13496    ast_cli(a->fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
13497    ao2_t_callback(peers, OBJ_NODATA, peer_dump_func, &a->fd, "initiate ao2_callback to dump peers");
13498    ast_cli(a->fd, "-= Registry objects: %d =-\n\n", regobjs);
13499    ASTOBJ_CONTAINER_DUMP(a->fd, tmp, sizeof(tmp), &regl);
13500    ast_cli(a->fd, "-= Dialog objects:\n\n");
13501    ao2_t_callback(dialogs, OBJ_NODATA, dialog_dump_func, &a->fd, "initiate ao2_callback to dump dialogs");
13502    return CLI_SUCCESS;
13503 }
13504 /*! \brief Print call group and pickup group */
13505 static void  print_group(int fd, ast_group_t group, int crlf)
13506 {
13507    char buf[256];
13508    ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
13509 }
13510 
13511 /*! \brief mapping between dtmf flags and strings */
13512 static struct _map_x_s dtmfstr[] = {
13513    { SIP_DTMF_RFC2833,     "rfc2833" },
13514    { SIP_DTMF_INFO,        "info" },
13515    { SIP_DTMF_SHORTINFO,   "shortinfo" },
13516    { SIP_DTMF_INBAND,      "inband" },
13517    { SIP_DTMF_AUTO,        "auto" },
13518    { -1,                   NULL }, /* terminator */
13519 };
13520 
13521 /*! \brief Convert DTMF mode to printable string */
13522 static const char *dtmfmode2str(int mode)
13523 {
13524    return map_x_s(dtmfstr, mode, "<error>");
13525 }
13526 
13527 /*! \brief maps a string to dtmfmode, returns -1 on error */
13528 static int str2dtmfmode(const char *str)
13529 {
13530    return map_s_x(dtmfstr, str, -1);
13531 }
13532 
13533 static struct _map_x_s insecurestr[] = {
13534    { SIP_INSECURE_PORT,    "port" },
13535    { SIP_INSECURE_INVITE,  "invite" },
13536    { SIP_INSECURE_PORT | SIP_INSECURE_INVITE, "port,invite" },
13537    { 0,                    "no" },
13538    { -1,                   NULL }, /* terminator */
13539 };
13540 
13541 /*! \brief Convert Insecure setting to printable string */
13542 static const char *insecure2str(int mode)
13543 {
13544    return map_x_s(insecurestr, mode, "<error>");
13545 }
13546 
13547 /*! \brief Destroy disused contexts between reloads
13548    Only used in reload_config so the code for regcontext doesn't get ugly
13549 */
13550 static void cleanup_stale_contexts(char *new, char *old)
13551 {
13552    char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
13553 
13554    while ((oldcontext = strsep(&old, "&"))) {
13555       stalecontext = '\0';
13556       ast_copy_string(newlist, new, sizeof(newlist));
13557       stringp = newlist;
13558       while ((newcontext = strsep(&stringp, "&"))) {
13559          if (!strcmp(newcontext, oldcontext)) {
13560             /* This is not the context you're looking for */
13561             stalecontext = '\0';
13562             break;
13563          } else if (strcmp(newcontext, oldcontext)) {
13564             stalecontext = oldcontext;
13565          }
13566          
13567       }
13568       if (stalecontext)
13569          ast_context_destroy(ast_context_find(stalecontext), "SIP");
13570    }
13571 }
13572 
13573 /* this func is used with ao2_callback to unlink/delete all dialogs that
13574    are marked needdestroy. It will return CMP_MATCH for candidates, and they
13575    will be unlinked */
13576 
13577 /* TODO: Implement a queue and instead of marking a dialog 
13578    to be destroyed, toss it into the queue. Have a separate
13579    thread do the locking and destruction */
13580 
13581 static int dialog_needdestroy(void *dialogobj, void *arg, int flags) 
13582 {
13583    struct sip_pvt *dialog = dialogobj;
13584    time_t *t = arg;
13585    
13586    /* log_show_lock(ao2_object_get_lockaddr(dialog)); this is an example of how to use log_show_lock() */
13587 
13588    if (sip_pvt_trylock(dialog)) {
13589       /* In very short-duration calls via sipp,
13590          this path gets executed fairly frequently (3% or so) even in low load
13591          situations; the routines we most commonly fight for a lock with:
13592          sip_answer (7 out of 9)
13593          sip_hangup (2 out of 9)
13594       */
13595       ao2_unlock(dialogs);
13596       usleep(1);
13597       ao2_lock(dialogs);
13598 
13599       /* I had previously returned CMP_STOP here; but changed it to return
13600          a zero instead, because there is no need to stop at the first sign
13601          of trouble. The old algorithm would restart in such circumstances,
13602          but there is no need for this now in astobj2-land. We'll
13603          just skip over this element this time, and catch it on the
13604          next traversal, which is about once a second or so. See the 
13605          ao2_callback call in do_monitor. We don't want the number of
13606          dialogs to back up too much between runs.
13607       */
13608       return 0;
13609    }
13610    
13611    /* Check RTP timeouts and kill calls if we have a timeout set and do not get RTP */
13612    check_rtp_timeout(dialog, *t);
13613 
13614    /* If we have sessions that needs to be destroyed, do it now */
13615    /* Check if we have outstanding requests not responsed to or an active call
13616       - if that's the case, wait with destruction */
13617    if (dialog->needdestroy && !dialog->packets && !dialog->owner) {
13618       /* We absolutely cannot destroy the rtp struct while a bridge is active or we WILL crash */
13619       if (dialog->rtp && ast_rtp_get_bridged(dialog->rtp)) {
13620          ast_debug(2, "Bridge still active.  Delaying destruction of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
13621          sip_pvt_unlock(dialog);
13622          return 0;
13623       }
13624       
13625       if (dialog->vrtp && ast_rtp_get_bridged(dialog->vrtp)) {
13626          ast_debug(2, "Bridge still active.  Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
13627          sip_pvt_unlock(dialog);
13628          return 0;
13629       }
13630 
13631       sip_pvt_unlock(dialog);
13632       /* no, the unlink should handle this: dialog_unref(dialog, "needdestroy: one more refcount decrement to allow dialog to be destroyed"); */
13633       /* the CMP_MATCH will unlink this dialog from the dialog hash table */
13634       dialog_unlink_all(dialog, TRUE, FALSE);
13635       return 0; /* the unlink_all should unlink this from the table, so.... no need to return a match */
13636    }
13637 
13638    sip_pvt_unlock(dialog);
13639 
13640    return 0;
13641 }
13642 
13643 /* this func is used with ao2_callback to unlink/delete all marked
13644    peers */
13645 static int peer_is_marked(void *peerobj, void *arg, int flags) 
13646 {
13647    struct sip_peer *peer = peerobj;
13648    return peer->the_mark ? CMP_MATCH : 0;
13649 }
13650 
13651 /*! \brief Remove temporary realtime objects from memory (CLI) */
13652 /*! \todo XXXX Propably needs an overhaul after removal of the devices */
13653 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13654 {
13655    struct sip_peer *peer, *pi;
13656    int prunepeer = FALSE;
13657    int multi = FALSE;
13658    char *name = NULL;
13659    regex_t regexbuf;
13660    struct ao2_iterator i;
13661    
13662    if (cmd == CLI_INIT) {
13663       e->command = "sip prune realtime [peer|all] [all|like]";
13664       e->usage =
13665          "Usage: sip prune realtime [peer [<name>|all|like <pattern>]|all]\n"
13666          "       Prunes object(s) from the cache.\n"
13667          "       Optional regular expression pattern is used to filter the objects.\n";
13668       return NULL;
13669    } else if (cmd == CLI_GENERATE) {
13670       if (a->pos == 4) {
13671          if (strcasestr(a->line, "realtime peer"))
13672             return complete_sip_peer(a->word, a->n, SIP_PAGE2_RTCACHEFRIENDS);
13673       }
13674       return NULL;
13675    }
13676    switch (a->argc) {
13677    case 4:
13678       name = a->argv[3];
13679       /* we accept a name in position 3, but keywords are not good. */
13680       if (!strcasecmp(name, "peer") || !strcasecmp(name, "like"))
13681          return CLI_SHOWUSAGE;
13682       prunepeer = TRUE;
13683       if (!strcasecmp(name, "all")) {
13684          multi = TRUE;
13685          name = NULL;
13686       }
13687       /* else a single name, already set */
13688       break;
13689    case 5:
13690       /* sip prune realtime {peer|like} name */
13691       name = a->argv[4];
13692       if (!strcasecmp(a->argv[3], "peer"))
13693          prunepeer = TRUE;
13694       else if (!strcasecmp(a->argv[3], "like")) {
13695          prunepeer = TRUE;
13696          multi = TRUE;
13697       } else
13698          return CLI_SHOWUSAGE;
13699       if (!strcasecmp(a->argv[4], "like"))
13700          return CLI_SHOWUSAGE;
13701       if (!multi && !strcasecmp(a->argv[4], "all")) {
13702          multi = TRUE;
13703          name = NULL;
13704       }
13705       break;
13706    case 6:
13707       name = a->argv[5];
13708       multi = TRUE;
13709       /* sip prune realtime {peer} like name */
13710       if (strcasecmp(a->argv[4], "like"))
13711          return CLI_SHOWUSAGE;
13712       if (!strcasecmp(a->argv[3], "peer")) {
13713          prunepeer = TRUE;
13714       } else
13715          return CLI_SHOWUSAGE;
13716       break;
13717    default:
13718       return CLI_SHOWUSAGE;
13719    }
13720 
13721    if (multi && name) {
13722       if (regcomp(&regexbuf, name, REG_EXTENDED | REG_NOSUB))
13723          return CLI_SHOWUSAGE;
13724    }
13725 
13726    if (multi) {
13727       if (prunepeer) {
13728          int pruned = 0;
13729          
13730          i = ao2_iterator_init(peers, 0);
13731          while ((pi = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
13732             ao2_lock(pi);
13733             if (name && regexec(&regexbuf, pi->name, 0, NULL, 0)) {
13734                unref_peer(pi, "toss iterator peer ptr before continue");
13735                ao2_unlock(pi);
13736                continue;
13737             };
13738             if (ast_test_flag(&pi->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
13739                pi->the_mark = 1;
13740                pruned++;
13741             }
13742             ao2_unlock(pi);
13743             unref_peer(pi, "toss iterator peer ptr");
13744          }
13745          if (pruned) {
13746             ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, 0, 
13747                   "initiating callback to remove marked peers");
13748             ast_cli(a->fd, "%d peers pruned.\n", pruned);
13749          } else
13750             ast_cli(a->fd, "No peers found to prune.\n");
13751       }
13752    } else {
13753       if (prunepeer) {
13754          struct sip_peer tmp;
13755          ast_copy_string(tmp.name, name, sizeof(tmp.name));
13756          if ((peer = ao2_t_find(peers, &tmp, OBJ_POINTER | OBJ_UNLINK, "finding to unlink from peers"))) {
13757             if (peer->addr.sin_addr.s_addr) {
13758                ao2_t_unlink(peers_by_ip, peer, "unlinking peer from peers_by_ip also");
13759             }
13760             if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
13761                ast_cli(a->fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
13762                /* put it back! */
13763                ao2_t_link(peers, peer, "link peer into peer table");
13764                if (peer->addr.sin_addr.s_addr) {
13765                   ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
13766                }
13767                
13768             } else
13769                ast_cli(a->fd, "Peer '%s' pruned.\n", name);
13770             unref_peer(peer, "sip_prune_realtime: unref_peer: tossing temp peer ptr");
13771          } else
13772             ast_cli(a->fd, "Peer '%s' not found.\n", name);
13773       }
13774    }
13775 
13776    return CLI_SUCCESS;
13777 }
13778 
13779 /*! \brief Print codec list from preference to CLI/manager */
13780 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
13781 {
13782    int x, codec;
13783 
13784    for(x = 0; x < 32 ; x++) {
13785       codec = ast_codec_pref_index(pref, x);
13786       if (!codec)
13787          break;
13788       ast_cli(fd, "%s", ast_getformatname(codec));
13789       ast_cli(fd, ":%d", pref->framing[x]);
13790       if (x < 31 && ast_codec_pref_index(pref, x + 1))
13791          ast_cli(fd, ",");
13792    }
13793    if (!x)
13794       ast_cli(fd, "none");
13795 }
13796 
13797 /*! \brief Print domain mode to cli */
13798 static const char *domain_mode_to_text(const enum domain_mode mode)
13799 {
13800    switch (mode) {
13801    case SIP_DOMAIN_AUTO:
13802       return "[Automatic]";
13803    case SIP_DOMAIN_CONFIG:
13804       return "[Configured]";
13805    }
13806 
13807    return "";
13808 }
13809 
13810 /*! \brief CLI command to list local domains */
13811 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13812 {
13813    struct domain *d;
13814 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
13815 
13816    switch (cmd) {
13817    case CLI_INIT:
13818       e->command = "sip show domains";
13819       e->usage =
13820          "Usage: sip show domains\n"
13821          "       Lists all configured SIP local domains.\n"
13822          "       Asterisk only responds to SIP messages to local domains.\n";
13823       return NULL;
13824    case CLI_GENERATE:
13825       return NULL;
13826    }
13827 
13828    if (AST_LIST_EMPTY(&domain_list)) {
13829       ast_cli(a->fd, "SIP Domain support not enabled.\n\n");
13830       return CLI_SUCCESS;
13831    } else {
13832       ast_cli(a->fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
13833       AST_LIST_LOCK(&domain_list);
13834       AST_LIST_TRAVERSE(&domain_list, d, list)
13835          ast_cli(a->fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
13836             domain_mode_to_text(d->mode));
13837       AST_LIST_UNLOCK(&domain_list);
13838       ast_cli(a->fd, "\n");
13839       return CLI_SUCCESS;
13840    }
13841 }
13842 #undef FORMAT
13843 
13844 static char mandescr_show_peer[] = 
13845 "Description: Show one SIP peer with details on current status.\n"
13846 "Variables: \n"
13847 "  Peer: <name>           The peer name you want to check.\n"
13848 "  ActionID: <id>   Optional action ID for this AMI transaction.\n";
13849 
13850 /*! \brief Show SIP peers in the manager API  */
13851 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
13852 {
13853    const char *a[4];
13854    const char *peer;
13855 
13856    peer = astman_get_header(m, "Peer");
13857    if (ast_strlen_zero(peer)) {
13858       astman_send_error(s, m, "Peer: <name> missing.");
13859       return 0;
13860    }
13861    a[0] = "sip";
13862    a[1] = "show";
13863    a[2] = "peer";
13864    a[3] = peer;
13865 
13866    _sip_show_peer(1, -1, s, m, 4, a);
13867    astman_append(s, "\r\n\r\n" );
13868    return 0;
13869 }
13870 
13871 /*! \brief Show one peer in detail */
13872 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13873 {
13874    switch (cmd) {
13875    case CLI_INIT:
13876       e->command = "sip show peer";
13877       e->usage =
13878          "Usage: sip show peer <name> [load]\n"
13879          "       Shows all details on one SIP peer and the current status.\n"
13880          "       Option \"load\" forces lookup of peer in realtime storage.\n";
13881       return NULL;
13882    case CLI_GENERATE:
13883       return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
13884    }
13885    return _sip_show_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
13886 }
13887 
13888 /*! \brief Send qualify message to peer from cli or manager. Mostly for debugging. */
13889 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
13890 {
13891    struct sip_peer *peer;
13892    int load_realtime;
13893 
13894    if (argc < 4)
13895       return CLI_SHOWUSAGE;
13896 
13897    load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
13898    if ((peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE))) {
13899       sip_poke_peer(peer, 1);
13900       unref_peer(peer, "qualify: done with peer");
13901    } else if (type == 0) {
13902       ast_cli(fd, "Peer '%s' not found\n", argv[3]);
13903    } else {
13904       astman_send_error(s, m, "Peer not found");
13905    }
13906    return CLI_SUCCESS;
13907 }
13908 
13909 /*! \brief Qualify SIP peers in the manager API  */
13910 static int manager_sip_qualify_peer(struct mansession *s, const struct message *m)
13911 {
13912    const char *a[4];
13913    const char *peer;
13914 
13915    peer = astman_get_header(m, "Peer");
13916    if (ast_strlen_zero(peer)) {
13917       astman_send_error(s, m, "Peer: <name> missing.");
13918       return 0;
13919    }
13920    a[0] = "sip";
13921    a[1] = "qualify";
13922    a[2] = "peer";
13923    a[3] = peer;
13924 
13925    _sip_qualify_peer(1, -1, s, m, 4, a);
13926    astman_append(s, "\r\n\r\n" );
13927    return 0;
13928 }
13929 
13930 /*! \brief Send an OPTIONS packet to a SIP peer */
13931 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13932 {
13933    switch (cmd) {
13934    case CLI_INIT:
13935       e->command = "sip qualify peer";
13936       e->usage =
13937          "Usage: sip qualify peer <name> [load]\n"
13938          "       Requests a response from one SIP peer and the current status.\n"
13939          "       Option \"load\" forces lookup of peer in realtime storage.\n";
13940       return NULL;
13941    case CLI_GENERATE:
13942       return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
13943    }
13944    return _sip_qualify_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
13945 }
13946 
13947 /*! \brief list peer mailboxes to CLI */
13948 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer)
13949 {
13950    struct sip_mailbox *mailbox;
13951 
13952    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
13953       ast_str_append(mailbox_str, 0, "%s%s%s%s",
13954          mailbox->mailbox,
13955          ast_strlen_zero(mailbox->context) ? "" : "@",
13956          S_OR(mailbox->context, ""),
13957          AST_LIST_NEXT(mailbox, entry) ? "," : "");
13958    }
13959 }
13960 
13961 /*! \brief Show one peer in detail (main function) */
13962 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
13963 {
13964    char status[30] = "";
13965    char cbuf[256];
13966    struct sip_peer *peer;
13967    char codec_buf[512];
13968    struct ast_codec_pref *pref;
13969    struct ast_variable *v;
13970    struct sip_auth *auth;
13971    int x = 0, codec = 0, load_realtime;
13972    int realtimepeers;
13973 
13974    realtimepeers = ast_check_realtime("sippeers");
13975 
13976    if (argc < 4)
13977       return CLI_SHOWUSAGE;
13978 
13979    load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
13980    peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE);
13981 
13982    if (s) {    /* Manager */
13983       if (peer) {
13984          const char *id = astman_get_header(m, "ActionID");
13985 
13986          astman_append(s, "Response: Success\r\n");
13987          if (!ast_strlen_zero(id))
13988             astman_append(s, "ActionID: %s\r\n", id);
13989       } else {
13990          snprintf (cbuf, sizeof(cbuf), "Peer %s not found.", argv[3]);
13991          astman_send_error(s, m, cbuf);
13992          return CLI_SUCCESS;
13993       }
13994    }
13995    if (peer && type==0 ) { /* Normal listing */
13996       struct ast_str *mailbox_str = ast_str_alloca(512);
13997       ast_cli(fd, "\n\n");
13998       ast_cli(fd, "  * Name       : %s\n", peer->name);
13999       if (realtimepeers) { /* Realtime is enabled */
14000          ast_cli(fd, "  Realtime peer: %s\n", peer->is_realtime ? "Yes, cached" : "No");
14001       }
14002       ast_cli(fd, "  Secret       : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
14003       ast_cli(fd, "  MD5Secret    : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
14004       for (auth = peer->auth; auth; auth = auth->next) {
14005          ast_cli(fd, "  Realm-auth   : Realm %-15.15s User %-10.20s ", auth->realm, auth->username);
14006          ast_cli(fd, "%s\n", !ast_strlen_zero(auth->secret)?"<Secret set>":(!ast_strlen_zero(auth->md5secret)?"<MD5secret set>" : "<Not set>"));
14007       }
14008       ast_cli(fd, "  Context      : %s\n", peer->context);
14009       ast_cli(fd, "  Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
14010       ast_cli(fd, "  Language     : %s\n", peer->language);
14011       if (!ast_strlen_zero(peer->accountcode))
14012          ast_cli(fd, "  Accountcode  : %s\n", peer->accountcode);
14013       ast_cli(fd, "  AMA flags    : %s\n", ast_cdr_flags2str(peer->amaflags));
14014       ast_cli(fd, "  Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
14015       ast_cli(fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(peer->callingpres));
14016       if (!ast_strlen_zero(peer->fromuser))
14017          ast_cli(fd, "  FromUser     : %s\n", peer->fromuser);
14018       if (!ast_strlen_zero(peer->fromdomain))
14019          ast_cli(fd, "  FromDomain   : %s\n", peer->fromdomain);
14020       ast_cli(fd, "  Callgroup    : ");
14021       print_group(fd, peer->callgroup, 0);
14022       ast_cli(fd, "  Pickupgroup  : ");
14023       print_group(fd, peer->pickupgroup, 0);
14024       peer_mailboxes_to_str(&mailbox_str, peer);
14025       ast_cli(fd, "  Mailbox      : %s\n", mailbox_str->str);
14026       ast_cli(fd, "  VM Extension : %s\n", peer->vmexten);
14027       ast_cli(fd, "  LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
14028       ast_cli(fd, "  Call limit   : %d\n", peer->call_limit);
14029       if (peer->busy_level)
14030          ast_cli(fd, "  Busy level   : %d\n", peer->busy_level);
14031       ast_cli(fd, "  Dynamic      : %s\n", cli_yesno(peer->host_dynamic));
14032       ast_cli(fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
14033       ast_cli(fd, "  MaxCallBR    : %d kbps\n", peer->maxcallbitrate);
14034       ast_cli(fd, "  Expire       : %ld\n", ast_sched_when(sched, peer->expire));
14035       ast_cli(fd, "  Insecure     : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
14036       ast_cli(fd, "  Nat          : %s\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
14037       ast_cli(fd, "  ACL          : %s\n", cli_yesno(peer->ha != NULL));
14038       ast_cli(fd, "  T38 pt UDPTL : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
14039       ast_cli(fd, "  CanReinvite  : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_CAN_REINVITE)));
14040       ast_cli(fd, "  PromiscRedir : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)));
14041       ast_cli(fd, "  User=Phone   : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)));
14042       ast_cli(fd, "  Video Support: %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)));
14043       ast_cli(fd, "  Text Support : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)));
14044       ast_cli(fd, "  Ign SDP ver  : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_IGNORESDPVERSION)));
14045       ast_cli(fd, "  Trust RPID   : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_TRUSTRPID)));
14046       ast_cli(fd, "  Send RPID    : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_SENDRPID)));
14047       ast_cli(fd, "  Subscriptions: %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
14048       ast_cli(fd, "  Overlap dial : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP)));
14049       if (peer->outboundproxy)
14050          ast_cli(fd, "  Outb. proxy  : %s %s\n", ast_strlen_zero(peer->outboundproxy->name) ? "<not set>" : peer->outboundproxy->name,
14051                      peer->outboundproxy->force ? "(forced)" : "");
14052 
14053       /* - is enumerated */
14054       ast_cli(fd, "  DTMFmode     : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
14055       ast_cli(fd, "  Timer T1     : %d\n", peer->timer_t1);
14056       ast_cli(fd, "  Timer B      : %d\n", peer->timer_b);
14057       ast_cli(fd, "  ToHost       : %s\n", peer->tohost);
14058       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));
14059       ast_cli(fd, "  Defaddr->IP  : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
14060       ast_cli(fd, "  Transport    : %s\n", get_transport(peer->socket.type));
14061       if (!ast_strlen_zero(global_regcontext))
14062          ast_cli(fd, "  Reg. exten   : %s\n", peer->regexten);
14063       ast_cli(fd, "  Def. Username: %s\n", peer->username);
14064       ast_cli(fd, "  SIP Options  : ");
14065       if (peer->sipoptions) {
14066          int lastoption = -1;
14067          for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
14068             if (sip_options[x].id != lastoption) {
14069                if (peer->sipoptions & sip_options[x].id)
14070                   ast_cli(fd, "%s ", sip_options[x].text);
14071                lastoption = x;
14072             }
14073          }
14074       } else
14075          ast_cli(fd, "(none)");
14076 
14077       ast_cli(fd, "\n");
14078       ast_cli(fd, "  Codecs       : ");
14079       ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
14080       ast_cli(fd, "%s\n", codec_buf);
14081       ast_cli(fd, "  Codec Order  : (");
14082       print_codec_to_cli(fd, &peer->prefs);
14083       ast_cli(fd, ")\n");
14084 
14085       ast_cli(fd, "  Auto-Framing :  %s \n", cli_yesno(peer->autoframing));
14086       ast_cli(fd, "  100 on REG   : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_REGISTERTRYING) ? "Yes" : "No");
14087       ast_cli(fd, "  Status       : ");
14088       peer_status(peer, status, sizeof(status));
14089       ast_cli(fd, "%s\n", status);
14090       ast_cli(fd, "  Useragent    : %s\n", peer->useragent);
14091       ast_cli(fd, "  Reg. Contact : %s\n", peer->fullcontact);
14092       ast_cli(fd, "  Qualify Freq : %d ms\n", peer->qualifyfreq);
14093       if (peer->chanvars) {
14094          ast_cli(fd, "  Variables    :\n");
14095          for (v = peer->chanvars ; v ; v = v->next)
14096             ast_cli(fd, "                 %s = %s\n", v->name, v->value);
14097       }
14098 
14099       ast_cli(fd, "  Sess-Timers  : %s\n", stmode2str(peer->stimer.st_mode_oper));
14100       ast_cli(fd, "  Sess-Refresh : %s\n", strefresher2str(peer->stimer.st_ref));
14101       ast_cli(fd, "  Sess-Expires : %d secs\n", peer->stimer.st_max_se);
14102       ast_cli(fd, "  Min-Sess     : %d secs\n", peer->stimer.st_min_se);
14103       ast_cli(fd, "\n");
14104       peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer ptr");
14105    } else  if (peer && type == 1) { /* manager listing */
14106       char buffer[256];
14107       struct ast_str *mailbox_str = ast_str_alloca(512);
14108       astman_append(s, "Channeltype: SIP\r\n");
14109       astman_append(s, "ObjectName: %s\r\n", peer->name);
14110       astman_append(s, "ChanObjectType: peer\r\n");
14111       astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
14112       astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
14113       astman_append(s, "Context: %s\r\n", peer->context);
14114       astman_append(s, "Language: %s\r\n", peer->language);
14115       if (!ast_strlen_zero(peer->accountcode))
14116          astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
14117       astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
14118       astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
14119       if (!ast_strlen_zero(peer->fromuser))
14120          astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
14121       if (!ast_strlen_zero(peer->fromdomain))
14122          astman_append(s, "SIP-FromDomain: %s\r\n", peer->fromdomain);
14123       astman_append(s, "Callgroup: ");
14124       astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->callgroup));
14125       astman_append(s, "Pickupgroup: ");
14126       astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->pickupgroup));
14127       peer_mailboxes_to_str(&mailbox_str, peer);
14128       astman_append(s, "VoiceMailbox: %s\r\n", mailbox_str->str);
14129       astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
14130       astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
14131       astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
14132       astman_append(s, "Busy-level: %d\r\n", peer->busy_level);
14133       astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
14134       astman_append(s, "Dynamic: %s\r\n", peer->host_dynamic?"Y":"N");
14135       astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
14136       astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched, peer->expire));
14137       astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
14138       astman_append(s, "SIP-NatSupport: %s\r\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
14139       astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
14140       astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_CAN_REINVITE)?"Y":"N"));
14141       astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
14142       astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
14143       astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
14144       astman_append(s, "SIP-TextSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)?"Y":"N"));
14145       astman_append(s, "SIP-Sess-Timers: %s\r\n", stmode2str(peer->stimer.st_mode_oper));
14146       astman_append(s, "SIP-Sess-Refresh: %s\r\n", strefresher2str(peer->stimer.st_ref));
14147       astman_append(s, "SIP-Sess-Expires: %d\r\n", peer->stimer.st_max_se);
14148       astman_append(s, "SIP-Sess-Min: %d\r\n", peer->stimer.st_min_se);
14149 
14150       /* - is enumerated */
14151       astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
14152       astman_append(s, "ToHost: %s\r\n", peer->tohost);
14153       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));
14154       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));
14155       astman_append(s, "Default-Username: %s\r\n", peer->username);
14156       if (!ast_strlen_zero(global_regcontext))
14157          astman_append(s, "RegExtension: %s\r\n", peer->regexten);
14158       astman_append(s, "Codecs: ");
14159       ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
14160       astman_append(s, "%s\r\n", codec_buf);
14161       astman_append(s, "CodecOrder: ");
14162       pref = &peer->prefs;
14163       for(x = 0; x < 32 ; x++) {
14164          codec = ast_codec_pref_index(pref, x);
14165          if (!codec)
14166             break;
14167          astman_append(s, "%s", ast_getformatname(codec));
14168          if (x < 31 && ast_codec_pref_index(pref, x+1))
14169             astman_append(s, ",");
14170       }
14171 
14172       astman_append(s, "\r\n");
14173       astman_append(s, "Status: ");
14174       peer_status(peer, status, sizeof(status));
14175       astman_append(s, "%s\r\n", status);
14176       astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
14177       astman_append(s, "Reg-Contact: %s\r\n", peer->fullcontact);
14178       astman_append(s, "QualifyFreq: %d ms\r\n", peer->qualifyfreq);
14179       if (peer->chanvars) {
14180          for (v = peer->chanvars ; v ; v = v->next) {
14181             astman_append(s, "ChanVariable: %s=%s\r\n", v->name, v->value);
14182          }
14183       }
14184 
14185       peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer");
14186 
14187    } else {
14188       ast_cli(fd, "Peer %s not found.\n", argv[3]);
14189       ast_cli(fd, "\n");
14190    }
14191 
14192    return CLI_SUCCESS;
14193 }
14194 
14195 /*! \brief Do completion on user name */
14196 static char *complete_sip_user(const char *word, int state)
14197 {
14198    char *result = NULL;
14199    int wordlen = strlen(word);
14200    int which = 0;
14201    struct ao2_iterator user_iter;
14202    struct sip_peer *user;
14203 
14204    user_iter = ao2_iterator_init(peers, 0);
14205    while ((user = ao2_iterator_next(&user_iter))) {
14206       ao2_lock(user);
14207       if (!(user->type & SIP_TYPE_USER)) {
14208          ao2_unlock(user);
14209          unref_peer(user, "complete sip user");
14210          continue;
14211       }
14212       /* locking of the object is not required because only the name and flags are being compared */
14213       if (!strncasecmp(word, user->name, wordlen) && ++which > state) {
14214          result = ast_strdup(user->name);
14215       }
14216       ao2_unlock(user);
14217       unref_peer(user, "complete sip user");
14218    }
14219    return result;
14220 }
14221 /*! \brief Support routine for 'sip show user' CLI */
14222 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
14223 {
14224    if (pos == 3)
14225       return complete_sip_user(word, state);
14226 
14227    return NULL;
14228 }
14229 
14230 /*! \brief Show one user in detail */
14231 static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14232 {
14233    char cbuf[256];
14234    struct sip_peer *user;
14235    struct ast_variable *v;
14236    int load_realtime;
14237 
14238    switch (cmd) {
14239    case CLI_INIT:
14240       e->command = "sip show user";
14241       e->usage =
14242          "Usage: sip show user <name> [load]\n"
14243          "       Shows all details on one SIP user and the current status.\n"
14244          "       Option \"load\" forces lookup of peer in realtime storage.\n";
14245       return NULL;
14246    case CLI_GENERATE:
14247       return complete_sip_show_user(a->line, a->word, a->pos, a->n);
14248    }
14249 
14250    if (a->argc < 4)
14251       return CLI_SHOWUSAGE;
14252 
14253    /* Load from realtime storage? */
14254    load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? TRUE : FALSE;
14255 
14256    if ((user = find_peer(a->argv[3], NULL, load_realtime, FINDUSERS, FALSE))) {
14257       ao2_lock(user);
14258       ast_cli(a->fd, "\n\n");
14259       ast_cli(a->fd, "  * Name       : %s\n", user->name);
14260       ast_cli(a->fd, "  Secret       : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
14261       ast_cli(a->fd, "  MD5Secret    : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
14262       ast_cli(a->fd, "  Context      : %s\n", user->context);
14263       ast_cli(a->fd, "  Language     : %s\n", user->language);
14264       if (!ast_strlen_zero(user->accountcode))
14265          ast_cli(a->fd, "  Accountcode  : %s\n", user->accountcode);
14266       ast_cli(a->fd, "  AMA flags    : %s\n", ast_cdr_flags2str(user->amaflags));
14267       ast_cli(a->fd, "  Transfer mode: %s\n", transfermode2str(user->allowtransfer));
14268       ast_cli(a->fd, "  MaxCallBR    : %d kbps\n", user->maxcallbitrate);
14269       ast_cli(a->fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(user->callingpres));
14270       ast_cli(a->fd, "  Call limit   : %d\n", user->call_limit);
14271       ast_cli(a->fd, "  Callgroup    : ");
14272       print_group(a->fd, user->callgroup, 0);
14273       ast_cli(a->fd, "  Pickupgroup  : ");
14274       print_group(a->fd, user->pickupgroup, 0);
14275       ast_cli(a->fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
14276       ast_cli(a->fd, "  ACL          : %s\n", cli_yesno(user->ha != NULL));
14277       ast_cli(a->fd, "  Sess-Timers  : %s\n", stmode2str(user->stimer.st_mode_oper));
14278       ast_cli(a->fd, "  Sess-Refresh : %s\n", strefresher2str(user->stimer.st_ref));
14279       ast_cli(a->fd, "  Sess-Expires : %d secs\n", user->stimer.st_max_se);
14280       ast_cli(a->fd, "  Sess-Min-SE  : %d secs\n", user->stimer.st_min_se);
14281       ast_cli(a->fd, "  Ign SDP ver  : %s\n", cli_yesno(ast_test_flag(&user->flags[1], SIP_PAGE2_IGNORESDPVERSION)));
14282 
14283       ast_cli(a->fd, "  Codec Order  : (");
14284       print_codec_to_cli(a->fd, &user->prefs);
14285       ast_cli(a->fd, ")\n");
14286 
14287       ast_cli(a->fd, "  Auto-Framing:  %s \n", cli_yesno(user->autoframing));
14288       if (user->chanvars) {
14289          ast_cli(a->fd, "  Variables    :\n");
14290          for (v = user->chanvars ; v ; v = v->next)
14291             ast_cli(a->fd, "                 %s = %s\n", v->name, v->value);
14292       }
14293 
14294       ast_cli(a->fd, "\n");
14295 
14296       ao2_unlock(user);
14297       unref_peer(user, "sip show user");
14298    } else {
14299       ast_cli(a->fd, "User %s not found.\n", a->argv[3]);
14300       ast_cli(a->fd, "\n");
14301    }
14302 
14303    return CLI_SUCCESS;
14304 }
14305 
14306 
14307 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14308 {
14309    struct ast_str *cbuf;
14310    struct ast_cb_names cbnames = {9, { "retrans_pkt",
14311                                         "__sip_autodestruct",
14312                                         "expire_register",
14313                                         "auto_congest",
14314                                         "sip_reg_timeout",
14315                                         "sip_poke_peer_s",
14316                                         "sip_poke_noanswer",
14317                                         "sip_reregister",
14318                                         "sip_reinvite_retry"},
14319                            { retrans_pkt,
14320                                      __sip_autodestruct,
14321                                      expire_register,
14322                                      auto_congest,
14323                                      sip_reg_timeout,
14324                                      sip_poke_peer_s,
14325                                      sip_poke_noanswer,
14326                                      sip_reregister,
14327                                      sip_reinvite_retry}};
14328    
14329    switch (cmd) {
14330    case CLI_INIT:
14331       e->command = "sip show sched";
14332       e->usage =
14333          "Usage: sip show sched\n"
14334          "       Shows stats on what's in the sched queue at the moment\n";
14335       return NULL;
14336    case CLI_GENERATE:
14337       return NULL;
14338    }
14339 
14340    cbuf = ast_str_alloca(2048);
14341 
14342    ast_cli(a->fd, "\n");
14343    ast_sched_report(sched, &cbuf, &cbnames);
14344    ast_cli(a->fd, "%s", cbuf->str);
14345 
14346    return CLI_SUCCESS;
14347 }
14348 
14349 /*! \brief  Show SIP Registry (registrations with other SIP proxies */
14350 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14351 {
14352 #define FORMAT2 "%-30.30s %-6.6s %-12.12s  %8.8s %-20.20s %-25.25s\n"
14353 #define FORMAT  "%-30.30s %-6.6s %-12.12s  %8d %-20.20s %-25.25s\n"
14354    char host[80];
14355    char tmpdat[256];
14356    struct ast_tm tm;
14357    int counter = 0;
14358 
14359    switch (cmd) {
14360    case CLI_INIT:
14361       e->command = "sip show registry";
14362       e->usage =
14363          "Usage: sip show registry\n"
14364          "       Lists all registration requests and status.\n";
14365       return NULL;
14366    case CLI_GENERATE:
14367       return NULL;
14368    }
14369 
14370    if (a->argc != 3)
14371       return CLI_SHOWUSAGE;
14372    ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Refresh", "State", "Reg.Time");
14373    
14374    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
14375       ASTOBJ_RDLOCK(iterator);
14376       snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
14377       if (iterator->regtime.tv_sec) {
14378          ast_localtime(&iterator->regtime, &tm, NULL);
14379          ast_strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
14380       } else 
14381          tmpdat[0] = '\0';
14382       ast_cli(a->fd, FORMAT, host, (iterator->dnsmgr) ? "Y" : "N", iterator->username, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
14383       ASTOBJ_UNLOCK(iterator);
14384       counter++;
14385    } while(0));
14386    ast_cli(a->fd, "%d SIP registrations.\n", counter);
14387    return CLI_SUCCESS;
14388 #undef FORMAT
14389 #undef FORMAT2
14390 }
14391 
14392 /*! \brief Unregister (force expiration) a SIP peer in the registry via CLI 
14393    \note This function does not tell the SIP device what's going on,
14394    so use it with great care.
14395 */
14396 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14397 {
14398    struct sip_peer *peer;
14399    int load_realtime = 0;
14400 
14401    switch (cmd) {
14402    case CLI_INIT:
14403       e->command = "sip unregister";
14404       e->usage =
14405          "Usage: sip unregister <peer>\n"
14406          "       Unregister (force expiration) a SIP peer from the registry\n";
14407       return NULL;
14408    case CLI_GENERATE:
14409       return complete_sip_unregister(a->line, a->word, a->pos, a->n);
14410    }
14411    
14412    if (a->argc != 3)
14413       return CLI_SHOWUSAGE;
14414    
14415    if ((peer = find_peer(a->argv[2], NULL, load_realtime, FINDPEERS, TRUE))) {
14416       if (peer->expire > 0) {
14417          AST_SCHED_DEL_UNREF(sched, peer->expire,
14418             unref_peer(peer, "remove register expire ref"));
14419          expire_register(ref_peer(peer, "ref for expire_register"));
14420          ast_cli(a->fd, "Unregistered peer \'%s\'\n\n", a->argv[2]);
14421       } else {
14422          ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
14423       }
14424       unref_peer(peer, "sip_unregister: unref_peer via sip_unregister: done with peer from find_peer call");
14425    } else {
14426       ast_cli(a->fd, "Peer unknown: \'%s\'. Not unregistered.\n", a->argv[2]);
14427    }
14428    
14429    return CLI_SUCCESS;
14430 }
14431 
14432 /*! \brief Callback for show_chanstats */
14433 static int show_chanstats_cb(void *__cur, void *__arg, int flags)
14434 {
14435 #define FORMAT2 "%-15.15s  %-11.11s  %-8.8s %-10.10s  %-10.10s (%-2.2s) %-6.6s %-10.10s  %-10.10s ( %%) %-6.6s\n"
14436 #define FORMAT  "%-15.15s  %-11.11s  %-8.8s %-10.10u%-1.1s %-10.10u (%-2.2u%%) %-6.6u %-10.10u%-1.1s %-10.10u (%-2.2u%%) %-6.6u\n"
14437    struct sip_pvt *cur = __cur;
14438    unsigned int rxcount;
14439    unsigned int txcount;
14440    char durbuf[10];
14441         int duration;
14442         int durh, durm, durs;
14443    struct ast_channel *c = cur->owner;
14444    struct __show_chan_arg *arg = __arg;
14445    int fd = arg->fd;
14446 
14447 
14448    if (cur->subscribed != NONE) /* Subscriptions */
14449       return 0;   /* don't care, we scan all channels */
14450 
14451    if (!cur->rtp) {
14452       if (sipdebug)
14453          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");
14454       return 0;   /* don't care, we scan all channels */
14455    }
14456    rxcount = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXCOUNT);
14457    txcount = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXCOUNT);
14458 
14459    /* Find the duration of this channel */
14460    if (c && c->cdr && !ast_tvzero(c->cdr->start)) {
14461       duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
14462       durh = duration / 3600;
14463       durm = (duration % 3600) / 60;
14464       durs = duration % 60;
14465       snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
14466    } else {
14467       durbuf[0] = '\0';
14468    }
14469    /* Print stats for every call with RTP */
14470    ast_cli(fd, FORMAT, 
14471       ast_inet_ntoa(cur->sa.sin_addr), 
14472       cur->callid, 
14473       durbuf,
14474       rxcount > (unsigned int) 100000 ? (unsigned int) (rxcount)/(unsigned int) 1000 : rxcount,
14475       rxcount > (unsigned int) 100000 ? "K":" ",
14476       ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXPLOSS),
14477       rxcount > ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXPLOSS) ? (unsigned int) (ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXPLOSS) / rxcount * 100) : 0,
14478       ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXJITTER),
14479       txcount > (unsigned int) 100000 ? (unsigned int) (txcount)/(unsigned int) 1000 : txcount,
14480       txcount > (unsigned int) 100000 ? "K":" ",
14481       ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXPLOSS),
14482       txcount > ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXPLOSS) ? (unsigned int) (ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXPLOSS)/ txcount * 100) : 0,
14483       ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXJITTER)
14484    );
14485    arg->numchans++;
14486 
14487    return 0;   /* don't care, we scan all channels */
14488 }
14489 
14490 /*! \brief SIP show channelstats CLI (main function) */
14491 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14492 {
14493    struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
14494 
14495    switch (cmd) {
14496    case CLI_INIT:
14497       e->command = "sip show channelstats";
14498       e->usage =
14499          "Usage: sip show channelstats\n"
14500          "       Lists all currently active SIP channel's RTCP statistics.\n"
14501          "       Note that calls in the much optimized RTP P2P bridge mode will not show any packets here.";
14502       return NULL;
14503    case CLI_GENERATE:
14504       return NULL;
14505    }
14506 
14507    if (a->argc != 3)
14508       return CLI_SHOWUSAGE;
14509 
14510    ast_cli(a->fd, FORMAT2, "Peer", "Call ID", "Duration", "Recv: Pack", "Lost", "%", "Jitter", "Send: Pack", "Lost", "Jitter");
14511    /* iterate on the container and invoke the callback on each item */
14512    ao2_t_callback(dialogs, OBJ_NODATA, show_chanstats_cb, &arg, "callback to sip show chanstats");
14513    ast_cli(a->fd, "%d active SIP channel%s\n", arg.numchans, (arg.numchans != 1) ? "s" : ""); 
14514    return CLI_SUCCESS;
14515 }
14516 #undef FORMAT
14517 #undef FORMAT2
14518 
14519 /*! \brief List global settings for the SIP channel */
14520 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14521 {
14522    int realtimepeers;
14523    int realtimeregs;
14524    char codec_buf[SIPBUFSIZE];
14525    const char *msg;  /* temporary msg pointer */
14526 
14527    switch (cmd) {
14528    case CLI_INIT:
14529       e->command = "sip show settings";
14530       e->usage =
14531          "Usage: sip show settings\n"
14532          "       Provides detailed list of the configuration of the SIP channel.\n";
14533       return NULL;
14534    case CLI_GENERATE:
14535       return NULL;
14536    }
14537 
14538 
14539    realtimepeers = ast_check_realtime("sippeers");
14540    realtimeregs = ast_check_realtime("sipregs");
14541 
14542    if (a->argc != 3)
14543       return CLI_SHOWUSAGE;
14544    ast_cli(a->fd, "\n\nGlobal Settings:\n");
14545    ast_cli(a->fd, "----------------\n");
14546    ast_cli(a->fd, "  UDP SIP Port:           %d\n", ntohs(bindaddr.sin_port));
14547    ast_cli(a->fd, "  UDP Bindaddress:        %s\n", ast_inet_ntoa(bindaddr.sin_addr));
14548    ast_cli(a->fd, "  TCP SIP Port:           ");
14549    if (sip_tcp_desc.local_address.sin_family == AF_INET) {
14550       ast_cli(a->fd, "%d\n", ntohs(sip_tcp_desc.local_address.sin_port));
14551       ast_cli(a->fd, "  TCP Bindaddress:        %s\n", ast_inet_ntoa(sip_tcp_desc.local_address.sin_addr));
14552    } else {
14553       ast_cli(a->fd, "Disabled\n");
14554    }
14555    ast_cli(a->fd, "  TLS SIP Port:           ");
14556    if (default_tls_cfg.enabled != FALSE) {
14557       ast_cli(a->fd, "%d\n", ntohs(sip_tls_desc.local_address.sin_port));
14558       ast_cli(a->fd, "  TLS Bindaddress:        %s\n", ast_inet_ntoa(sip_tls_desc.local_address.sin_addr));
14559    } else {
14560       ast_cli(a->fd, "Disabled\n");
14561    }
14562    ast_cli(a->fd, "  Videosupport:           %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT)));
14563    ast_cli(a->fd, "  Textsupport:            %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT)));
14564    ast_cli(a->fd, "  AutoCreate Peer:        %s\n", cli_yesno(autocreatepeer));
14565    ast_cli(a->fd, "  Ignore SDP sess. ver.:  %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION)));
14566    ast_cli(a->fd, "  Match Auth Username:    %s\n", cli_yesno(global_match_auth_username));
14567    ast_cli(a->fd, "  Allow unknown access:   %s\n", cli_yesno(global_allowguest));
14568    ast_cli(a->fd, "  Allow subscriptions:    %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
14569    ast_cli(a->fd, "  Allow overlap dialing:  %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)));
14570    ast_cli(a->fd, "  Allow promsic. redir:   %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_PROMISCREDIR)));
14571    ast_cli(a->fd, "  Enable call counters:   %s\n", cli_yesno(global_callcounter));
14572    ast_cli(a->fd, "  SIP domain support:     %s\n", cli_yesno(!AST_LIST_EMPTY(&domain_list)));
14573    ast_cli(a->fd, "  Realm. auth:            %s\n", cli_yesno(authl != NULL));
14574    ast_cli(a->fd, "  Our auth realm          %s\n", global_realm);
14575    ast_cli(a->fd, "  Call to non-local dom.: %s\n", cli_yesno(allow_external_domains));
14576    ast_cli(a->fd, "  URI user is phone no:   %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_USEREQPHONE)));
14577    ast_cli(a->fd, "  Always auth rejects:    %s\n", cli_yesno(global_alwaysauthreject));
14578    ast_cli(a->fd, "  Direct RTP setup:       %s\n", cli_yesno(global_directrtpsetup));
14579    ast_cli(a->fd, "  User Agent:             %s\n", global_useragent);
14580    ast_cli(a->fd, "  SDP Session Name:       %s\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
14581    ast_cli(a->fd, "  SDP Owner Name:         %s\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner);
14582    ast_cli(a->fd, "  Reg. context:           %s\n", S_OR(global_regcontext, "(not set)"));
14583    ast_cli(a->fd, "  Regexten on Qualify:    %s\n", cli_yesno(global_regextenonqualify));
14584    ast_cli(a->fd, "  Caller ID:              %s\n", default_callerid);
14585    ast_cli(a->fd, "  From: Domain:           %s\n", default_fromdomain);
14586    ast_cli(a->fd, "  Record SIP history:     %s\n", recordhistory ? "On" : "Off");
14587    ast_cli(a->fd, "  Call Events:            %s\n", global_callevents ? "On" : "Off");
14588    ast_cli(a->fd, "  Auth. Failure Events:   %s\n", global_authfailureevents ? "On" : "Off");
14589 
14590    ast_cli(a->fd, "  T38 fax pt UDPTL:       %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
14591 
14592    if (!realtimepeers && !realtimeregs)
14593       ast_cli(a->fd, "  SIP realtime:           Disabled\n" );
14594    else
14595       ast_cli(a->fd, "  SIP realtime:           Enabled\n" );
14596    ast_cli(a->fd, "  Qualify Freq :          %d ms\n", global_qualifyfreq);
14597    ast_cli(a->fd, "\nNetwork QoS Settings:\n");
14598    ast_cli(a->fd, "---------------------------\n");
14599    ast_cli(a->fd, "  IP ToS SIP:             %s\n", ast_tos2str(global_tos_sip));
14600    ast_cli(a->fd, "  IP ToS RTP audio:       %s\n", ast_tos2str(global_tos_audio));
14601    ast_cli(a->fd, "  IP ToS RTP video:       %s\n", ast_tos2str(global_tos_video));
14602    ast_cli(a->fd, "  IP ToS RTP text:        %s\n", ast_tos2str(global_tos_text));
14603    ast_cli(a->fd, "  802.1p CoS SIP:         %d\n", global_cos_sip);
14604    ast_cli(a->fd, "  802.1p CoS RTP audio:   %d\n", global_cos_audio);
14605    ast_cli(a->fd, "  802.1p CoS RTP video:   %d\n", global_cos_video);
14606    ast_cli(a->fd, "  802.1p CoS RTP text:    %d\n", global_cos_text);
14607    ast_cli(a->fd, "  Jitterbuffer enabled:   %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_ENABLED)));
14608    ast_cli(a->fd, "  Jitterbuffer forced:    %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_FORCED)));
14609    ast_cli(a->fd, "  Jitterbuffer max size:  %ld\n", global_jbconf.max_size);
14610    ast_cli(a->fd, "  Jitterbuffer resync:    %ld\n", global_jbconf.resync_threshold);
14611    ast_cli(a->fd, "  Jitterbuffer impl:      %s\n", global_jbconf.impl);
14612    ast_cli(a->fd, "  Jitterbuffer log:       %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_LOG)));
14613 
14614    ast_cli(a->fd, "\nNetwork Settings:\n");
14615    ast_cli(a->fd, "---------------------------\n");
14616    /* determine if/how SIP address can be remapped */
14617    if (localaddr == NULL)
14618       msg = "Disabled, no localnet list";
14619    else if (externip.sin_addr.s_addr == 0)
14620       msg = "Disabled, externip is 0.0.0.0";
14621    else if (stunaddr.sin_addr.s_addr != 0)
14622       msg = "Enabled using STUN";
14623    else if (!ast_strlen_zero(externhost))
14624       msg = "Enabled using externhost";
14625    else
14626       msg = "Enabled using externip";
14627    ast_cli(a->fd, "  SIP address remapping:  %s\n", msg);
14628    ast_cli(a->fd, "  Externhost:             %s\n", S_OR(externhost, "<none>"));
14629    ast_cli(a->fd, "  Externip:               %s:%d\n", ast_inet_ntoa(externip.sin_addr), ntohs(externip.sin_port));
14630    ast_cli(a->fd, "  Externrefresh:          %d\n", externrefresh);
14631    ast_cli(a->fd, "  Internal IP:            %s:%d\n", ast_inet_ntoa(internip.sin_addr), ntohs(internip.sin_port));
14632    {
14633       struct ast_ha *d;
14634       const char *prefix = "Localnet:";
14635       char buf[INET_ADDRSTRLEN]; /* need to print two addresses */
14636 
14637       for (d = localaddr; d ; prefix = "", d = d->next) {
14638          ast_cli(a->fd, "  %-24s%s/%s\n",
14639              prefix, ast_inet_ntoa(d->netaddr),
14640              inet_ntop(AF_INET, &d->netmask, buf, sizeof(buf)) );
14641       }
14642    }
14643    ast_cli(a->fd, "  STUN server:            %s:%d\n", ast_inet_ntoa(stunaddr.sin_addr), ntohs(stunaddr.sin_port));
14644  
14645    ast_cli(a->fd, "\nGlobal Signalling Settings:\n");
14646    ast_cli(a->fd, "---------------------------\n");
14647    ast_cli(a->fd, "  Codecs:                 ");
14648    ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, global_capability);
14649    ast_cli(a->fd, "%s\n", codec_buf);
14650    ast_cli(a->fd, "  Codec Order:            ");
14651    print_codec_to_cli(a->fd, &default_prefs);
14652    ast_cli(a->fd, "\n");
14653    ast_cli(a->fd, "  Relax DTMF:             %s\n", cli_yesno(global_relaxdtmf));
14654    ast_cli(a->fd, "  RFC2833 Compensation:   %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE)));
14655    ast_cli(a->fd, "  Compact SIP headers:    %s\n", cli_yesno(compactheaders));
14656    ast_cli(a->fd, "  RTP Keepalive:          %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
14657    ast_cli(a->fd, "  RTP Timeout:            %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
14658    ast_cli(a->fd, "  RTP Hold Timeout:       %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
14659    ast_cli(a->fd, "  MWI NOTIFY mime type:   %s\n", default_notifymime);
14660    ast_cli(a->fd, "  DNS SRV lookup:         %s\n", cli_yesno(global_srvlookup));
14661    ast_cli(a->fd, "  Pedantic SIP support:   %s\n", cli_yesno(pedanticsipchecking));
14662    ast_cli(a->fd, "  Reg. min duration       %d secs\n", min_expiry);
14663    ast_cli(a->fd, "  Reg. max duration:      %d secs\n", max_expiry);
14664    ast_cli(a->fd, "  Reg. default duration:  %d secs\n", default_expiry);
14665    ast_cli(a->fd, "  Outbound reg. timeout:  %d secs\n", global_reg_timeout);
14666    ast_cli(a->fd, "  Outbound reg. attempts: %d\n", global_regattempts_max);
14667    ast_cli(a->fd, "  Notify ringing state:   %s\n", cli_yesno(global_notifyringing));
14668    ast_cli(a->fd, "  Notify hold state:      %s\n", cli_yesno(global_notifyhold));
14669    ast_cli(a->fd, "  SIP Transfer mode:      %s\n", transfermode2str(global_allowtransfer));
14670    ast_cli(a->fd, "  Max Call Bitrate:       %d kbps\n", default_maxcallbitrate);
14671    ast_cli(a->fd, "  Auto-Framing:           %s\n", cli_yesno(global_autoframing));
14672    ast_cli(a->fd, "  Outb. proxy:            %s %s\n", ast_strlen_zero(global_outboundproxy.name) ? "<not set>" : global_outboundproxy.name,
14673                      global_outboundproxy.force ? "(forced)" : "");
14674    ast_cli(a->fd, "  Session Timers:         %s\n", stmode2str(global_st_mode));
14675    ast_cli(a->fd, "  Session Refresher:      %s\n", strefresher2str (global_st_refresher));
14676    ast_cli(a->fd, "  Session Expires:        %d secs\n", global_max_se);
14677    ast_cli(a->fd, "  Session Min-SE:         %d secs\n", global_min_se);
14678    ast_cli(a->fd, "  Timer T1:               %d\n", global_t1);
14679    ast_cli(a->fd, "  Timer T1 minimum:       %d\n", global_t1min);
14680    ast_cli(a->fd, "  Timer B:                %d\n", global_timer_b);
14681 
14682    ast_cli(a->fd, "\nDefault Settings:\n");
14683    ast_cli(a->fd, "-----------------\n");
14684    ast_cli(a->fd, "  Context:                %s\n", default_context);
14685    ast_cli(a->fd, "  Nat:                    %s\n", nat2str(ast_test_flag(&global_flags[0], SIP_NAT)));
14686    ast_cli(a->fd, "  DTMF:                   %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
14687    ast_cli(a->fd, "  Qualify:                %d\n", default_qualify);
14688    ast_cli(a->fd, "  Use ClientCode:         %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_USECLIENTCODE)));
14689    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" );
14690    ast_cli(a->fd, "  Language:               %s\n", default_language);
14691    ast_cli(a->fd, "  MOH Interpret:          %s\n", default_mohinterpret);
14692    ast_cli(a->fd, "  MOH Suggest:            %s\n", default_mohsuggest);
14693    ast_cli(a->fd, "  Voice Mail Extension:   %s\n", default_vmexten);
14694 
14695    
14696    if (realtimepeers || realtimeregs) {
14697       ast_cli(a->fd, "\nRealtime SIP Settings:\n");
14698       ast_cli(a->fd, "----------------------\n");
14699       ast_cli(a->fd, "  Realtime Peers:         %s\n", cli_yesno(realtimepeers));
14700       ast_cli(a->fd, "  Realtime Regs:          %s\n", cli_yesno(realtimeregs));
14701       ast_cli(a->fd, "  Cache Friends:          %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)));
14702       ast_cli(a->fd, "  Update:                 %s\n", cli_yesno(sip_cfg.peer_rtupdate));
14703       ast_cli(a->fd, "  Ignore Reg. Expire:     %s\n", cli_yesno(sip_cfg.ignore_regexpire));
14704       ast_cli(a->fd, "  Save sys. name:         %s\n", cli_yesno(sip_cfg.rtsave_sysname));
14705       ast_cli(a->fd, "  Auto Clear:             %d\n", global_rtautoclear);
14706    }
14707    ast_cli(a->fd, "\n----\n");
14708    return CLI_SUCCESS;
14709 }
14710 
14711 /*! \brief Show subscription type in string format */
14712 static const char *subscription_type2str(enum subscriptiontype subtype)
14713 {
14714    int i;
14715 
14716    for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
14717       if (subscription_types[i].type == subtype) {
14718          return subscription_types[i].text;
14719       }
14720    }
14721    return subscription_types[0].text;
14722 }
14723 
14724 /*! \brief Find subscription type in array */
14725 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
14726 {
14727    int i;
14728 
14729    for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
14730       if (subscription_types[i].type == subtype) {
14731          return &subscription_types[i];
14732       }
14733    }
14734    return &subscription_types[0];
14735 }
14736 
14737 /*
14738  * We try to structure all functions that loop on data structures as
14739  * a handler for individual entries, and a mainloop that iterates
14740  * on the main data structure. This way, moving the code to containers
14741  * that support iteration through callbacks will be a lot easier.
14742  */
14743 
14744 #define FORMAT4 "%-15.15s  %-10.10s  %-15.15s  %-15.15s  %-13.13s  %-15.15s %-10.10s %-6.6d\n"
14745 #define FORMAT3 "%-15.15s  %-10.10s  %-15.15s  %-15.15s  %-13.13s  %-15.15s %-10.10s %-6.6s\n"
14746 #define FORMAT2 "%-15.15s  %-10.10s  %-15.15s  %-15.15s  %-7.7s  %-15.15s %-6.6s\n"
14747 #define FORMAT  "%-15.15s  %-10.10s  %-15.15s  %-15.15s  %-3.3s %-3.3s  %-15.15s %-10.10s\n"
14748 
14749 /*! \brief callback for show channel|subscription */
14750 static int show_channels_cb(void *__cur, void *__arg, int flags)
14751 {
14752    struct sip_pvt *cur = __cur;
14753    struct __show_chan_arg *arg = __arg;
14754    const struct sockaddr_in *dst = sip_real_dst(cur);
14755    
14756    /* XXX indentation preserved to reduce diff. Will be fixed later */
14757    if (cur->subscribed == NONE && !arg->subscriptions) {
14758       /* set if SIP transfer in progress */
14759       const char *referstatus = cur->refer ? referstatus2str(cur->refer->status) : "";
14760       char formatbuf[SIPBUFSIZE/2];
14761       
14762       ast_cli(arg->fd, FORMAT, ast_inet_ntoa(dst->sin_addr), 
14763             S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
14764             cur->callid, 
14765             ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0),
14766             cli_yesno(ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD)),
14767             cur->needdestroy ? "(d)" : "",
14768             cur->lastmsg ,
14769             referstatus
14770          );
14771       arg->numchans++;
14772    }
14773    if (cur->subscribed != NONE && arg->subscriptions) {
14774       struct ast_str *mailbox_str = ast_str_alloca(512);
14775       if (cur->subscribed == MWI_NOTIFICATION && cur->relatedpeer)
14776          peer_mailboxes_to_str(&mailbox_str, cur->relatedpeer);
14777       ast_cli(arg->fd, FORMAT4, ast_inet_ntoa(dst->sin_addr),
14778             S_OR(cur->username, S_OR(cur->cid_num, "(None)")), 
14779                cur->callid,
14780             /* the 'complete' exten/context is hidden in the refer_to field for subscriptions */
14781             cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
14782             cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate), 
14783             subscription_type2str(cur->subscribed),
14784             cur->subscribed == MWI_NOTIFICATION ? S_OR(mailbox_str->str, "<none>") : "<none>",
14785             cur->expiry
14786          );
14787       arg->numchans++;
14788    }
14789    return 0;   /* don't care, we scan all channels */
14790 }
14791 
14792 /*! \brief CLI for show channels or subscriptions.
14793  * This is a new-style CLI handler so a single function contains
14794  * the prototype for the function, the 'generator' to produce multiple
14795  * entries in case it is required, and the actual handler for the command.
14796  */
14797 static char *sip_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14798 {
14799    struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
14800 
14801 
14802    if (cmd == CLI_INIT) {
14803       e->command = "sip show {channels|subscriptions}";
14804       e->usage =
14805          "Usage: sip show channels\n"
14806          "       Lists all currently active SIP calls (dialogs).\n"
14807          "Usage: sip show subscriptions\n"
14808          "       Lists active SIP subscriptions.\n";
14809       return NULL;
14810    } else if (cmd == CLI_GENERATE)
14811       return NULL;
14812 
14813    if (a->argc != e->args)
14814       return CLI_SHOWUSAGE;
14815    arg.subscriptions = !strcasecmp(a->argv[e->args - 1], "subscriptions");
14816    if (!arg.subscriptions)
14817       ast_cli(arg.fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Format", "Hold", "Last Message", "Expiry");
14818    else
14819       ast_cli(arg.fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox", "Expiry");
14820 
14821    /* iterate on the container and invoke the callback on each item */
14822    ao2_t_callback(dialogs, OBJ_NODATA, show_channels_cb, &arg, "callback to show channels");
14823    
14824    /* print summary information */
14825    ast_cli(arg.fd, "%d active SIP %s%s\n", arg.numchans,
14826       (arg.subscriptions ? "subscription" : "dialog"),
14827       ESS(arg.numchans));  /* ESS(n) returns an "s" if n>1 */
14828    return CLI_SUCCESS;
14829 #undef FORMAT
14830 #undef FORMAT2
14831 #undef FORMAT3
14832 }
14833 
14834 /*! \brief Support routine for 'sip show channel' and 'sip show history' CLI
14835  * This is in charge of generating all strings that match a prefix in the
14836  * given position. As many functions of this kind, each invokation has
14837  * O(state) time complexity so be careful in using it.
14838  */
14839 static char *complete_sipch(const char *line, const char *word, int pos, int state)
14840 {
14841    int which=0;
14842    struct sip_pvt *cur;
14843    char *c = NULL;
14844    int wordlen = strlen(word);
14845    struct ao2_iterator i;
14846 
14847    if (pos != 3) {
14848       return NULL;
14849    }
14850 
14851    i = ao2_iterator_init(dialogs, 0);
14852    
14853    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
14854       sip_pvt_lock(cur);
14855       if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
14856          c = ast_strdup(cur->callid);
14857          sip_pvt_unlock(cur);
14858          dialog_unref(cur, "drop ref in iterator loop break");
14859          break;
14860       }
14861       sip_pvt_unlock(cur);
14862       dialog_unref(cur, "drop ref in iterator loop");
14863    }
14864    return c;
14865 }
14866 
14867 
14868 /*! \brief Do completion on peer name */
14869 static char *complete_sip_peer(const char *word, int state, int flags2)
14870 {
14871    char *result = NULL;
14872    int wordlen = strlen(word);
14873    int which = 0;
14874    struct ao2_iterator i = ao2_iterator_init(peers, 0);
14875    struct sip_peer *peer;
14876 
14877    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
14878       /* locking of the object is not required because only the name and flags are being compared */
14879       if (!strncasecmp(word, peer->name, wordlen) &&
14880             (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
14881             ++which > state)
14882          result = ast_strdup(peer->name);
14883       unref_peer(peer, "toss iterator peer ptr before break");
14884       if (result) {
14885          break;
14886       }
14887    }
14888    return result;
14889 }
14890 
14891 /*! \brief Do completion on registered peer name */
14892 static char *complete_sip_registered_peer(const char *word, int state, int flags2)
14893 {
14894        char *result = NULL;
14895        int wordlen = strlen(word);
14896        int which = 0;
14897       struct ao2_iterator i;
14898       struct sip_peer *peer;
14899 
14900       i = ao2_iterator_init(peers, 0);
14901       while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
14902          if (!strncasecmp(word, peer->name, wordlen) &&
14903             (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
14904             ++which > state && peer->expire > 0)
14905             result = ast_strdup(peer->name);
14906          if (result) {
14907             unref_peer(peer, "toss iterator peer ptr before break");
14908             break;
14909          }
14910          unref_peer(peer, "toss iterator peer ptr");
14911        }
14912        return result;
14913 }
14914 
14915 /*! \brief Support routine for 'sip show history' CLI */
14916 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state)
14917 {
14918    if (pos == 3)
14919       return complete_sipch(line, word, pos, state);
14920 
14921    return NULL;
14922 }
14923 
14924 /*! \brief Support routine for 'sip show peer' CLI */
14925 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
14926 {
14927    if (pos == 3) {
14928       return complete_sip_peer(word, state, 0);
14929    }
14930 
14931    return NULL;
14932 }
14933 
14934 /*! \brief Support routine for 'sip unregister' CLI */
14935 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state)
14936 {
14937        if (pos == 2)
14938                return complete_sip_registered_peer(word, state, 0);
14939 
14940        return NULL;
14941 }
14942 
14943 /*! \brief Support routine for 'sip notify' CLI */
14944 static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
14945 {
14946    char *c = NULL;
14947 
14948    if (pos == 2) {
14949       int which = 0;
14950       char *cat = NULL;
14951       int wordlen = strlen(word);
14952 
14953       /* do completion for notify type */
14954 
14955       if (!notify_types)
14956          return NULL;
14957       
14958       while ( (cat = ast_category_browse(notify_types, cat)) ) {
14959          if (!strncasecmp(word, cat, wordlen) && ++which > state) {
14960             c = ast_strdup(cat);
14961             break;
14962          }
14963       }
14964       return c;
14965    }
14966 
14967    if (pos > 2)
14968       return complete_sip_peer(word, state, 0);
14969 
14970    return NULL;
14971 }
14972 
14973 /*! \brief Show details of one active dialog */
14974 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14975 {
14976    struct sip_pvt *cur;
14977    size_t len;
14978    int found = 0;
14979    struct ao2_iterator i;
14980 
14981    switch (cmd) {
14982    case CLI_INIT:
14983       e->command = "sip show channel";
14984       e->usage =
14985          "Usage: sip show channel <call-id>\n"
14986          "       Provides detailed status on a given SIP dialog (identified by SIP call-id).\n";
14987       return NULL;
14988    case CLI_GENERATE:
14989       return complete_sipch(a->line, a->word, a->pos, a->n);
14990    }
14991 
14992    if (a->argc != 4)
14993       return CLI_SHOWUSAGE;
14994    len = strlen(a->argv[3]);
14995    
14996    i = ao2_iterator_init(dialogs, 0);
14997 
14998    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
14999       sip_pvt_lock(cur);
15000 
15001       if (!strncasecmp(cur->callid, a->argv[3], len)) {
15002          char formatbuf[SIPBUFSIZE/2];
15003          ast_cli(a->fd, "\n");
15004          if (cur->subscribed != NONE)
15005             ast_cli(a->fd, "  * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
15006          else
15007             ast_cli(a->fd, "  * SIP Call\n");
15008          ast_cli(a->fd, "  Curr. trans. direction:  %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
15009          ast_cli(a->fd, "  Call-ID:                %s\n", cur->callid);
15010          ast_cli(a->fd, "  Owner channel ID:       %s\n", cur->owner ? cur->owner->name : "<none>");
15011          ast_cli(a->fd, "  Our Codec Capability:   %d\n", cur->capability);
15012          ast_cli(a->fd, "  Non-Codec Capability (DTMF):   %d\n", cur->noncodeccapability);
15013          ast_cli(a->fd, "  Their Codec Capability:   %d\n", cur->peercapability);
15014          ast_cli(a->fd, "  Joint Codec Capability:   %d\n", cur->jointcapability);
15015          ast_cli(a->fd, "  Format:                 %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
15016          ast_cli(a->fd, "  T.38 support            %s\n", cli_yesno(cur->udptl != NULL));
15017          ast_cli(a->fd, "  Video support           %s\n", cli_yesno(cur->vrtp != NULL));
15018          ast_cli(a->fd, "  MaxCallBR:              %d kbps\n", cur->maxcallbitrate);
15019          ast_cli(a->fd, "  Theoretical Address:    %s:%d\n", ast_inet_ntoa(cur->sa.sin_addr), ntohs(cur->sa.sin_port));
15020          ast_cli(a->fd, "  Received Address:       %s:%d\n", ast_inet_ntoa(cur->recv.sin_addr), ntohs(cur->recv.sin_port));
15021          ast_cli(a->fd, "  SIP Transfer mode:      %s\n", transfermode2str(cur->allowtransfer));
15022          ast_cli(a->fd, "  NAT Support:            %s\n", nat2str(ast_test_flag(&cur->flags[0], SIP_NAT)));
15023          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)" );
15024          ast_cli(a->fd, "  Our Tag:                %s\n", cur->tag);
15025          ast_cli(a->fd, "  Their Tag:              %s\n", cur->theirtag);
15026          ast_cli(a->fd, "  SIP User agent:         %s\n", cur->useragent);
15027          if (!ast_strlen_zero(cur->username))
15028             ast_cli(a->fd, "  Username:               %s\n", cur->username);
15029          if (!ast_strlen_zero(cur->peername))
15030             ast_cli(a->fd, "  Peername:               %s\n", cur->peername);
15031          if (!ast_strlen_zero(cur->uri))
15032             ast_cli(a->fd, "  Original uri:           %s\n", cur->uri);
15033          if (!ast_strlen_zero(cur->cid_num))
15034             ast_cli(a->fd, "  Caller-ID:              %s\n", cur->cid_num);
15035          ast_cli(a->fd, "  Need Destroy:           %s\n", cli_yesno(cur->needdestroy));
15036          ast_cli(a->fd, "  Last Message:           %s\n", cur->lastmsg);
15037          ast_cli(a->fd, "  Promiscuous Redir:      %s\n", cli_yesno(ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR)));
15038          ast_cli(a->fd, "  Route:                  %s\n", cur->route ? cur->route->hop : "N/A");
15039          ast_cli(a->fd, "  DTMF Mode:              %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
15040          ast_cli(a->fd, "  SIP Options:            ");
15041          if (cur->sipoptions) {
15042             int x;
15043             for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
15044                if (cur->sipoptions & sip_options[x].id)
15045                   ast_cli(a->fd, "%s ", sip_options[x].text);
15046             }
15047             ast_cli(a->fd, "\n");
15048          } else
15049             ast_cli(a->fd, "(none)\n");
15050 
15051          if (!cur->stimer)
15052             ast_cli(a->fd, "  Session-Timer:          Uninitiallized\n");
15053          else {
15054             ast_cli(a->fd, "  Session-Timer:          %s\n", cur->stimer->st_active ? "Active" : "Inactive");
15055             if (cur->stimer->st_active == TRUE) {
15056                ast_cli(a->fd, "  S-Timer Interval:       %d\n", cur->stimer->st_interval);
15057                ast_cli(a->fd, "  S-Timer Refresher:      %s\n", strefresher2str(cur->stimer->st_ref));
15058                ast_cli(a->fd, "  S-Timer Expirys:        %d\n", cur->stimer->st_expirys);
15059                ast_cli(a->fd, "  S-Timer Sched Id:       %d\n", cur->stimer->st_schedid);
15060                ast_cli(a->fd, "  S-Timer Peer Sts:       %s\n", cur->stimer->st_active_peer_ua ? "Active" : "Inactive");
15061                ast_cli(a->fd, "  S-Timer Cached Min-SE:  %d\n", cur->stimer->st_cached_min_se);
15062                ast_cli(a->fd, "  S-Timer Cached SE:      %d\n", cur->stimer->st_cached_max_se);
15063                ast_cli(a->fd, "  S-Timer Cached Ref:     %s\n", strefresher2str(cur->stimer->st_cached_ref));
15064                ast_cli(a->fd, "  S-Timer Cached Mode:    %s\n", stmode2str(cur->stimer->st_cached_mode));
15065             }
15066          }
15067 
15068          ast_cli(a->fd, "\n\n");
15069 
15070          found++;
15071       }
15072 
15073       sip_pvt_unlock(cur);
15074 
15075       ao2_t_ref(cur, -1, "toss dialog ptr set by iterator_next");
15076    }
15077 
15078    if (!found) 
15079       ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
15080 
15081    return CLI_SUCCESS;
15082 }
15083 
15084 /*! \brief Show history details of one dialog */
15085 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15086 {
15087    struct sip_pvt *cur;
15088    size_t len;
15089    int found = 0;
15090    struct ao2_iterator i;
15091 
15092    switch (cmd) {
15093    case CLI_INIT:
15094       e->command = "sip show history";
15095       e->usage =
15096          "Usage: sip show history <call-id>\n"
15097          "       Provides detailed dialog history on a given SIP call (specified by call-id).\n";
15098       return NULL;
15099    case CLI_GENERATE:
15100       return complete_sip_show_history(a->line, a->word, a->pos, a->n);
15101    }
15102 
15103    if (a->argc != 4)
15104       return CLI_SHOWUSAGE;
15105 
15106    if (!recordhistory)
15107       ast_cli(a->fd, "\n***Note: History recording is currently DISABLED.  Use 'sip set history on' to ENABLE.\n");
15108 
15109    len = strlen(a->argv[3]);
15110 
15111    i = ao2_iterator_init(dialogs, 0);
15112    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
15113       sip_pvt_lock(cur);
15114       if (!strncasecmp(cur->callid, a->argv[3], len)) {
15115          struct sip_history *hist;
15116          int x = 0;
15117 
15118          ast_cli(a->fd, "\n");
15119          if (cur->subscribed != NONE)
15120             ast_cli(a->fd, "  * Subscription\n");
15121          else
15122             ast_cli(a->fd, "  * SIP Call\n");
15123          if (cur->history)
15124             AST_LIST_TRAVERSE(cur->history, hist, list)
15125                ast_cli(a->fd, "%d. %s\n", ++x, hist->event);
15126          if (x == 0)
15127             ast_cli(a->fd, "Call '%s' has no history\n", cur->callid);
15128          found++;
15129       }
15130       sip_pvt_unlock(cur);
15131       ao2_t_ref(cur, -1, "toss dialog ptr from iterator_next");
15132    }
15133 
15134    if (!found) 
15135       ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
15136 
15137    return CLI_SUCCESS;
15138 }
15139 
15140 /*! \brief Dump SIP history to debug log file at end of lifespan for SIP dialog */
15141 static void sip_dump_history(struct sip_pvt *dialog)
15142 {
15143    int x = 0;
15144    struct sip_history *hist;
15145    static int errmsg = 0;
15146 
15147    if (!dialog)
15148       return;
15149 
15150    if (!option_debug && !sipdebug) {
15151       if (!errmsg) {
15152          ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
15153          errmsg = 1;
15154       }
15155       return;
15156    }
15157 
15158    ast_debug(1, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
15159    if (dialog->subscribed)
15160       ast_debug(1, "  * Subscription\n");
15161    else
15162       ast_debug(1, "  * SIP Call\n");
15163    if (dialog->history)
15164       AST_LIST_TRAVERSE(dialog->history, hist, list)
15165          ast_debug(1, "  %-3.3d. %s\n", ++x, hist->event);
15166    if (!x)
15167       ast_debug(1, "Call '%s' has no history\n", dialog->callid);
15168    ast_debug(1, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
15169 }
15170 
15171 
15172 /*! \brief  Receive SIP INFO Message */
15173 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
15174 {
15175    char buf[1024];
15176    unsigned int event;
15177    const char *c = get_header(req, "Content-Type");
15178 
15179    /* Need to check the media/type */
15180    if (!strcasecmp(c, "application/dtmf-relay") ||
15181        !strcasecmp(c, "application/vnd.nortelnetworks.digits")) {
15182       unsigned int duration = 0;
15183 
15184       if (!p->owner) {  /* not a PBX call */
15185          transmit_response(p, "481 Call leg/transaction does not exist", req);
15186          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15187          return;
15188       }
15189 
15190       /* Try getting the "signal=" part */
15191       if (ast_strlen_zero(c = get_body(req, "Signal")) && ast_strlen_zero(c = get_body(req, "d"))) {
15192          ast_log(LOG_WARNING, "Unable to retrieve DTMF signal from INFO message from %s\n", p->callid);
15193          transmit_response(p, "200 OK", req); /* Should return error */
15194          return;
15195       } else {
15196          ast_copy_string(buf, c, sizeof(buf));
15197       }
15198 
15199       if (!ast_strlen_zero((c = get_body(req, "Duration"))))
15200          duration = atoi(c);
15201       if (!duration)
15202          duration = 100; /* 100 ms */
15203 
15204 
15205       if (ast_strlen_zero(buf)) {
15206          transmit_response(p, "200 OK", req);
15207          return;
15208       }
15209 
15210       if (buf[0] == '*')
15211          event = 10;
15212       else if (buf[0] == '#')
15213          event = 11;
15214       else if ((buf[0] >= 'A') && (buf[0] <= 'D'))
15215          event = 12 + buf[0] - 'A';
15216       else if (buf[0] == '!')
15217          event = 16;
15218       else
15219          event = atoi(buf);
15220       if (event == 16) {
15221          /* send a FLASH event */
15222          struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
15223          ast_queue_frame(p->owner, &f);
15224          if (sipdebug)
15225             ast_verbose("* DTMF-relay event received: FLASH\n");
15226       } else {
15227          /* send a DTMF event */
15228          struct ast_frame f = { AST_FRAME_DTMF, };
15229          if (event < 10) {
15230             f.subclass = '0' + event;
15231          } else if (event < 11) {
15232             f.subclass = '*';
15233          } else if (event < 12) {
15234             f.subclass = '#';
15235          } else if (event < 16) {
15236             f.subclass = 'A' + (event - 12);
15237          }
15238          f.len = duration;
15239          ast_queue_frame(p->owner, &f);
15240          if (sipdebug)
15241             ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
15242       }
15243       transmit_response(p, "200 OK", req);
15244       return;
15245    } else if (!strcasecmp(c, "application/dtmf")) {
15246       /*! \todo Note: Doesn't read the duration of the DTMF. Should be fixed. */
15247       unsigned int duration = 0;
15248 
15249       if (!p->owner) {  /* not a PBX call */
15250          transmit_response(p, "481 Call leg/transaction does not exist", req);
15251          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15252          return;
15253       }
15254 
15255       get_msg_text(buf, sizeof(buf), req, TRUE);
15256       duration = 100; /* 100 ms */
15257 
15258       if (ast_strlen_zero(buf)) {
15259          transmit_response(p, "200 OK", req);
15260          return;
15261       }
15262       event = atoi(buf);
15263       if (event == 16) {
15264          /* send a FLASH event */
15265          struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
15266          ast_queue_frame(p->owner, &f);
15267          if (sipdebug)
15268             ast_verbose("* DTMF-relay event received: FLASH\n");
15269       } else {
15270          /* send a DTMF event */
15271          struct ast_frame f = { AST_FRAME_DTMF, };
15272          if (event < 10) {
15273             f.subclass = '0' + event;
15274          } else if (event < 11) {
15275             f.subclass = '*';
15276          } else if (event < 12) {
15277             f.subclass = '#';
15278          } else if (event < 16) {
15279             f.subclass = 'A' + (event - 12);
15280          }
15281          f.len = duration;
15282          ast_queue_frame(p->owner, &f);
15283          if (sipdebug)
15284             ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
15285       }
15286       transmit_response(p, "200 OK", req);
15287       return;
15288 
15289    } else if (!strcasecmp(c, "application/media_control+xml")) {
15290       /* Eh, we'll just assume it's a fast picture update for now */
15291       if (p->owner)
15292          ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
15293       transmit_response(p, "200 OK", req);
15294       return;
15295    } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
15296       /* Client code (from SNOM phone) */
15297       if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
15298          if (p->owner && p->owner->cdr)
15299             ast_cdr_setuserfield(p->owner, c);
15300          if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
15301             ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
15302          transmit_response(p, "200 OK", req);
15303       } else {
15304          transmit_response(p, "403 Forbidden", req);
15305       }
15306       return;
15307    } else if (!ast_strlen_zero(c = get_header(req, "Record"))) {
15308       /* INFO messages generated by some phones to start/stop recording
15309          on phone calls. 
15310          OEJ: I think this should be something that is enabled/disabled
15311          per device. I don't want incoming callers to record calls in my
15312          pbx.
15313       */
15314       /* first, get the feature string, if it exists */
15315       struct ast_call_feature *feat;
15316       int j;
15317       struct ast_frame f = { AST_FRAME_DTMF, };
15318 
15319       ast_rdlock_call_features();
15320       feat = ast_find_call_feature("automon");
15321       if (!feat || ast_strlen_zero(feat->exten)) {
15322          ast_log(LOG_WARNING, "Recording requested, but no One Touch Monitor registered. (See features.conf)\n");
15323          /* 403 means that we don't support this feature, so don't request it again */
15324          transmit_response(p, "403 Forbidden", req);
15325          ast_unlock_call_features();
15326          return;
15327       } 
15328       /* Send the feature code to the PBX as DTMF, just like the handset had sent it */
15329       f.len = 100;
15330       for (j=0; j < strlen(feat->exten); j++) {
15331          f.subclass = feat->exten[j];
15332          ast_queue_frame(p->owner, &f);
15333          if (sipdebug)
15334             ast_verbose("* DTMF-relay event faked: %c\n", f.subclass);
15335       }
15336       ast_unlock_call_features();
15337 
15338       ast_debug(1, "Got a Request to Record the channel, state %s\n", c);
15339       transmit_response(p, "200 OK", req);
15340       return;
15341    } else if (ast_strlen_zero(c = get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
15342       /* This is probably just a packet making sure the signalling is still up, just send back a 200 OK */
15343       transmit_response(p, "200 OK", req);
15344       return;
15345    }
15346 
15347    /* Other type of INFO message, not really understood by Asterisk */
15348    /* if (get_msg_text(buf, sizeof(buf), req)) { */
15349 
15350    ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
15351    transmit_response(p, "415 Unsupported media type", req);
15352    return;
15353 }
15354 
15355 /*! \brief Enable SIP Debugging for a single IP */
15356 static char *sip_do_debug_ip(int fd, char *arg)
15357 {
15358    struct hostent *hp;
15359    struct ast_hostent ahp;
15360    int port = 0;
15361    char *p;
15362 
15363    p = arg;
15364    strsep(&p, ":");
15365    if (p)
15366       port = atoi(p);
15367    hp = ast_gethostbyname(arg, &ahp);
15368    if (hp == NULL)
15369       return CLI_SHOWUSAGE;
15370 
15371    debugaddr.sin_family = AF_INET;
15372    memcpy(&debugaddr.sin_addr, hp->h_addr, sizeof(debugaddr.sin_addr));
15373    debugaddr.sin_port = htons(port);
15374    if (port == 0)
15375       ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_inet_ntoa(debugaddr.sin_addr));
15376    else
15377       ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), port);
15378 
15379    sipdebug |= sip_debug_console;
15380 
15381    return CLI_SUCCESS;
15382 }
15383 
15384 /*! \brief  Turn on SIP debugging for a given peer */
15385 static char *sip_do_debug_peer(int fd, char *arg)
15386 {
15387    struct sip_peer *peer = find_peer(arg, NULL, TRUE, FINDPEERS, FALSE);
15388    if (!peer)
15389       ast_cli(fd, "No such peer '%s'\n", arg);
15390    else if (peer->addr.sin_addr.s_addr == 0)
15391       ast_cli(fd, "Unable to get IP address of peer '%s'\n", arg);
15392    else {
15393       debugaddr.sin_family = AF_INET;
15394       debugaddr.sin_addr = peer->addr.sin_addr;
15395       debugaddr.sin_port = peer->addr.sin_port;
15396       ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n",
15397          ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
15398       sipdebug |= sip_debug_console;
15399    }
15400    if (peer)
15401       unref_peer(peer, "sip_do_debug_peer: unref_peer, from find_peer call");
15402    return CLI_SUCCESS;
15403 }
15404 
15405 /*! \brief Turn on SIP debugging (CLI command) */
15406 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15407 {
15408    int oldsipdebug = sipdebug & sip_debug_console;
15409    char *what;
15410 
15411    if (cmd == CLI_INIT) {
15412       e->command = "sip set debug {on|off|ip|peer}";
15413       e->usage =
15414          "Usage: sip set debug {off|on|ip addr[:port]|peer peername}\n"
15415          "       Globally disables dumping of SIP packets,\n"
15416          "       or enables it either globally or for a (single)\n"
15417          "       IP address or registered peer.\n";
15418       return NULL;
15419    } else if (cmd == CLI_GENERATE) {
15420       if (a->pos == 4 && strcasestr(a->line, " peer")) /* XXX should check on argv too */
15421          return complete_sip_peer(a->word, a->n, 0);
15422       return NULL;
15423         }
15424 
15425    what = a->argv[e->args-1];      /* guaranteed to exist */
15426    if (a->argc == e->args) {       /* on/off */
15427       if (!strcasecmp(what, "on")) {
15428          sipdebug |= sip_debug_console;
15429          sipdebug_text = 1;   /*! \note this can be a special debug command - "sip debug text" or something */
15430          memset(&debugaddr, 0, sizeof(debugaddr));
15431          ast_cli(a->fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
15432          return CLI_SUCCESS;
15433       } else if (!strcasecmp(what, "off")) {
15434          sipdebug &= ~sip_debug_console;
15435          sipdebug_text = 0;
15436          ast_cli(a->fd, "SIP Debugging Disabled\n");
15437          return CLI_SUCCESS;
15438       }
15439    } else if (a->argc == e->args +1) {/* ip/peer */
15440       if (!strcasecmp(what, "ip"))
15441          return sip_do_debug_ip(a->fd, a->argv[e->args]);
15442       else if (!strcasecmp(what, "peer"))
15443          return sip_do_debug_peer(a->fd, a->argv[e->args]);
15444    }
15445    return CLI_SHOWUSAGE;   /* default, failure */
15446 }
15447 
15448 /*! \brief Cli command to send SIP notify to peer */
15449 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15450 {
15451    struct ast_variable *varlist;
15452    int i;
15453 
15454    switch (cmd) {
15455    case CLI_INIT:
15456       e->command = "sip notify";
15457       e->usage =
15458          "Usage: sip notify <type> <peer> [<peer>...]\n"
15459          "       Send a NOTIFY message to a SIP peer or peers\n"
15460          "       Message types are defined in sip_notify.conf\n";
15461       return NULL;
15462    case CLI_GENERATE:
15463       return complete_sipnotify(a->line, a->word, a->pos, a->n);
15464    }
15465 
15466    if (a->argc < 4)
15467       return CLI_SHOWUSAGE;
15468 
15469    if (!notify_types) {
15470       ast_cli(a->fd, "No %s file found, or no types listed there\n", notify_config);
15471       return CLI_FAILURE;
15472    }
15473 
15474    varlist = ast_variable_browse(notify_types, a->argv[2]);
15475 
15476    if (!varlist) {
15477       ast_cli(a->fd, "Unable to find notify type '%s'\n", a->argv[2]);
15478       return CLI_FAILURE;
15479    }
15480 
15481    for (i = 3; i < a->argc; i++) {
15482       struct sip_pvt *p;
15483 
15484       if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
15485          ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
15486          return CLI_FAILURE;
15487       }
15488 
15489       if (create_addr(p, a->argv[i], NULL, 1)) {
15490          /* Maybe they're not registered, etc. */
15491          dialog_unlink_all(p, TRUE, TRUE);
15492          dialog_unref(p, "unref dialog inside for loop" );
15493          /* sip_destroy(p); */
15494          ast_cli(a->fd, "Could not create address for '%s'\n", a->argv[i]);
15495          continue;
15496       }
15497 
15498       /* Notify is outgoing call */
15499       ast_set_flag(&p->flags[0], SIP_OUTGOING);
15500 
15501       /* Recalculate our side, and recalculate Call ID */
15502       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
15503       build_via(p);
15504       ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
15505       build_callid_pvt(p);
15506       ao2_t_link(dialogs, p, "Linking in new name");
15507       ast_cli(a->fd, "Sending NOTIFY of type '%s' to '%s'\n", a->argv[2], a->argv[i]);
15508       dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
15509       sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
15510       transmit_notify_custom(p, varlist);
15511    }
15512 
15513    return CLI_SUCCESS;
15514 }
15515 
15516 /*! \brief Enable/Disable SIP History logging (CLI) - deprecated. use sip_set_history instead */
15517 static char *sip_do_history_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15518 {
15519    switch (cmd) {
15520    case CLI_INIT:
15521       e->command = "sip history [off]";
15522       e->usage =
15523          "Usage: sip history [off]\n"
15524          "       Enables/Disables recording of SIP dialog history for debugging purposes.\n"
15525          "       Use 'sip show history' to view the history of a call number.\n";
15526       return NULL;
15527    case CLI_GENERATE:
15528       return NULL;
15529    }
15530 
15531    if (a->argc < 2 || a->argc > 3) {
15532       return CLI_SHOWUSAGE;
15533    }
15534    if (a->argc == 2) {
15535       recordhistory = TRUE;
15536       ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
15537    } else {
15538       if (strncasecmp(a->argv[2], "off", 3))
15539          return CLI_SHOWUSAGE;
15540       recordhistory = FALSE;
15541       ast_cli(a->fd, "SIP History Recording Disabled\n");
15542    }
15543    return CLI_SUCCESS;
15544 }
15545 
15546 /*! \brief Enable/Disable SIP History logging (CLI) */
15547 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15548 {
15549    switch (cmd) {
15550    case CLI_INIT:
15551       e->command = "sip set history {on|off}";
15552       e->usage =
15553          "Usage: sip set history {on|off}\n"
15554          "       Enables/Disables recording of SIP dialog history for debugging purposes.\n"
15555          "       Use 'sip show history' to view the history of a call number.\n";
15556       return NULL;
15557    case CLI_GENERATE:
15558       return NULL;
15559    }
15560 
15561    if (a->argc != e->args)
15562       return CLI_SHOWUSAGE;
15563 
15564    if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
15565       recordhistory = TRUE;
15566       ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
15567    } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
15568       recordhistory = FALSE;
15569       ast_cli(a->fd, "SIP History Recording Disabled\n");
15570    } else {
15571       return CLI_SHOWUSAGE;
15572    }
15573    return CLI_SUCCESS;
15574 }
15575 
15576 /*! \brief Authenticate for outbound registration */
15577 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code)
15578 {
15579    char *header, *respheader;
15580    char digest[1024];
15581 
15582    p->authtries++;
15583    auth_headers(code, &header, &respheader);
15584    memset(digest, 0, sizeof(digest));
15585    if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
15586       /* There's nothing to use for authentication */
15587       /* No digest challenge in request */
15588       if (sip_debug_test_pvt(p) && p->registry)
15589          ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
15590          /* No old challenge */
15591       return -1;
15592    }
15593    if (p->do_history)
15594       append_history(p, "RegistryAuth", "Try: %d", p->authtries);
15595    if (sip_debug_test_pvt(p) && p->registry)
15596       ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
15597    return transmit_register(p->registry, SIP_REGISTER, digest, respheader); 
15598 }
15599 
15600 /*! \brief Add authentication on outbound SIP packet */
15601 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code, int sipmethod, int init)
15602 {
15603    char *header, *respheader;
15604    char digest[1024];
15605 
15606    if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
15607       return -2;
15608 
15609    p->authtries++;
15610    auth_headers(code, &header, &respheader);
15611    ast_debug(2, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
15612    memset(digest, 0, sizeof(digest));
15613    if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
15614       /* No way to authenticate */
15615       return -1;
15616    }
15617    /* Now we have a reply digest */
15618    p->options->auth = digest;
15619    p->options->authheader = respheader;
15620    return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init); 
15621 }
15622 
15623 /*! \brief  reply to authentication for outbound registrations
15624 \return  Returns -1 if we have no auth 
15625 \note This is used for register= servers in sip.conf, SIP proxies we register
15626    with  for receiving calls from.  */
15627 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod,  char *digest, int digest_len)
15628 {
15629    char tmp[512];
15630    char *c;
15631    char oldnonce[256];
15632 
15633    /* table of recognised keywords, and places where they should be copied */
15634    const struct x {
15635       const char *key;
15636       const ast_string_field *field;
15637    } *i, keys[] = {
15638       { "realm=", &p->realm },
15639       { "nonce=", &p->nonce },
15640       { "opaque=", &p->opaque },
15641       { "qop=", &p->qop },
15642       { "domain=", &p->domain },
15643       { NULL, 0 },
15644    };
15645 
15646    ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
15647    if (ast_strlen_zero(tmp)) 
15648       return -1;
15649    if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
15650       ast_log(LOG_WARNING, "missing Digest.\n");
15651       return -1;
15652    }
15653    c = tmp + strlen("Digest ");
15654    ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
15655    while (c && *(c = ast_skip_blanks(c))) {  /* lookup for keys */
15656       for (i = keys; i->key != NULL; i++) {
15657          char *src, *separator;
15658          if (strncasecmp(c, i->key, strlen(i->key)) != 0)
15659             continue;
15660          /* Found. Skip keyword, take text in quotes or up to the separator. */
15661          c += strlen(i->key);
15662          if (*c == '"') {
15663             src = ++c;
15664             separator = "\"";
15665          } else {
15666             src = c;
15667             separator = ",";
15668          }
15669          strsep(&c, separator); /* clear separator and move ptr */
15670          ast_string_field_ptr_set(p, i->field, src);
15671          break;
15672       }
15673       if (i->key == NULL) /* not found, try ',' */
15674          strsep(&c, ",");
15675    }
15676    /* Reset nonce count */
15677    if (strcmp(p->nonce, oldnonce)) 
15678       p->noncecount = 0;
15679 
15680    /* Save auth data for following registrations */
15681    if (p->registry) {
15682       struct sip_registry *r = p->registry;
15683 
15684       if (strcmp(r->nonce, p->nonce)) {
15685          ast_string_field_set(r, realm, p->realm);
15686          ast_string_field_set(r, nonce, p->nonce);
15687          ast_string_field_set(r, domain, p->domain);
15688          ast_string_field_set(r, opaque, p->opaque);
15689          ast_string_field_set(r, qop, p->qop);
15690          r->noncecount = 0;
15691       }
15692    }
15693    return build_reply_digest(p, sipmethod, digest, digest_len); 
15694 }
15695 
15696 /*! \brief  Build reply digest 
15697 \return  Returns -1 if we have no auth 
15698 \note Build digest challenge for authentication of registrations and calls
15699    Also used for authentication of BYE 
15700 */
15701 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
15702 {
15703    char a1[256];
15704    char a2[256];
15705    char a1_hash[256];
15706    char a2_hash[256];
15707    char resp[256];
15708    char resp_hash[256];
15709    char uri[256];
15710    char opaque[256] = "";
15711    char cnonce[80];
15712    const char *username;
15713    const char *secret;
15714    const char *md5secret;
15715    struct sip_auth *auth = NULL; /* Realm authentication */
15716 
15717    if (!ast_strlen_zero(p->domain))
15718       ast_copy_string(uri, p->domain, sizeof(uri));
15719    else if (!ast_strlen_zero(p->uri))
15720       ast_copy_string(uri, p->uri, sizeof(uri));
15721    else
15722       snprintf(uri, sizeof(uri), "sip:%s@%s", p->username, ast_inet_ntoa(p->sa.sin_addr));
15723 
15724    snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
15725 
15726    /* Check if we have separate auth credentials */
15727    if(!(auth = find_realm_authentication(p->peerauth, p->realm))) /* Start with peer list */
15728       auth = find_realm_authentication(authl, p->realm); /* If not, global list */
15729 
15730    if (auth) {
15731       ast_log(LOG_DEBUG, "use realm [%s] from peer [%s][%s]\n", auth->username, p->peername, p->username);
15732       username = auth->username;
15733       secret = auth->secret;
15734       md5secret = auth->md5secret;
15735       if (sipdebug)
15736          ast_debug(1, "Using realm %s authentication for call %s\n", p->realm, p->callid);
15737    } else {
15738       /* No authentication, use peer or register= config */
15739       username = p->authname;
15740       secret =  p->peersecret;
15741       md5secret = p->peermd5secret;
15742    }
15743    if (ast_strlen_zero(username))   /* We have no authentication */
15744       return -1;
15745 
15746    /* Calculate SIP digest response */
15747    snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
15748    snprintf(a2, sizeof(a2), "%s:%s", sip_methods[method].text, uri);
15749    if (!ast_strlen_zero(md5secret))
15750       ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
15751    else
15752       ast_md5_hash(a1_hash, a1);
15753    ast_md5_hash(a2_hash, a2);
15754 
15755    p->noncecount++;
15756    if (!ast_strlen_zero(p->qop))
15757       snprintf(resp, sizeof(resp), "%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
15758    else
15759       snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, p->nonce, a2_hash);
15760    ast_md5_hash(resp_hash, resp);
15761 
15762    /* only include the opaque string if it's set */
15763    if (!ast_strlen_zero(p->opaque)) {
15764      snprintf(opaque, sizeof(opaque), ", opaque=\"%s\"", p->opaque);
15765    }
15766 
15767    /* XXX We hard code our qop to "auth" for now.  XXX */
15768    if (!ast_strlen_zero(p->qop))
15769       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);
15770    else
15771       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);
15772 
15773    append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
15774 
15775    return 0;
15776 }
15777    
15778 /*! \brief Read SIP header (dialplan function) */
15779 static int func_header_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len) 
15780 {
15781    struct sip_pvt *p;
15782    const char *content = NULL;
15783    AST_DECLARE_APP_ARGS(args,
15784       AST_APP_ARG(header);
15785       AST_APP_ARG(number);
15786    );
15787    int i, number, start = 0;
15788 
15789    if (ast_strlen_zero(data)) {
15790       ast_log(LOG_WARNING, "This function requires a header name.\n");
15791       return -1;
15792    }
15793 
15794    ast_channel_lock(chan);
15795    if (!IS_SIP_TECH(chan->tech)) {
15796       ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
15797       ast_channel_unlock(chan);
15798       return -1;
15799    }
15800 
15801    AST_STANDARD_APP_ARGS(args, data);
15802    if (!args.number) {
15803       number = 1;
15804    } else {
15805       sscanf(args.number, "%30d", &number);
15806       if (number < 1)
15807          number = 1;
15808    }
15809 
15810    p = chan->tech_pvt;
15811 
15812    /* If there is no private structure, this channel is no longer alive */
15813    if (!p) {
15814       ast_channel_unlock(chan);
15815       return -1;
15816    }
15817 
15818    for (i = 0; i < number; i++)
15819       content = __get_header(&p->initreq, args.header, &start);
15820 
15821    if (ast_strlen_zero(content)) {
15822       ast_channel_unlock(chan);
15823       return -1;
15824    }
15825 
15826    ast_copy_string(buf, content, len);
15827    ast_channel_unlock(chan);
15828 
15829    return 0;
15830 }
15831 
15832 static struct ast_custom_function sip_header_function = {
15833    .name = "SIP_HEADER",
15834    .synopsis = "Gets the specified SIP header",
15835    .syntax = "SIP_HEADER(<name>[,<number>])",
15836    .desc = "Since there are several headers (such as Via) which can occur multiple\n"
15837    "times, SIP_HEADER takes an optional second argument to specify which header with\n"
15838    "that name to retrieve. Headers start at offset 1.\n",
15839    .read = func_header_read,
15840 };
15841 
15842 /*! \brief  Dial plan function to check if domain is local */
15843 static int func_check_sipdomain(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
15844 {
15845    if (ast_strlen_zero(data)) {
15846       ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
15847       return -1;
15848    }
15849    if (check_sip_domain(data, NULL, 0))
15850       ast_copy_string(buf, data, len);
15851    else
15852       buf[0] = '\0';
15853    return 0;
15854 }
15855 
15856 static struct ast_custom_function checksipdomain_function = {
15857    .name = "CHECKSIPDOMAIN",
15858    .synopsis = "Checks if domain is a local domain",
15859    .syntax = "CHECKSIPDOMAIN(<domain|IP>)",
15860    .read = func_check_sipdomain,
15861    .desc = "This function checks if the domain in the argument is configured\n"
15862       "as a local SIP domain that this Asterisk server is configured to handle.\n"
15863       "Returns the domain name if it is locally handled, otherwise an empty string.\n"
15864       "Check the domain= configuration in sip.conf\n",
15865 };
15866 
15867 /*! \brief  ${SIPPEER()} Dialplan function - reads peer data */
15868 static int function_sippeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
15869 {
15870    struct sip_peer *peer;
15871    char *colname;
15872 
15873    if ((colname = strchr(data, ':'))) {   /*! \todo Will be deprecated after 1.4 */
15874       static int deprecation_warning = 0;
15875       *colname++ = '\0';
15876       if (deprecation_warning++ % 10 == 0)
15877          ast_log(LOG_WARNING, "SIPPEER(): usage of ':' to separate arguments is deprecated.  Please use ',' instead.\n");
15878    } else if ((colname = strchr(data, ',')))
15879       *colname++ = '\0';
15880    else
15881       colname = "ip";
15882 
15883    if (!(peer = find_peer(data, NULL, TRUE, FINDPEERS, FALSE)))
15884       return -1;
15885 
15886    if (!strcasecmp(colname, "ip")) {
15887       ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len);
15888    } else  if (!strcasecmp(colname, "port")) {
15889       snprintf(buf, len, "%d", ntohs(peer->addr.sin_port));
15890    } else  if (!strcasecmp(colname, "status")) {
15891       peer_status(peer, buf, len);
15892    } else  if (!strcasecmp(colname, "language")) {
15893       ast_copy_string(buf, peer->language, len);
15894    } else  if (!strcasecmp(colname, "regexten")) {
15895       ast_copy_string(buf, peer->regexten, len);
15896    } else  if (!strcasecmp(colname, "limit")) {
15897       snprintf(buf, len, "%d", peer->call_limit);
15898    } else  if (!strcasecmp(colname, "busylevel")) {
15899       snprintf(buf, len, "%d", peer->busy_level);
15900    } else  if (!strcasecmp(colname, "curcalls")) {
15901       snprintf(buf, len, "%d", peer->inUse);
15902    } else  if (!strcasecmp(colname, "accountcode")) {
15903       ast_copy_string(buf, peer->accountcode, len);
15904    } else  if (!strcasecmp(colname, "callgroup")) {
15905       ast_print_group(buf, len, peer->callgroup);
15906    } else  if (!strcasecmp(colname, "pickupgroup")) {
15907       ast_print_group(buf, len, peer->pickupgroup);
15908    } else  if (!strcasecmp(colname, "useragent")) {
15909       ast_copy_string(buf, peer->useragent, len);
15910    } else  if (!strcasecmp(colname, "mailbox")) {
15911       struct ast_str *mailbox_str = ast_str_alloca(512);
15912       peer_mailboxes_to_str(&mailbox_str, peer);
15913       ast_copy_string(buf, mailbox_str->str, len);
15914    } else  if (!strcasecmp(colname, "context")) {
15915       ast_copy_string(buf, peer->context, len);
15916    } else  if (!strcasecmp(colname, "expire")) {
15917       snprintf(buf, len, "%d", peer->expire);
15918    } else  if (!strcasecmp(colname, "dynamic")) {
15919       ast_copy_string(buf, peer->host_dynamic ? "yes" : "no", len);
15920    } else  if (!strcasecmp(colname, "callerid_name")) {
15921       ast_copy_string(buf, peer->cid_name, len);
15922    } else  if (!strcasecmp(colname, "callerid_num")) {
15923       ast_copy_string(buf, peer->cid_num, len);
15924    } else  if (!strcasecmp(colname, "codecs")) {
15925       ast_getformatname_multiple(buf, len -1, peer->capability);
15926    } else  if (!strncasecmp(colname, "chanvar[", 8)) {
15927       char *chanvar=colname + 8;
15928       struct ast_variable *v;
15929    
15930       chanvar = strsep(&chanvar, "]");
15931       for (v = peer->chanvars ; v ; v = v->next)
15932          if (!strcasecmp(v->name, chanvar))
15933             ast_copy_string(buf, v->value, len);
15934    } else  if (!strncasecmp(colname, "codec[", 6)) {
15935       char *codecnum;
15936       int codec = 0;
15937       
15938       codecnum = colname + 6; /* move past the '[' */
15939       codecnum = strsep(&codecnum, "]"); /* trim trailing ']' if any */
15940       if((codec = ast_codec_pref_index(&peer->prefs, atoi(codecnum)))) {
15941          ast_copy_string(buf, ast_getformatname(codec), len);
15942       } else {
15943          buf[0] = '\0';
15944       }
15945    } else {
15946       buf[0] = '\0';
15947    }
15948 
15949    unref_peer(peer, "unref_peer from function_sippeer, just before return");
15950 
15951    return 0;
15952 }
15953 
15954 /*! \brief Structure to declare a dialplan function: SIPPEER */
15955 struct ast_custom_function sippeer_function = {
15956    .name = "SIPPEER",
15957    .synopsis = "Gets SIP peer information",
15958    .syntax = "SIPPEER(<peername>[,item])",
15959    .read = function_sippeer,
15960    .desc = "Valid items are:\n"
15961    "- ip (default)          The IP address.\n"
15962    "- port                  The port number\n"
15963    "- mailbox               The configured mailbox.\n"
15964    "- context               The configured context.\n"
15965    "- expire                The epoch time of the next expire.\n"
15966    "- dynamic               Is it dynamic? (yes/no).\n"
15967    "- callerid_name         The configured Caller ID name.\n"
15968    "- callerid_num          The configured Caller ID number.\n"
15969    "- callgroup             The configured Callgroup.\n"
15970    "- pickupgroup           The configured Pickupgroup.\n"
15971    "- codecs                The configured codecs.\n"
15972    "- status                Status (if qualify=yes).\n"
15973    "- regexten              Registration extension\n"
15974    "- limit                 Call limit (call-limit)\n"
15975    "- busylevel             Configured call level for signalling busy\n"
15976    "- curcalls              Current amount of calls \n"
15977    "                        Only available if call-limit is set\n"
15978    "- language              Default language for peer\n"
15979    "- accountcode           Account code for this peer\n"
15980    "- useragent             Current user agent id for peer\n"
15981    "- chanvar[name]         A channel variable configured with setvar for this peer.\n"
15982    "- codec[x]              Preferred codec index number 'x' (beginning with zero).\n"
15983    "\n"
15984 };
15985 
15986 /*! \brief ${SIPCHANINFO()} Dialplan function - reads sip channel data */
15987 static int function_sipchaninfo_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
15988 {
15989    struct sip_pvt *p;
15990    static int deprecated = 0;
15991 
15992    *buf = 0;
15993    
15994    if (!data) {
15995       ast_log(LOG_WARNING, "This function requires a parameter name.\n");
15996       return -1;
15997    }
15998 
15999    ast_channel_lock(chan);
16000    if (!IS_SIP_TECH(chan->tech)) {
16001       ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
16002       ast_channel_unlock(chan);
16003       return -1;
16004    }
16005 
16006    if (deprecated++ % 20 == 0) {
16007       /* Deprecated in 1.6.1 */
16008       ast_log(LOG_WARNING, "SIPCHANINFO() is deprecated.  Please transition to using CHANNEL().\n");
16009    }
16010 
16011    p = chan->tech_pvt;
16012 
16013    /* If there is no private structure, this channel is no longer alive */
16014    if (!p) {
16015       ast_channel_unlock(chan);
16016       return -1;
16017    }
16018 
16019    if (!strcasecmp(data, "peerip")) {
16020       ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", len);
16021    } else  if (!strcasecmp(data, "recvip")) {
16022       ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", len);
16023    } else  if (!strcasecmp(data, "from")) {
16024       ast_copy_string(buf, p->from, len);
16025    } else  if (!strcasecmp(data, "uri")) {
16026       ast_copy_string(buf, p->uri, len);
16027    } else  if (!strcasecmp(data, "useragent")) {
16028       ast_copy_string(buf, p->useragent, len);
16029    } else  if (!strcasecmp(data, "peername")) {
16030       ast_copy_string(buf, p->peername, len);
16031    } else if (!strcasecmp(data, "t38passthrough")) {
16032       if (p->t38.state == T38_DISABLED)
16033          ast_copy_string(buf, "0", sizeof("0"));
16034       else    /* T38 is offered or enabled in this call */
16035          ast_copy_string(buf, "1", sizeof("1"));
16036    } else {
16037       ast_channel_unlock(chan);
16038       return -1;
16039    }
16040    ast_channel_unlock(chan);
16041 
16042    return 0;
16043 }
16044 
16045 /*! \brief Structure to declare a dialplan function: SIPCHANINFO */
16046 static struct ast_custom_function sipchaninfo_function = {
16047    .name = "SIPCHANINFO",
16048    .synopsis = "Gets the specified SIP parameter from the current channel",
16049    .syntax = "SIPCHANINFO(item)",
16050    .read = function_sipchaninfo_read,
16051    .desc = "Valid items are:\n"
16052    "- peerip                The IP address of the peer.\n"
16053    "- recvip                The source IP address of the peer.\n"
16054    "- from                  The URI from the From: header.\n"
16055    "- uri                   The URI from the Contact: header.\n"
16056    "- useragent             The useragent.\n"
16057    "- peername              The name of the peer.\n"
16058    "- t38passthrough        1 if T38 is offered or enabled in this channel, otherwise 0\n"
16059 };
16060 
16061 /*! \brief Parse 302 Moved temporalily response */
16062 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req)
16063 {
16064    char tmp[SIPBUFSIZE];
16065    char *s, *e, *t, *trans;
16066    char *domain;
16067    enum sip_transport transport = SIP_TRANSPORT_UDP;
16068 
16069    ast_copy_string(tmp, get_header(req, "Contact"), sizeof(tmp));
16070    if ((t = strchr(tmp, ',')))
16071       *t = '\0';
16072 
16073    s = get_in_brackets(tmp);
16074    if ((trans = strcasestr(s, ";transport="))) do {
16075       trans += 11;
16076 
16077       if ((e = strchr(trans, ';')))
16078          *e = '\0';
16079 
16080       if (!strncasecmp(trans, "tcp", 3))
16081          transport = SIP_TRANSPORT_TCP;
16082       else if (!strncasecmp(trans, "tls", 3))
16083          transport = SIP_TRANSPORT_TLS;
16084       else {
16085          if (strncasecmp(trans, "udp", 3))
16086             ast_debug(1, "received contact with an invalid transport, '%s'\n", s);
16087          transport = SIP_TRANSPORT_UDP;
16088       }
16089    } while(0);
16090    s = remove_uri_parameters(s);
16091 
16092    if (p->socket.tcptls_session) {
16093       ao2_ref(p->socket.tcptls_session, -1);
16094       p->socket.tcptls_session = NULL;
16095    }
16096 
16097    set_socket_transport(&p->socket, transport);
16098 
16099    if (ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
16100       char *host = NULL;
16101       if (!strncasecmp(s, "sip:", 4))
16102          s += 4;
16103       else if (!strncasecmp(s, "sips:", 5))
16104          s += 5;
16105       e = strchr(s, '/');
16106       if (e)
16107          *e = '\0';
16108       if ((host = strchr(s, '@'))) {
16109          *host++ = '\0';
16110          ast_debug(2, "Found promiscuous redirection to 'SIP/%s::::%s@%s'\n", s, get_transport(transport), host);
16111          if (p->owner)
16112             ast_string_field_build(p->owner, call_forward, "SIP/%s::::%s@%s", s, get_transport(transport), host);
16113       } else {
16114          ast_debug(2, "Found promiscuous redirection to 'SIP/::::%s@%s'\n", get_transport(transport), s);
16115          if (p->owner)
16116             ast_string_field_build(p->owner, call_forward, "SIP/::::%s@%s", get_transport(transport), s);
16117       }
16118    } else {
16119       e = strchr(tmp, '@');
16120       if (e) {
16121          *e++ = '\0';
16122          domain = e;
16123       } else {
16124          /* No username part */
16125          domain = tmp;
16126       }
16127       e = strchr(tmp, '/');   /* WHEN do we hae a forward slash in the URI? */
16128       if (e)
16129          *e = '\0';
16130 
16131       if (!strncasecmp(s, "sip:", 4))
16132          s += 4;
16133       else if (!strncasecmp(s, "sips:", 5))
16134          s += 5;
16135       e = strchr(s, ';');  /* And username ; parameters? */
16136       if (e)
16137          *e = '\0';  
16138       ast_debug(2, "Received 302 Redirect to extension '%s' (domain %s)\n", s, domain);
16139       if (p->owner) {
16140          pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
16141          ast_string_field_set(p->owner, call_forward, s);
16142       }
16143    }
16144 }
16145 
16146 /*! \brief Check pending actions on SIP call */
16147 static void check_pendings(struct sip_pvt *p)
16148 {
16149    if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
16150       /* if we can't BYE, then this is really a pending CANCEL */
16151       if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA)
16152          transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
16153          /* Actually don't destroy us yet, wait for the 487 on our original 
16154             INVITE, but do set an autodestruct just in case we never get it. */
16155       else {
16156          /* We have a pending outbound invite, don't send someting
16157             new in-transaction */
16158          if (p->pendinginvite)
16159             return;
16160 
16161          /* Perhaps there is an SD change INVITE outstanding */
16162          transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
16163       }
16164       ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);   
16165       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16166    } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
16167       /* if we can't REINVITE, hold it for later */
16168       if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
16169          ast_debug(2, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
16170       } else {
16171          ast_debug(2, "Sending pending reinvite on '%s'\n", p->callid);
16172          /* Didn't get to reinvite yet, so do it now */
16173          transmit_reinvite_with_sdp(p, (p->t38.state == T38_LOCAL_REINVITE ? TRUE : FALSE), FALSE);
16174          ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE); 
16175       }
16176    }
16177 }
16178 
16179 /*! \brief Reset the NEEDREINVITE flag after waiting when we get 491 on a Re-invite
16180    to avoid race conditions between asterisk servers.
16181    Called from the scheduler.
16182 */
16183 static int sip_reinvite_retry(const void *data)
16184 {
16185    struct sip_pvt *p = (struct sip_pvt *) data;
16186 
16187    sip_pvt_lock(p); /* called from schedule thread which requires a lock */
16188    ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
16189    p->waitid = -1;
16190    check_pendings(p);
16191    sip_pvt_unlock(p);
16192    dialog_unref(p, "unref the dialog ptr from sip_reinvite_retry, because it held a dialog ptr");
16193    return 0;
16194 }
16195 
16196 
16197 /*! \brief Handle SIP response to INVITE dialogue */
16198 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
16199 {
16200    int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
16201    int res = 0;
16202    int xmitres = 0;
16203    int reinvite = (p->owner && p->owner->_state == AST_STATE_UP);
16204    char *p_hdrval;
16205    int rtn;
16206 
16207    if (reinvite)
16208       ast_debug(4, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
16209    else
16210       ast_debug(4, "SIP response %d to standard invite\n", resp);
16211 
16212    if (p->alreadygone) { /* This call is already gone */
16213       ast_debug(1, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
16214       return;
16215    }
16216 
16217    /* Acknowledge sequence number - This only happens on INVITE from SIP-call */
16218    /* Don't auto congest anymore since we've gotten something useful back */
16219    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"));
16220 
16221    /* RFC3261 says we must treat every 1xx response (but not 100)
16222       that we don't recognize as if it was 183.
16223    */
16224    if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 182 && resp != 183)
16225       resp = 183;
16226 
16227    /* Any response between 100 and 199 is PROCEEDING */
16228    if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING)
16229       p->invitestate = INV_PROCEEDING;
16230  
16231    /* Final response, not 200 ? */
16232    if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA ))
16233       p->invitestate = INV_COMPLETED;
16234    
16235    /* Final response, clear out pending invite */
16236    if ((resp == 200 || resp >= 300) && p->pendinginvite && seqno == p->pendinginvite)
16237       p->pendinginvite = 0;
16238 
16239    switch (resp) {
16240    case 100:   /* Trying */
16241    case 101:   /* Dialog establishment */
16242       if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
16243          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
16244       check_pendings(p);
16245       break;
16246 
16247    case 180:   /* 180 Ringing */
16248    case 182:       /* 182 Queued */
16249       if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
16250          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
16251       if (!req->ignore && p->owner) {
16252          ast_queue_control(p->owner, AST_CONTROL_RINGING);
16253          if (p->owner->_state != AST_STATE_UP) {
16254             ast_setstate(p->owner, AST_STATE_RINGING);
16255          }
16256       }
16257       if (find_sdp(req)) {
16258          if (p->invitestate != INV_CANCELLED)
16259             p->invitestate = INV_EARLY_MEDIA;
16260          res = process_sdp(p, req, SDP_T38_NONE);
16261          if (!req->ignore && p->owner) {
16262             /* Queue a progress frame only if we have SDP in 180 or 182 */
16263             ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
16264          }
16265       }
16266       check_pendings(p);
16267       break;
16268 
16269    case 183:   /* Session progress */
16270       if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
16271          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
16272       if (find_sdp(req)) {
16273          if (p->invitestate != INV_CANCELLED)
16274             p->invitestate = INV_EARLY_MEDIA;
16275          res = process_sdp(p, req, SDP_T38_NONE);
16276          if (!req->ignore && p->owner) {
16277             /* Queue a progress frame */
16278             ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
16279          }
16280       } else {
16281          /* Alcatel PBXs are known to send 183s with no SDP after sending
16282           * a 100 Trying response. We're just going to treat this sort of thing
16283           * the same as we would treat a 180 Ringing
16284           */
16285          if (!req->ignore && p->owner) {
16286             ast_queue_control(p->owner, AST_CONTROL_RINGING);
16287          }
16288       }
16289       check_pendings(p);
16290       break;
16291 
16292    case 200:   /* 200 OK on invite - someone's answering our call */
16293       if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
16294          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
16295       p->authtries = 0;
16296       if (find_sdp(req)) {
16297          if ((res = process_sdp(p, req, SDP_T38_ACCEPT)) && !req->ignore)
16298             if (!reinvite)
16299                /* This 200 OK's SDP is not acceptable, so we need to ack, then hangup */
16300                /* For re-invites, we try to recover */
16301                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
16302       }
16303 
16304       /* Parse contact header for continued conversation */
16305       /* When we get 200 OK, we know which device (and IP) to contact for this call */
16306       /* This is important when we have a SIP proxy between us and the phone */
16307       if (outgoing) {
16308          update_call_counter(p, DEC_CALL_RINGING);
16309          parse_ok_contact(p, req);
16310          /* Save Record-Route for any later requests we make on this dialogue */
16311          if (!reinvite)
16312             build_route(p, req, 1);
16313 
16314          if(set_address_from_contact(p)) {
16315             /* Bad contact - we don't know how to reach this device */
16316             /* We need to ACK, but then send a bye */
16317             if (!p->route && !req->ignore)
16318                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
16319          } 
16320 
16321       }
16322 
16323       if (!req->ignore && p->owner) {
16324          if (!reinvite) {
16325             ast_queue_control(p->owner, AST_CONTROL_ANSWER);
16326             if (global_callevents)
16327                manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
16328                   "Channel: %s\r\nChanneltype: %s\r\nUniqueid: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
16329                   p->owner->name, "SIP", p->owner->uniqueid, p->callid, p->fullcontact, p->peername);
16330          } else { /* RE-invite */
16331             ast_queue_frame(p->owner, &ast_null_frame);
16332          }
16333       } else {
16334           /* It's possible we're getting an 200 OK after we've tried to disconnect
16335               by sending CANCEL */
16336          /* First send ACK, then send bye */
16337          if (!req->ignore)
16338             ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
16339       }
16340 
16341       /* Check for Session-Timers related headers */
16342       if (st_get_mode(p) != SESSION_TIMER_MODE_REFUSE && p->outgoing_call == TRUE && !reinvite) {
16343          p_hdrval = (char*)get_header(req, "Session-Expires");
16344             if (!ast_strlen_zero(p_hdrval)) {
16345             /* UAS supports Session-Timers */
16346             enum st_refresher tmp_st_ref = SESSION_TIMER_REFRESHER_AUTO;
16347             int tmp_st_interval = 0;
16348             rtn = parse_session_expires(p_hdrval, &tmp_st_interval, &tmp_st_ref);
16349             if (rtn != 0) {
16350                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
16351             }
16352             if (tmp_st_ref == SESSION_TIMER_REFRESHER_UAC || 
16353                tmp_st_ref == SESSION_TIMER_REFRESHER_UAS) {
16354                p->stimer->st_ref = tmp_st_ref;
16355             } 
16356             if (tmp_st_interval) {
16357                p->stimer->st_interval = tmp_st_interval;
16358             }
16359             p->stimer->st_active = TRUE;
16360             p->stimer->st_active_peer_ua = TRUE;
16361             start_session_timer(p);
16362          } else {
16363             /* UAS doesn't support Session-Timers */
16364             if (st_get_mode(p) == SESSION_TIMER_MODE_ORIGINATE) {
16365                p->stimer->st_ref = SESSION_TIMER_REFRESHER_UAC;
16366                p->stimer->st_active_peer_ua = FALSE;
16367                start_session_timer(p);
16368             }
16369          }
16370       }
16371 
16372 
16373       /* If I understand this right, the branch is different for a non-200 ACK only */
16374       p->invitestate = INV_TERMINATED;
16375       ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
16376       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
16377       check_pendings(p);
16378       break;
16379 
16380    case 407: /* Proxy authentication */
16381    case 401: /* Www auth */
16382       /* First we ACK */
16383       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
16384       if (p->options)
16385          p->options->auth_type = resp;
16386 
16387       /* Then we AUTH */
16388       ast_string_field_set(p, theirtag, NULL);  /* forget their old tag, so we don't match tags when getting response */
16389       if (!req->ignore) {
16390          if (p->authtries < MAX_AUTHTRIES)
16391             p->invitestate = INV_CALLING;
16392          if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, SIP_INVITE, 1)) {
16393             ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
16394             p->needdestroy = 1;
16395             sip_alreadygone(p);
16396             if (p->owner)
16397                ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
16398          }
16399       }
16400       break;
16401 
16402    case 403: /* Forbidden */
16403       /* First we ACK */
16404       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
16405       ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
16406       if (!req->ignore && p->owner)
16407          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
16408       p->needdestroy = 1;
16409       sip_alreadygone(p);
16410       break;
16411 
16412    case 404: /* Not found */
16413       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
16414       if (p->owner && !req->ignore)
16415          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
16416       sip_alreadygone(p);
16417       break;
16418 
16419    case 408: /* Request timeout */
16420    case 481: /* Call leg does not exist */
16421       /* Could be REFER caused INVITE with replaces */
16422       ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
16423       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
16424       if (p->owner)
16425          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
16426       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16427       break;
16428 
16429    case 422: /* Session-Timers: Session interval too small */
16430       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
16431       ast_string_field_set(p, theirtag, NULL);
16432       proc_422_rsp(p, req);
16433       break;
16434 
16435    case 487: /* Cancelled transaction */
16436       /* We have sent CANCEL on an outbound INVITE 
16437          This transaction is already scheduled to be killed by sip_hangup().
16438       */
16439       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
16440       if (p->owner && !req->ignore) {
16441          ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_CLEARING);
16442          append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
16443       } else if (!req->ignore) {
16444          update_call_counter(p, DEC_CALL_LIMIT);
16445          append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
16446          p->needdestroy = 1;
16447          sip_alreadygone(p);
16448       }
16449       break;
16450    case 488: /* Not acceptable here */
16451       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
16452       if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
16453          change_t38_state(p, T38_DISABLED);
16454          /* Try to reset RTP timers */
16455          ast_rtp_set_rtptimers_onhold(p->rtp);
16456 
16457          /* Trigger a reinvite back to audio */
16458          transmit_reinvite_with_sdp(p, FALSE, FALSE);
16459       } else {
16460          /* We can't set up this call, so give up */
16461          if (p->owner && !req->ignore)
16462             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
16463          p->needdestroy = 1;
16464          /* If there's no dialog to end, then mark p as already gone */
16465          if (!reinvite)
16466             sip_alreadygone(p);
16467       }
16468       break;
16469    case 491: /* Pending */
16470       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
16471       if (p->owner && !req->ignore) {
16472          if (p->owner->_state != AST_STATE_UP) {
16473             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
16474             p->needdestroy = 1;
16475          } else {
16476             /* This is a re-invite that failed. */
16477             /* Reset the flag after a while 
16478              */
16479             int wait;
16480             /* RFC 3261, if owner of call, wait between 2.1 to 4 seconds,
16481              * if not owner of call, wait 0 to 2 seconds */
16482             if (p->outgoing_call) {
16483                wait = 2100 + ast_random() % 2000;
16484             } else {
16485                wait = ast_random() % 2000;
16486             }
16487             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."));
16488             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);
16489             ast_debug(2, "Reinvite race. Waiting %d secs before retry\n", wait);
16490          }
16491       }
16492       break;
16493 
16494    case 501: /* Not implemented */
16495       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
16496       if (p->owner)
16497          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
16498       break;
16499    }
16500    if (xmitres == XMIT_ERROR)
16501       ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
16502 }
16503 
16504 /* \brief Handle SIP response in NOTIFY transaction
16505        We've sent a NOTIFY, now handle responses to it
16506   */
16507 static void handle_response_notify(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
16508 {
16509    switch (resp) {
16510    case 200:   /* Notify accepted */
16511       /* They got the notify, this is the end */
16512       if (p->owner) {
16513          if (!p->refer) {
16514             ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
16515             ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_UNSPECIFIED);
16516          } else {
16517             ast_debug(4, "Got OK on REFER Notify message\n");
16518          }
16519       } else {
16520          if (p->subscribed == NONE) {
16521             ast_debug(4, "Got 200 accepted on NOTIFY\n");
16522             p->needdestroy = 1;
16523          }
16524          if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
16525             /* Ready to send the next state we have on queue */
16526             ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
16527             cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
16528          }
16529       }
16530       break;
16531    case 401:   /* Not www-authorized on SIP method */
16532    case 407:   /* Proxy auth */
16533       if (!p->notify_headers) {
16534          break; /* Only device notify can use NOTIFY auth */
16535       }
16536       ast_string_field_set(p, theirtag, NULL);
16537       if (ast_strlen_zero(p->authname)) {
16538          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));
16539          p->needdestroy = 1;
16540       }
16541       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_NOTIFY, 0)) {
16542          ast_log(LOG_NOTICE, "Failed to authenticate on NOTYFY to '%s'\n", get_header(&p->initreq, "From"));
16543          p->needdestroy = 1;
16544       }
16545       break;
16546    }
16547 }
16548 
16549 /* \brief Handle SIP response in REFER transaction
16550    We've sent a REFER, now handle responses to it 
16551   */
16552 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
16553 {
16554    /* If no refer structure exists, then do nothing */
16555    if (!p->refer)
16556       return;
16557 
16558    switch (resp) {
16559    case 202:   /* Transfer accepted */
16560       /* We need  to do something here */
16561       /* The transferee is now sending INVITE to target */
16562       p->refer->status = REFER_ACCEPTED;
16563       /* Now wait for next message */
16564       ast_debug(3, "Got 202 accepted on transfer\n");
16565       /* We should hang along, waiting for NOTIFY's here */
16566       break;
16567 
16568    case 401:   /* Not www-authorized on SIP method */
16569    case 407:   /* Proxy auth */
16570       if (ast_strlen_zero(p->authname)) {
16571          ast_log(LOG_WARNING, "Asked to authenticate REFER to %s:%d but we have no matching peer or realm auth!\n",
16572             ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
16573          p->needdestroy = 1;
16574       }
16575       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_REFER, 0)) {
16576          ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
16577          p->refer->status = REFER_NOAUTH;
16578          p->needdestroy = 1;
16579       }
16580       break;
16581    case 481: /* Call leg does not exist */
16582 
16583       /* A transfer with Replaces did not work */
16584       /* OEJ: We should Set flag, cancel the REFER, go back
16585       to original call - but right now we can't */
16586       ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
16587       if (p->owner)
16588          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
16589       p->needdestroy = 1;
16590       break;
16591 
16592    case 500:   /* Server error */
16593    case 501:   /* Method not implemented */
16594       /* Return to the current call onhold */
16595       /* Status flag needed to be reset */
16596       ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
16597       p->needdestroy = 1;
16598       p->refer->status = REFER_FAILED;
16599       break;
16600    case 603:   /* Transfer declined */
16601       ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
16602       p->refer->status = REFER_FAILED;
16603       p->needdestroy = 1;
16604       break;
16605    }
16606 }
16607 
16608 /*! \brief Handle responses on REGISTER to services */
16609 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
16610 {
16611    int expires, expires_ms;
16612    struct sip_registry *r;
16613    r=p->registry;
16614    
16615    switch (resp) {
16616    case 401:   /* Unauthorized */
16617       if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
16618          ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
16619          p->needdestroy = 1;
16620       }
16621       break;
16622    case 403:   /* Forbidden */
16623       ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
16624       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 403"));
16625       r->regstate = REG_STATE_NOAUTH;
16626       p->needdestroy = 1;
16627       break;
16628    case 404:   /* Not found */
16629       ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username, p->registry->hostname);
16630       p->needdestroy = 1;
16631       if (r->call)
16632          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 404");
16633       r->regstate = REG_STATE_REJECTED;
16634       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 404"));
16635       break;
16636    case 407:   /* Proxy auth */
16637       if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
16638          ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
16639          p->needdestroy = 1;
16640       }
16641       break;
16642    case 408:   /* Request timeout */
16643       /* Got a timeout response, so reset the counter of failed responses */
16644       if (r) {
16645          r->regattempts = 0;
16646       } else {
16647          ast_log(LOG_WARNING, "Got a 408 response to our REGISTER on call %s after we had destroyed the registry object\n", p->callid);
16648       }
16649       break;
16650    case 423:   /* Interval too brief */
16651       r->expiry = atoi(get_header(req, "Min-Expires"));
16652       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);
16653       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 423"));
16654       if (r->call) {
16655          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 423");
16656          p->needdestroy = 1;
16657       }
16658       if (r->expiry > max_expiry) {
16659          ast_log(LOG_WARNING, "Required expiration time from %s@%s is too high, giving up\n", p->registry->username, p->registry->hostname);
16660          r->expiry = default_expiry;
16661          r->regstate = REG_STATE_REJECTED;
16662       } else {
16663          r->regstate = REG_STATE_UNREGISTERED;
16664          transmit_register(r, SIP_REGISTER, NULL, NULL);
16665       }
16666       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));
16667       break;
16668    case 479:   /* SER: Not able to process the URI - address is wrong in register*/
16669       ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username, p->registry->hostname);
16670       p->needdestroy = 1;
16671       if (r->call)
16672          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 479");
16673       r->regstate = REG_STATE_REJECTED;
16674       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 479"));
16675       break;
16676    case 200:   /* 200 OK */
16677       if (!r) {
16678          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));
16679          p->needdestroy = 1;
16680          return 0;
16681       }
16682       
16683       r->regstate = REG_STATE_REGISTERED;
16684       r->regtime = ast_tvnow();     /* Reset time of last succesful registration */
16685       manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
16686       r->regattempts = 0;
16687       ast_debug(1, "Registration successful\n");
16688       if (r->timeout > -1) {
16689          ast_debug(1, "Cancelling timeout %d\n", r->timeout);
16690       }
16691       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 200"));
16692       if (r->call)
16693          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 200");
16694       p->registry = registry_unref(p->registry, "unref registry entry p->registry");
16695       /* Let this one hang around until we have all the responses */
16696       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16697       /* p->needdestroy = 1; */
16698       
16699       /* set us up for re-registering
16700        * figure out how long we got registered for
16701        * according to section 6.13 of RFC, contact headers override
16702        * expires headers, so check those first */
16703       expires = 0;
16704 
16705       /* XXX todo: try to save the extra call */
16706       if (!ast_strlen_zero(get_header(req, "Contact"))) {
16707          const char *contact = NULL;
16708          const char *tmptmp = NULL;
16709          int start = 0;
16710          for(;;) {
16711             contact = __get_header(req, "Contact", &start);
16712             /* this loop ensures we get a contact header about our register request */
16713             if(!ast_strlen_zero(contact)) {
16714                if( (tmptmp=strstr(contact, p->our_contact))) {
16715                   contact=tmptmp;
16716                   break;
16717                }
16718             } else
16719                break;
16720          }
16721          tmptmp = strcasestr(contact, "expires=");
16722          if (tmptmp) {
16723             if (sscanf(tmptmp + 8, "%30d;", &expires) != 1)
16724                expires = 0;
16725          }
16726          
16727       }
16728       if (!expires) 
16729          expires=atoi(get_header(req, "expires"));
16730       if (!expires)
16731          expires=default_expiry;
16732       
16733       expires_ms = expires * 1000;
16734       if (expires <= EXPIRY_GUARD_LIMIT)
16735          expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT), EXPIRY_GUARD_MIN);
16736       else
16737          expires_ms -= EXPIRY_GUARD_SECS * 1000;
16738       if (sipdebug)
16739          ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000); 
16740       
16741       r->refresh= (int) expires_ms / 1000;
16742       
16743       /* Schedule re-registration before we expire */
16744       AST_SCHED_REPLACE_UNREF(r->expire, sched, expires_ms, sip_reregister, r, 
16745                         registry_unref(_data,"unref in REPLACE del fail"), 
16746                         registry_unref(r,"unref in REPLACE add fail"), 
16747                         registry_addref(r,"The Addition side of REPLACE")); 
16748    }
16749    return 1;
16750 }
16751 
16752 /*! \brief Handle qualification responses (OPTIONS) */
16753 static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
16754 {
16755    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! */
16756    int statechanged, is_reachable, was_reachable;
16757    int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
16758 
16759    /*
16760     * Compute the response time to a ping (goes in peer->lastms.)
16761     * -1 means did not respond, 0 means unknown,
16762     * 1..maxms is a valid response, >maxms means late response.
16763     */
16764    if (pingtime < 1) /* zero = unknown, so round up to 1 */
16765       pingtime = 1;
16766 
16767    /* Now determine new state and whether it has changed.
16768     * Use some helper variables to simplify the writing
16769     * of the expressions.
16770     */
16771    was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
16772    is_reachable = pingtime <= peer->maxms;
16773    statechanged = peer->lastms == 0 /* yes, unknown before */
16774       || was_reachable != is_reachable;
16775 
16776    peer->lastms = pingtime;
16777    peer->call = dialog_unref(peer->call, "unref dialog peer->call");
16778    if (statechanged) {
16779       const char *s = is_reachable ? "Reachable" : "Lagged";
16780       char str_lastms[20];
16781       snprintf(str_lastms, sizeof(str_lastms), "%d", pingtime);
16782 
16783       ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
16784          peer->name, s, pingtime, peer->maxms);
16785       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
16786       if (sip_cfg.peer_rtupdate) {
16787          ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", str_lastms, SENTINEL);
16788       }
16789       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
16790          "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
16791          peer->name, s, pingtime);
16792       if (is_reachable && global_regextenonqualify)
16793          register_peer_exten(peer, TRUE);
16794    }
16795 
16796    p->needdestroy = 1;
16797 
16798    /* Try again eventually */
16799    AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
16800          is_reachable ? peer->qualifyfreq : DEFAULT_FREQ_NOTOK,
16801          sip_poke_peer_s, peer,
16802          unref_peer(_data, "removing poke peer ref"),
16803          unref_peer(peer, "removing poke peer ref"),
16804          ref_peer(peer, "adding poke peer ref"));
16805 }
16806 
16807 /*! \brief Immediately stop RTP, VRTP and UDPTL as applicable */
16808 static void stop_media_flows(struct sip_pvt *p)
16809 {
16810    /* Immediately stop RTP, VRTP and UDPTL as applicable */
16811    if (p->rtp)
16812       ast_rtp_stop(p->rtp);
16813    if (p->vrtp)
16814       ast_rtp_stop(p->vrtp);
16815    if (p->trtp)
16816       ast_rtp_stop(p->trtp);
16817    if (p->udptl)
16818       ast_udptl_stop(p->udptl);
16819 }
16820 
16821 /*! \brief Handle SIP response in dialogue
16822    \note only called by handle_incoming */
16823 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
16824 {
16825    struct ast_channel *owner;
16826    int sipmethod;
16827    int res = 1;
16828    int ack_res;
16829    const char *c = get_header(req, "Cseq");
16830    /* 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 */
16831    char *c_copy = ast_strdupa(c);
16832    /* Skip the Cseq and its subsequent spaces */
16833    const char *msg = ast_skip_blanks(ast_skip_nonblanks(c_copy));
16834 
16835    if (!msg)
16836       msg = "";
16837 
16838    sipmethod = find_sip_method(msg);
16839 
16840    owner = p->owner;
16841    if (owner) 
16842       owner->hangupcause = hangup_sip2cause(resp);
16843 
16844    /* Acknowledge whatever it is destined for */
16845    if ((resp >= 100) && (resp <= 199)) {
16846       ack_res = __sip_semi_ack(p, seqno, 0, sipmethod);
16847    } else {
16848       ack_res = __sip_ack(p, seqno, 0, sipmethod);
16849    }
16850 
16851    if (ack_res == FALSE) {
16852       append_history(p, "Ignore", "Ignoring this retransmit\n");
16853       return;
16854    }
16855 
16856    /* If this is a NOTIFY for a subscription clear the flag that indicates that we have a NOTIFY pending */
16857    if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite) 
16858       p->pendinginvite = 0;
16859 
16860    /* Get their tag if we haven't already */
16861    if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
16862       char tag[128];
16863 
16864       gettag(req, "To", tag, sizeof(tag));
16865       ast_string_field_set(p, theirtag, tag);
16866    }
16867    /* This needs to be configurable on a channel/peer level,
16868       not mandatory for all communication. Sadly enough, NAT implementations
16869       are not so stable so we can always rely on these headers. 
16870       Temporarily disabled, while waiting for fix.
16871       Fix assigned to Rizzo :-)
16872    */
16873    /* check_via_response(p, req); */
16874 
16875    /* RFC 3261 Section 15 specifies that if we receive a 408 or 481
16876     * in response to a BYE, then we should end the current dialog
16877     * and session.  It is known that at least one phone manufacturer
16878     * potentially will send a 404 in response to a BYE, so we'll be
16879     * liberal in what we accept and end the dialog and session if we
16880     * receive any of those responses to a BYE.
16881     */
16882    if ((resp == 404 || resp == 408 || resp == 481) && sipmethod == SIP_BYE) {
16883       p->needdestroy = 1;
16884       return;
16885    }
16886 
16887    if (p->relatedpeer && p->method == SIP_OPTIONS) {
16888       /* We don't really care what the response is, just that it replied back. 
16889          Well, as long as it's not a 100 response...  since we might
16890          need to hang around for something more "definitive" */
16891       if (resp != 100)
16892          handle_response_peerpoke(p, resp, req);
16893    } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
16894       switch(resp) {
16895       case 100:   /* 100 Trying */
16896       case 101:   /* 101 Dialog establishment */
16897          if (sipmethod == SIP_INVITE) 
16898             handle_response_invite(p, resp, rest, req, seqno);
16899          break;
16900       case 183:   /* 183 Session Progress */
16901          if (sipmethod == SIP_INVITE) 
16902             handle_response_invite(p, resp, rest, req, seqno);
16903          break;
16904       case 180:   /* 180 Ringing */
16905          if (sipmethod == SIP_INVITE) 
16906             handle_response_invite(p, resp, rest, req, seqno);
16907          break;
16908       case 182:       /* 182 Queued */
16909          if (sipmethod == SIP_INVITE)
16910             handle_response_invite(p, resp, rest, req, seqno);
16911          break;
16912       case 200:   /* 200 OK */
16913          p->authtries = 0; /* Reset authentication counter */
16914          if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
16915             /* We successfully transmitted a message 
16916                or a video update request in INFO */
16917             /* Nothing happens here - the message is inside a dialog */
16918          } else if (sipmethod == SIP_INVITE) {
16919             handle_response_invite(p, resp, rest, req, seqno);
16920          } else if (sipmethod == SIP_NOTIFY) {
16921             handle_response_notify(p, resp, rest, req, seqno);
16922          } else if (sipmethod == SIP_REGISTER) 
16923             res = handle_response_register(p, resp, rest, req, seqno);
16924          else if (sipmethod == SIP_BYE) {    /* Ok, we're ready to go */
16925             p->needdestroy = 1;
16926             ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
16927          } else if (sipmethod == SIP_SUBSCRIBE) {
16928             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
16929          }
16930          break;
16931       case 202:   /* Transfer accepted */
16932          if (sipmethod == SIP_REFER) 
16933             handle_response_refer(p, resp, rest, req, seqno);
16934          break;
16935       case 401: /* Not www-authorized on SIP method */
16936       case 407: /* Proxy auth required */
16937          if (sipmethod == SIP_INVITE)
16938             handle_response_invite(p, resp, rest, req, seqno);
16939          else if (sipmethod == SIP_NOTIFY)
16940             handle_response_notify(p, resp, rest, req, seqno);
16941          else if (sipmethod == SIP_REFER)
16942             handle_response_refer(p, resp, rest, req, seqno);
16943          else if (p->registry && sipmethod == SIP_REGISTER)
16944             res = handle_response_register(p, resp, rest, req, seqno);
16945          else if (sipmethod == SIP_BYE) {
16946             if (p->options)
16947                p->options->auth_type = resp;
16948             if (ast_strlen_zero(p->authname)) {
16949                ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
16950                      msg, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
16951                p->needdestroy = 1;
16952             } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp,  sipmethod, 0)) {
16953                ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
16954                p->needdestroy = 1;
16955             }
16956          } else {
16957             ast_log(LOG_WARNING, "Got authentication request (%d) on %s to '%s'\n", resp, sip_methods[sipmethod].text, get_header(req, "To"));
16958             p->needdestroy = 1;
16959          }
16960          break;
16961       case 403: /* Forbidden - we failed authentication */
16962          if (sipmethod == SIP_INVITE)
16963             handle_response_invite(p, resp, rest, req, seqno);
16964          else if (p->registry && sipmethod == SIP_REGISTER) 
16965             res = handle_response_register(p, resp, rest, req, seqno);
16966          else {
16967             ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
16968             p->needdestroy = 1;
16969          }
16970          break;
16971       case 404: /* Not found */
16972          if (p->registry && sipmethod == SIP_REGISTER)
16973             res = handle_response_register(p, resp, rest, req, seqno);
16974          else if (sipmethod == SIP_INVITE)
16975             handle_response_invite(p, resp, rest, req, seqno);
16976          else if (owner)
16977             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
16978          break;
16979       case 423: /* Interval too brief */
16980          if (sipmethod == SIP_REGISTER)
16981             res = handle_response_register(p, resp, rest, req, seqno);
16982          break;
16983       case 408: /* Request timeout - terminate dialog */
16984          if (sipmethod == SIP_INVITE)
16985             handle_response_invite(p, resp, rest, req, seqno);
16986          else if (sipmethod == SIP_REGISTER) 
16987             res = handle_response_register(p, resp, rest, req, seqno);
16988          else if (sipmethod == SIP_BYE) {
16989             p->needdestroy = 1;
16990             ast_debug(4, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
16991          } else {
16992             if (owner)
16993                ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
16994             p->needdestroy = 1;
16995          }
16996          break;
16997 
16998       case 422: /* Session-Timers: Session Interval Too Small */
16999          if (sipmethod == SIP_INVITE) {
17000             handle_response_invite(p, resp, rest, req, seqno);
17001          }
17002          break;
17003 
17004       case 481: /* Call leg does not exist */
17005          if (sipmethod == SIP_INVITE) {
17006             handle_response_invite(p, resp, rest, req, seqno);
17007          } else if (sipmethod == SIP_REFER) {
17008             handle_response_refer(p, resp, rest, req, seqno);
17009          } else if (sipmethod == SIP_BYE) {
17010             /* The other side has no transaction to bye,
17011             just assume it's all right then */
17012             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
17013          } else if (sipmethod == SIP_CANCEL) {
17014             /* The other side has no transaction to cancel,
17015             just assume it's all right then */
17016             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
17017          } else {
17018             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
17019             /* Guessing that this is not an important request */
17020          }
17021          break;
17022       case 487:
17023          if (sipmethod == SIP_INVITE)
17024             handle_response_invite(p, resp, rest, req, seqno);
17025          break;
17026       case 488: /* Not acceptable here - codec error */
17027          if (sipmethod == SIP_INVITE)
17028             handle_response_invite(p, resp, rest, req, seqno);
17029          break;
17030       case 491: /* Pending */
17031          if (sipmethod == SIP_INVITE)
17032             handle_response_invite(p, resp, rest, req, seqno);
17033          else {
17034             ast_debug(1, "Got 491 on %s, unspported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
17035             p->needdestroy = 1;
17036          }
17037          break;
17038       case 501: /* Not Implemented */
17039          if (sipmethod == SIP_INVITE)
17040             handle_response_invite(p, resp, rest, req, seqno);
17041          else if (sipmethod == SIP_REFER)
17042             handle_response_refer(p, resp, rest, req, seqno);
17043          else
17044             ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_inet_ntoa(p->sa.sin_addr), msg);
17045          break;
17046       case 603:   /* Declined transfer */
17047          if (sipmethod == SIP_REFER) {
17048             handle_response_refer(p, resp, rest, req, seqno);
17049             break;
17050          }
17051          /* Fallthrough */
17052       default:
17053          if ((resp >= 300) && (resp < 700)) {
17054             /* Fatal response */
17055             if ((resp != 487))
17056                ast_verb(3, "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
17057    
17058             if (sipmethod == SIP_INVITE)
17059                stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
17060 
17061             /* XXX Locking issues?? XXX */
17062             switch(resp) {
17063             case 300: /* Multiple Choices */
17064             case 301: /* Moved permanently */
17065             case 302: /* Moved temporarily */
17066             case 305: /* Use Proxy */
17067                parse_moved_contact(p, req);
17068                /* Fall through */
17069             case 486: /* Busy here */
17070             case 600: /* Busy everywhere */
17071             case 603: /* Decline */
17072                if (p->owner)
17073                   ast_queue_control(p->owner, AST_CONTROL_BUSY);
17074                break;
17075             case 482: /*!
17076                \note SIP is incapable of performing a hairpin call, which
17077                is yet another failure of not having a layer 2 (again, YAY
17078                 IETF for thinking ahead).  So we treat this as a call
17079                 forward and hope we end up at the right place... */
17080                ast_debug(1, "Hairpin detected, setting up call forward for what it's worth\n");
17081                if (p->owner)
17082                   ast_string_field_build(p->owner, call_forward,
17083                                "Local/%s@%s", p->username, p->context);
17084                /* Fall through */
17085             case 480: /* Temporarily Unavailable */
17086             case 404: /* Not Found */
17087             case 410: /* Gone */
17088             case 400: /* Bad Request */
17089             case 500: /* Server error */
17090                if (sipmethod == SIP_REFER) {
17091                   handle_response_refer(p, resp, rest, req, seqno);
17092                   break;
17093                }
17094                /* Fall through */
17095             case 502: /* Bad gateway */
17096             case 503: /* Service Unavailable */
17097             case 504: /* Server Timeout */
17098                if (owner)
17099                   ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17100                break;
17101             default:
17102                /* Send hangup */ 
17103                if (owner && sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO && sipmethod != SIP_BYE)
17104                   ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
17105                break;
17106             }
17107             /* ACK on invite */
17108             if (sipmethod == SIP_INVITE) 
17109                transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17110             if (sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO) 
17111                sip_alreadygone(p);
17112             if (!p->owner)
17113                p->needdestroy = 1;
17114          } else if ((resp >= 100) && (resp < 200)) {
17115             if (sipmethod == SIP_INVITE) {
17116                if (!req->ignore && sip_cancel_destroy(p))
17117                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
17118                if (find_sdp(req))
17119                   process_sdp(p, req, SDP_T38_NONE);
17120                if (p->owner) {
17121                   /* Queue a progress frame */
17122                   ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
17123                }
17124             }
17125          } else
17126             ast_log(LOG_NOTICE, "Dont know how to handle a %d %s response from %s\n", resp, rest, p->owner ? p->owner->name : ast_inet_ntoa(p->sa.sin_addr));
17127       }
17128    } else { 
17129       /* Responses to OUTGOING SIP requests on INCOMING calls 
17130          get handled here. As well as out-of-call message responses */
17131       if (req->debug)
17132          ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
17133 
17134       if (sipmethod == SIP_INVITE && resp == 200) {
17135          /* Tags in early session is replaced by the tag in 200 OK, which is 
17136          the final reply to our INVITE */
17137          char tag[128];
17138 
17139          gettag(req, "To", tag, sizeof(tag));
17140          ast_string_field_set(p, theirtag, tag);
17141       }
17142 
17143       switch(resp) {
17144       case 200:
17145          if (sipmethod == SIP_INVITE) {
17146             handle_response_invite(p, resp, rest, req, seqno);
17147          } else if (sipmethod == SIP_CANCEL) {
17148             ast_debug(1, "Got 200 OK on CANCEL\n");
17149 
17150             /* Wait for 487, then destroy */
17151          } else if (sipmethod == SIP_NOTIFY) {
17152             /* They got the notify, this is the end */
17153             if (p->owner) {
17154                if (p->refer) {
17155                   ast_debug(1, "Got 200 OK on NOTIFY for transfer\n");
17156                } else
17157                   ast_log(LOG_WARNING, "Notify answer on an owned channel?\n");
17158                /* ast_queue_hangup(p->owner); Disabled */
17159             } else {
17160                if (!p->subscribed && !p->refer)
17161                   p->needdestroy = 1;
17162                if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
17163                   /* Ready to send the next state we have on queue */
17164                   ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
17165                   cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
17166                }
17167             }
17168          } else if (sipmethod == SIP_BYE)
17169             p->needdestroy = 1;
17170          else if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO)
17171             /* We successfully transmitted a message or
17172                a video update request in INFO */
17173             ;
17174          else if (sipmethod == SIP_BYE) 
17175             /* Ok, we're ready to go */
17176             p->needdestroy = 1;
17177          break;
17178       case 202:   /* Transfer accepted */
17179          if (sipmethod == SIP_REFER) 
17180             handle_response_refer(p, resp, rest, req, seqno);
17181          break;
17182       case 401:   /* www-auth */
17183       case 407:
17184          if (sipmethod == SIP_REFER)
17185             handle_response_refer(p, resp, rest, req, seqno);
17186          else if (sipmethod == SIP_INVITE) 
17187             handle_response_invite(p, resp, rest, req, seqno);
17188          else if (sipmethod == SIP_BYE) {
17189             if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, sipmethod, 0)) {
17190                ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
17191                p->needdestroy = 1;
17192             }
17193          }
17194          break;
17195       case 481:   /* Call leg does not exist */
17196          if (sipmethod == SIP_INVITE) {
17197             /* Re-invite failed */
17198             handle_response_invite(p, resp, rest, req, seqno);
17199          } else if (sipmethod == SIP_BYE) {
17200             p->needdestroy = 1;
17201          } else if (sipdebug) {
17202             ast_debug(1, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
17203          }
17204          break;
17205       case 501: /* Not Implemented */
17206          if (sipmethod == SIP_INVITE) 
17207             handle_response_invite(p, resp, rest, req, seqno);
17208          else if (sipmethod == SIP_REFER) 
17209             handle_response_refer(p, resp, rest, req, seqno);
17210          break;
17211       case 603:   /* Declined transfer */
17212          if (sipmethod == SIP_REFER) {
17213             handle_response_refer(p, resp, rest, req, seqno);
17214             break;
17215          }
17216          /* Fallthrough */
17217       default: /* Errors without handlers */
17218          if ((resp >= 100) && (resp < 200)) {
17219             if (sipmethod == SIP_INVITE) {   /* re-invite */
17220                if (!req->ignore && sip_cancel_destroy(p))
17221                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
17222             }
17223          }
17224          if ((resp >= 300) && (resp < 700)) {
17225             if ((resp != 487))
17226                ast_verb(3, "Incoming call: Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
17227             switch(resp) {
17228             case 488: /* Not acceptable here - codec error */
17229             case 603: /* Decline */
17230             case 500: /* Server error */
17231             case 502: /* Bad gateway */
17232             case 503: /* Service Unavailable */
17233             case 504: /* Server timeout */
17234 
17235                /* re-invite failed */
17236                if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
17237                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
17238                break;
17239             }
17240          }
17241          break;
17242       }
17243    }
17244 }
17245 
17246 
17247 /*! \brief Park SIP call support function 
17248    Starts in a new thread, then parks the call
17249    XXX Should we add a wait period after streaming audio and before hangup?? Sometimes the
17250       audio can't be heard before hangup
17251 */
17252 static void *sip_park_thread(void *stuff)
17253 {
17254    struct ast_channel *transferee, *transferer; /* Chan1: The transferee, Chan2: The transferer */
17255    struct sip_dual *d;
17256    struct sip_request req = {0,};
17257    int ext;
17258    int res;
17259 
17260    d = stuff;
17261    transferee = d->chan1;
17262    transferer = d->chan2;
17263    copy_request(&req, &d->req);
17264 
17265    if (!transferee || !transferer) {
17266       ast_log(LOG_ERROR, "Missing channels for parking! Transferer %s Transferee %s\n", transferer ? "<available>" : "<missing>", transferee ? "<available>" : "<missing>" );
17267       if (d->req.data)
17268          ast_free(d->req.data);
17269       free(d);
17270       return NULL;
17271    }
17272    ast_debug(4, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);
17273 
17274    ast_channel_lock(transferee);
17275    if (ast_do_masquerade(transferee)) {
17276       ast_log(LOG_WARNING, "Masquerade failed.\n");
17277       transmit_response(transferer->tech_pvt, "503 Internal error", &req);
17278       ast_channel_unlock(transferee);
17279       if (d->req.data)
17280          ast_free(d->req.data);
17281       free(d);
17282       return NULL;
17283    } 
17284    ast_channel_unlock(transferee);
17285 
17286    res = ast_park_call(transferee, transferer, 0, &ext);
17287    
17288 
17289 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
17290    if (!res) {
17291       transmit_message_with_text(transferer->tech_pvt, "Unable to park call.\n");
17292    } else {
17293       /* Then tell the transferer what happened */
17294       sprintf(buf, "Call parked on extension '%d'", ext);
17295       transmit_message_with_text(transferer->tech_pvt, buf);
17296    }
17297 #endif
17298 
17299    /* Any way back to the current call??? */
17300    /* Transmit response to the REFER request */
17301    transmit_response(transferer->tech_pvt, "202 Accepted", &req);
17302    if (!res)   {
17303       /* Transfer succeeded */
17304       append_history(transferer->tech_pvt, "SIPpark", "Parked call on %d", ext);
17305       transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "200 OK", TRUE);
17306       transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
17307       ast_hangup(transferer); /* This will cause a BYE */
17308       ast_debug(1, "SIP Call parked on extension '%d'\n", ext);
17309    } else {
17310       transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "503 Service Unavailable", TRUE);
17311       append_history(transferer->tech_pvt, "SIPpark", "Parking failed\n");
17312       ast_debug(1, "SIP Call parked failed \n");
17313       /* Do not hangup call */
17314    }
17315    if (d->req.data)
17316       ast_free(d->req.data);
17317    free(d);
17318    return NULL;
17319 }
17320 
17321 /*! \brief Park a call using the subsystem in res_features.c 
17322    This is executed in a separate thread
17323 */
17324 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno)
17325 {
17326    struct sip_dual *d;
17327    struct ast_channel *transferee, *transferer;
17328       /* Chan2m: The transferer, chan1m: The transferee */
17329    pthread_t th;
17330 
17331    transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan1->accountcode, chan1->exten, chan1->context, chan1->amaflags, "Parking/%s", chan1->name);
17332    transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->amaflags, "SIPPeer/%s", chan2->name);
17333    if ((!transferer) || (!transferee)) {
17334       if (transferee) {
17335          transferee->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
17336          ast_hangup(transferee);
17337       }
17338       if (transferer) {
17339          transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
17340          ast_hangup(transferer);
17341       }
17342       return -1;
17343    }
17344 
17345    /* Make formats okay */
17346    transferee->readformat = chan1->readformat;
17347    transferee->writeformat = chan1->writeformat;
17348 
17349    /* Prepare for taking over the channel */
17350    ast_channel_masquerade(transferee, chan1);
17351 
17352    /* Setup the extensions and such */
17353    ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
17354    ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
17355    transferee->priority = chan1->priority;
17356       
17357    /* We make a clone of the peer channel too, so we can play
17358       back the announcement */
17359 
17360    /* Make formats okay */
17361    transferer->readformat = chan2->readformat;
17362    transferer->writeformat = chan2->writeformat;
17363 
17364    /* Prepare for taking over the channel.  Go ahead and grab this channel
17365     * lock here to avoid a deadlock with callbacks into the channel driver
17366     * that hold the channel lock and want the pvt lock.  */
17367    while (ast_channel_trylock(chan2)) {
17368       struct sip_pvt *pvt = chan2->tech_pvt;
17369       sip_pvt_unlock(pvt);
17370       usleep(1);
17371       sip_pvt_lock(pvt);
17372    }
17373    ast_channel_masquerade(transferer, chan2);
17374    ast_channel_unlock(chan2);
17375 
17376    /* Setup the extensions and such */
17377    ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
17378    ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
17379    transferer->priority = chan2->priority;
17380 
17381    ast_channel_lock(transferer);
17382    if (ast_do_masquerade(transferer)) {
17383       ast_log(LOG_WARNING, "Masquerade failed :(\n");
17384       ast_channel_unlock(transferer);
17385       transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
17386       ast_hangup(transferer);
17387       return -1;
17388    }
17389    ast_channel_unlock(transferer);
17390    if (!transferer || !transferee) {
17391       if (!transferer) { 
17392          ast_debug(1, "No transferer channel, giving up parking\n");
17393       }
17394       if (!transferee) {
17395          ast_debug(1, "No transferee channel, giving up parking\n");
17396       }
17397       return -1;
17398    }
17399    if ((d = ast_calloc(1, sizeof(*d)))) {
17400 
17401       /* Save original request for followup */
17402       copy_request(&d->req, req);
17403       d->chan1 = transferee;  /* Transferee */
17404       d->chan2 = transferer;  /* Transferer */
17405       d->seqno = seqno;
17406       if (ast_pthread_create_detached_background(&th, NULL, sip_park_thread, d) < 0) {
17407          /* Could not start thread */
17408          if (d->req.data)
17409             ast_free(d->req.data);
17410          ast_free(d);   /* We don't need it anymore. If thread is created, d will be free'd
17411                   by sip_park_thread() */
17412          return 0;
17413       }
17414    } 
17415    return -1;
17416 }
17417 
17418 /*! \brief Turn off generator data 
17419    XXX Does this function belong in the SIP channel?
17420 */
17421 static void ast_quiet_chan(struct ast_channel *chan) 
17422 {
17423    if (chan && chan->_state == AST_STATE_UP) {
17424       if (ast_test_flag(chan, AST_FLAG_MOH))
17425          ast_moh_stop(chan);
17426       else if (chan->generatordata)
17427          ast_deactivate_generator(chan);
17428    }
17429 }
17430 
17431 /*! \brief Attempt transfer of SIP call 
17432    This fix for attended transfers on a local PBX */
17433 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
17434 {
17435    int res = 0;
17436    struct ast_channel *peera = NULL,   
17437       *peerb = NULL,
17438       *peerc = NULL,
17439       *peerd = NULL;
17440 
17441 
17442    /* We will try to connect the transferee with the target and hangup
17443       all channels to the transferer */   
17444    ast_debug(4, "Sip transfer:--------------------\n");
17445    if (transferer->chan1)
17446       ast_debug(4, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
17447    else
17448       ast_debug(4, "-- No transferer first channel - odd??? \n");
17449    if (target->chan1)
17450       ast_debug(4, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
17451    else
17452       ast_debug(4, "-- No target first channel ---\n");
17453    if (transferer->chan2)
17454       ast_debug(4, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
17455    else
17456       ast_debug(4, "-- No bridged call to transferee\n");
17457    if (target->chan2)
17458       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)");
17459    else
17460       ast_debug(4, "-- No target second channel ---\n");
17461    ast_debug(4, "-- END Sip transfer:--------------------\n");
17462    if (transferer->chan2) { /* We have a bridge on the transferer's channel */
17463       peera = transferer->chan1; /* Transferer - PBX -> transferee channel * the one we hangup */
17464       peerb = target->chan1;     /* Transferer - PBX -> target channel - This will get lost in masq */
17465       peerc = transferer->chan2; /* Asterisk to Transferee */
17466       peerd = target->chan2;     /* Asterisk to Target */
17467       ast_debug(3, "SIP transfer: Four channels to handle\n");
17468    } else if (target->chan2) {   /* Transferer has no bridge (IVR), but transferee */
17469       peera = target->chan1;     /* Transferer to PBX -> target channel */
17470       peerb = transferer->chan1; /* Transferer to IVR*/
17471       peerc = target->chan2;     /* Asterisk to Target */
17472       peerd = transferer->chan2; /* Nothing */
17473       ast_debug(3, "SIP transfer: Three channels to handle\n");
17474    }
17475 
17476    if (peera && peerb && peerc && (peerb != peerc)) {
17477       ast_quiet_chan(peera);     /* Stop generators */
17478       ast_quiet_chan(peerb);  
17479       ast_quiet_chan(peerc);
17480       if (peerd)
17481          ast_quiet_chan(peerd);
17482 
17483       ast_debug(4, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
17484       if (ast_channel_masquerade(peerb, peerc)) {
17485          ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
17486          res = -1;
17487       } else
17488          ast_debug(4, "SIP transfer: Succeeded to masquerade channels.\n");
17489       return res;
17490    } else {
17491       ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
17492       if (transferer->chan1)
17493          ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
17494       if (target->chan1)
17495          ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
17496       return -1;
17497    }
17498    return 0;
17499 }
17500 
17501 /*! \brief Get tag from packet 
17502  *
17503  * \return Returns the pointer to the provided tag buffer,
17504  *         or NULL if the tag was not found.
17505  */
17506 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
17507 {
17508    const char *thetag;
17509 
17510    if (!tagbuf)
17511       return NULL;
17512    tagbuf[0] = '\0';    /* reset the buffer */
17513    thetag = get_header(req, header);
17514    thetag = strcasestr(thetag, ";tag=");
17515    if (thetag) {
17516       thetag += 5;
17517       ast_copy_string(tagbuf, thetag, tagbufsize);
17518       return strsep(&tagbuf, ";");
17519    }
17520    return NULL;
17521 }
17522 
17523 /*! \brief Handle incoming notifications */
17524 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
17525 {
17526    /* This is mostly a skeleton for future improvements */
17527    /* Mostly created to return proper answers on notifications on outbound REFER's */
17528    int res = 0;
17529    const char *event = get_header(req, "Event");
17530    char *eventid = NULL;
17531    char *sep;
17532 
17533    if( (sep = strchr(event, ';')) ) {  /* XXX bug here - overwriting string ? */
17534       *sep++ = '\0';
17535       eventid = sep;
17536    }
17537    
17538    if (sipdebug)
17539       ast_debug(2, "Got NOTIFY Event: %s\n", event);
17540 
17541    if (strcmp(event, "refer")) {
17542       /* We don't understand this event. */
17543       /* Here's room to implement incoming voicemail notifications :-) */
17544       transmit_response(p, "489 Bad event", req);
17545       res = -1;
17546    } else {
17547       /* Save nesting depth for now, since there might be other events we will
17548          support in the future */
17549 
17550       /* Handle REFER notifications */
17551 
17552       char buf[1024];
17553       char *cmd, *code;
17554       int respcode;
17555       int success = TRUE;
17556 
17557       /* EventID for each transfer... EventID is basically the REFER cseq 
17558 
17559        We are getting notifications on a call that we transfered
17560        We should hangup when we are getting a 200 OK in a sipfrag
17561        Check if we have an owner of this event */
17562       
17563       /* Check the content type */
17564       if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
17565          /* We need a sipfrag */
17566          transmit_response(p, "400 Bad request", req);
17567          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17568          return -1;
17569       }
17570 
17571       /* Get the text of the attachment */
17572       if (get_msg_text(buf, sizeof(buf), req, TRUE)) {
17573          ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
17574          transmit_response(p, "400 Bad request", req);
17575          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17576          return -1;
17577       }
17578 
17579       /*
17580       From the RFC...
17581       A minimal, but complete, implementation can respond with a single
17582       NOTIFY containing either the body:
17583          SIP/2.0 100 Trying
17584       
17585       if the subscription is pending, the body:
17586          SIP/2.0 200 OK
17587       if the reference was successful, the body:
17588          SIP/2.0 503 Service Unavailable
17589       if the reference failed, or the body:
17590          SIP/2.0 603 Declined
17591 
17592       if the REFER request was accepted before approval to follow the
17593       reference could be obtained and that approval was subsequently denied
17594       (see Section 2.4.7).
17595       
17596       If there are several REFERs in the same dialog, we need to
17597       match the ID of the event header...
17598       */
17599       ast_debug(3, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
17600       cmd = ast_skip_blanks(buf);
17601       code = cmd;
17602       /* We are at SIP/2.0 */
17603       while(*code && (*code > 32)) {   /* Search white space */
17604          code++;
17605       }
17606       *code++ = '\0';
17607       code = ast_skip_blanks(code);
17608       sep = code;
17609       sep++;
17610       while(*sep && (*sep > 32)) {  /* Search white space */
17611          sep++;
17612       }
17613       *sep++ = '\0';       /* Response string */
17614       respcode = atoi(code);
17615       switch (respcode) {
17616       case 100:   /* Trying: */
17617       case 101:   /* dialog establishment */
17618          /* Don't do anything yet */
17619          break;
17620       case 183:   /* Ringing: */
17621          /* Don't do anything yet */
17622          break;
17623       case 200:   /* OK: The new call is up, hangup this call */
17624          /* Hangup the call that we are replacing */
17625          break;
17626       case 301: /* Moved permenantly */
17627       case 302: /* Moved temporarily */
17628          /* Do we get the header in the packet in this case? */
17629          success = FALSE;
17630          break;
17631       case 503:   /* Service Unavailable: The new call failed */
17632             /* Cancel transfer, continue the call */
17633          success = FALSE;
17634          break;
17635       case 603:   /* Declined: Not accepted */
17636             /* Cancel transfer, continue the current call */
17637          success = FALSE;
17638          break;
17639       }
17640       if (!success) {
17641          ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
17642       }
17643       
17644       /* Confirm that we received this packet */
17645       transmit_response(p, "200 OK", req);
17646    };
17647 
17648    if (!p->lastinvite)
17649       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17650 
17651    return res;
17652 }
17653 
17654 /*! \brief Handle incoming OPTIONS request 
17655    An OPTIONS request should be answered like an INVITE from the same UA, including SDP
17656 */
17657 static int handle_request_options(struct sip_pvt *p, struct sip_request *req)
17658 {
17659    int res;
17660 
17661    /*! XXX get_destination assumes we're already authenticated. This means that a request from
17662       a known device (peer) will end up in the wrong context if this is out-of-dialog.
17663       However, we want to handle OPTIONS as light as possible, so we might want to have
17664       a configuration option whether we care or not. Some devices use this for testing
17665       capabilities, which means that we need to match device to answer with proper 
17666       capabilities (including SDP).
17667       \todo Fix handle_request_options device handling with optional authentication
17668          (this needs to be fixed in 1.4 as well)
17669    */
17670 
17671    if (p->lastinvite) {
17672       /* if this is a request in an active dialog, just confirm that the dialog exists. */
17673       transmit_response_with_allow(p, "200 OK", req, 0);
17674       return 0;
17675    }
17676 
17677    res = get_destination(p, req);
17678    build_contact(p);
17679 
17680    if (ast_strlen_zero(p->context))
17681       ast_string_field_set(p, context, default_context);
17682 
17683    if (ast_shutting_down())
17684       transmit_response_with_allow(p, "503 Unavailable", req, 0);
17685    else if (res < 0)
17686       transmit_response_with_allow(p, "404 Not Found", req, 0);
17687    else 
17688       transmit_response_with_allow(p, "200 OK", req, 0);
17689 
17690    /* Destroy if this OPTIONS was the opening request, but not if
17691       it's in the middle of a normal call flow. */
17692    sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17693 
17694    return res;
17695 }
17696 
17697 /*! \brief Handle the transfer part of INVITE with a replaces: header, 
17698     meaning a target pickup or an attended transfer.
17699     Used only once.
17700    XXX 'ignore' is unused.
17701  */
17702 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin)
17703 {
17704    struct ast_frame *f;
17705    int earlyreplace = 0;
17706    int oneleggedreplace = 0;     /* Call with no bridge, propably IVR or voice message */
17707    struct ast_channel *c = p->owner;   /* Our incoming call */
17708    struct ast_channel *replacecall = p->refer->refer_call->owner; /* The channel we're about to take over */
17709    struct ast_channel *targetcall;     /* The bridge to the take-over target */
17710 
17711    struct ast_channel *test;
17712 
17713    /* Check if we're in ring state */
17714    if (replacecall->_state == AST_STATE_RING)
17715       earlyreplace = 1;
17716 
17717    /* Check if we have a bridge */
17718    if (!(targetcall = ast_bridged_channel(replacecall))) {
17719       /* We have no bridge */
17720       if (!earlyreplace) {
17721          ast_debug(2, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
17722          oneleggedreplace = 1;
17723       }
17724    } 
17725    if (targetcall && targetcall->_state == AST_STATE_RINGING)
17726       ast_debug(4, "SIP transfer: Target channel is in ringing state\n");
17727 
17728    if (targetcall) 
17729       ast_debug(4, "SIP transfer: Invite Replace incoming channel should bridge to channel %s while hanging up channel %s\n", targetcall->name, replacecall->name); 
17730    else
17731       ast_debug(4, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name); 
17732 
17733    if (req->ignore) {
17734       ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
17735       /* We should answer something here. If we are here, the
17736          call we are replacing exists, so an accepted 
17737          can't harm */
17738       transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE);
17739       /* Do something more clever here */
17740       ast_channel_unlock(c);
17741       sip_pvt_unlock(p->refer->refer_call);
17742       return 1;
17743    } 
17744    if (!c) {
17745       /* What to do if no channel ??? */
17746       ast_log(LOG_ERROR, "Unable to create new channel.  Invite/replace failed.\n");
17747       transmit_response_reliable(p, "503 Service Unavailable", req);
17748       append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
17749       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17750       sip_pvt_unlock(p->refer->refer_call);
17751       return 1;
17752    }
17753    append_history(p, "Xfer", "INVITE/Replace received");
17754    /* We have three channels to play with
17755       channel c: New incoming call
17756       targetcall: Call from PBX to target
17757       p->refer->refer_call: SIP pvt dialog from transferer to pbx.
17758       replacecall: The owner of the previous
17759       We need to masq C into refer_call to connect to 
17760       targetcall;
17761       If we are talking to internal audio stream, target call is null.
17762    */
17763 
17764    /* Fake call progress */
17765    transmit_response(p, "100 Trying", req);
17766    ast_setstate(c, AST_STATE_RING);
17767 
17768    /* Masquerade the new call into the referred call to connect to target call 
17769       Targetcall is not touched by the masq */
17770 
17771    /* Answer the incoming call and set channel to UP state */
17772    transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE);
17773       
17774    ast_setstate(c, AST_STATE_UP);
17775    
17776    /* Stop music on hold and other generators */
17777    ast_quiet_chan(replacecall);
17778    ast_quiet_chan(targetcall);
17779    ast_debug(4, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);
17780    /* Unlock clone, but not original (replacecall) */
17781    if (!oneleggedreplace)
17782       ast_channel_unlock(c);
17783 
17784    /* Unlock PVT */
17785    sip_pvt_unlock(p->refer->refer_call);
17786 
17787    /* Make sure that the masq does not free our PVT for the old call */
17788    if (! earlyreplace && ! oneleggedreplace )
17789       ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER);  /* Delay hangup */
17790       
17791    /* Prepare the masquerade - if this does not happen, we will be gone */
17792    if(ast_channel_masquerade(replacecall, c))
17793       ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
17794    else
17795       ast_debug(4, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);
17796 
17797    /* The masquerade will happen as soon as someone reads a frame from the channel */
17798 
17799    /* C should now be in place of replacecall */
17800    /* ast_read needs to lock channel */
17801    ast_channel_unlock(c);
17802    
17803    if (earlyreplace || oneleggedreplace ) {
17804       /* Force the masq to happen */
17805       if ((f = ast_read(replacecall))) {  /* Force the masq to happen */
17806          ast_frfree(f);
17807          f = NULL;
17808          ast_debug(4, "Invite/Replace:  Could successfully read frame from RING channel!\n");
17809       } else {
17810          ast_log(LOG_WARNING, "Invite/Replace:  Could not read frame from RING channel \n");
17811       }
17812       c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
17813       if (!oneleggedreplace)
17814          ast_channel_unlock(replacecall);
17815    } else { /* Bridged call, UP channel */
17816       if ((f = ast_read(replacecall))) {  /* Force the masq to happen */
17817          /* Masq ok */
17818          ast_frfree(f);
17819          f = NULL;
17820          ast_debug(3, "Invite/Replace:  Could successfully read frame from channel! Masq done.\n");
17821       } else {
17822          ast_log(LOG_WARNING, "Invite/Replace:  Could not read frame from channel. Transfer failed\n");
17823       }
17824       ast_channel_unlock(replacecall);
17825    }
17826    sip_pvt_unlock(p->refer->refer_call);
17827 
17828    ast_setstate(c, AST_STATE_DOWN);
17829    ast_debug(4, "After transfer:----------------------------\n");
17830    ast_debug(4, " -- C:        %s State %s\n", c->name, ast_state2str(c->_state));
17831    if (replacecall)
17832       ast_debug(4, " -- replacecall:        %s State %s\n", replacecall->name, ast_state2str(replacecall->_state));
17833    if (p->owner) {
17834       ast_debug(4, " -- P->owner: %s State %s\n", p->owner->name, ast_state2str(p->owner->_state));
17835       test = ast_bridged_channel(p->owner);
17836       if (test)
17837          ast_debug(4, " -- Call bridged to P->owner: %s State %s\n", test->name, ast_state2str(test->_state));
17838       else
17839          ast_debug(4, " -- No call bridged to C->owner \n");
17840    } else 
17841       ast_debug(4, " -- No channel yet \n");
17842    ast_debug(4, "End After transfer:----------------------------\n");
17843 
17844    ast_channel_unlock(p->owner); /* Unlock new owner */
17845    if (!oneleggedreplace)
17846       sip_pvt_unlock(p);   /* Unlock SIP structure */
17847 
17848    /* The call should be down with no ast_channel, so hang it up */
17849    c->tech_pvt = dialog_unref(c->tech_pvt, "unref dialog c->tech_pvt");
17850    ast_hangup(c);
17851    return 0;
17852 }
17853 
17854 /*! \brief helper routine for sip_uri_cmp
17855  *
17856  * This takes the parameters from two SIP URIs and determines
17857  * if the URIs match. The rules for parameters *suck*. Here's a breakdown
17858  * 1. If a parameter appears in both URIs, then they must have the same value
17859  *    in order for the URIs to match
17860  * 2. If one URI has a user, maddr, ttl, or method parameter, then the other
17861  *    URI must also have that parameter and must have the same value
17862  *    in order for the URIs to match
17863  * 3. All other headers appearing in only one URI are not considered when
17864  *    determining if URIs match
17865  *
17866  * \param input1 Parameters from URI 1
17867  * \param input2 Parameters from URI 2
17868  * \return Return 0 if the URIs' parameters match, 1 if they do not
17869  */
17870 static int sip_uri_params_cmp(const char *input1, const char *input2) 
17871 {
17872    char *params1 = NULL;
17873    char *params2 = NULL;
17874    char *pos1;
17875    char *pos2;
17876    int zerolength1 = 0;
17877    int zerolength2 = 0;
17878    int maddrmatch = 0;
17879    int ttlmatch = 0;
17880    int usermatch = 0;
17881    int methodmatch = 0;
17882 
17883    if (ast_strlen_zero(input1)) {
17884       zerolength1 = 1;
17885    } else {
17886       params1 = ast_strdupa(input1);
17887    }
17888    if (ast_strlen_zero(input2)) {
17889       zerolength2 = 1;
17890    } else {
17891       params2 = ast_strdupa(input2);
17892    }
17893 
17894    /*Quick optimization. If both params are zero-length, then
17895     * they match
17896     */
17897    if (zerolength1 && zerolength2) {
17898       return 0;
17899    }
17900 
17901    pos1 = params1;
17902    while (!ast_strlen_zero(pos1)) {
17903       char *name1 = pos1;
17904       char *value1 = strchr(pos1, '=');
17905       char *semicolon1 = strchr(pos1, ';');
17906       int matched = 0;
17907       if (semicolon1) {
17908          *semicolon1++ = '\0';
17909       }
17910       if (!value1) {
17911          goto fail;
17912       }
17913       *value1++ = '\0';
17914       /* Checkpoint reached. We have the name and value parsed for param1 
17915        * We have to duplicate params2 each time through the second loop
17916        * or else we can't search and replace the semicolons with \0 each
17917        * time
17918        */
17919       pos2 = ast_strdupa(params2);
17920       while (!ast_strlen_zero(pos2)) {
17921          char *name2 = pos2;
17922          char *value2 = strchr(pos2, '=');
17923          char *semicolon2 = strchr(pos2, ';');
17924          if (semicolon2) {
17925             *semicolon2++ = '\0';
17926          }
17927          if (!value2) {
17928             goto fail;
17929          }
17930          *value2++ = '\0';
17931          if (!strcasecmp(name1, name2)) {
17932             if (strcasecmp(value1, value2)) {
17933                goto fail;
17934             } else {
17935                matched = 1;
17936                break;
17937             }
17938          }
17939          pos2 = semicolon2;
17940       }
17941       /* Need to see if the parameter we're looking at is one of the 'must-match' parameters */
17942       if (!strcasecmp(name1, "maddr")) {
17943          if (matched) {
17944             maddrmatch = 1;
17945          } else {
17946             goto fail;
17947          }
17948       } else if (!strcasecmp(name1, "ttl")) {
17949          if (matched) {
17950             ttlmatch = 1;
17951          } else {
17952             goto fail;
17953          }
17954       } else if (!strcasecmp(name1, "user")) {
17955          if (matched) {
17956             usermatch = 1;
17957          } else {
17958             goto fail;
17959          }
17960       } else if (!strcasecmp(name1, "method")) {
17961          if (matched) {
17962             methodmatch = 1;
17963          } else {
17964             goto fail;
17965          }
17966       }
17967       pos1 = semicolon1;
17968    }
17969 
17970    /* We've made it out of that horrible O(m*n) construct and there are no
17971     * failures yet. We're not done yet, though, because params2 could have
17972     * an maddr, ttl, user, or method header and params1 did not.
17973     */
17974    pos2 = params2;
17975    while (!ast_strlen_zero(pos2)) {
17976       char *name2 = pos2;
17977       char *value2 = strchr(pos2, '=');
17978       char *semicolon2 = strchr(pos2, ';');
17979       if (semicolon2) {
17980          *semicolon2++ = '\0';
17981       }
17982       if (!value2) {
17983          goto fail;
17984       }
17985       *value2++ = '\0';
17986       if ((!strcasecmp(name2, "maddr") && !maddrmatch) ||
17987             (!strcasecmp(name2, "ttl") && !ttlmatch) ||
17988             (!strcasecmp(name2, "user") && !usermatch) ||
17989             (!strcasecmp(name2, "method") && !methodmatch)) {
17990          goto fail;
17991       }
17992    }
17993    return 0;
17994 
17995 fail:
17996    return 1;
17997 }
17998 
17999 /*! \brief helper routine for sip_uri_cmp
18000  *
18001  * This takes the "headers" from two SIP URIs and determines
18002  * if the URIs match. The rules for headers is simple. If a header
18003  * appears in one URI, then it must also appear in the other URI. The
18004  * order in which the headers appear does not matter.
18005  *
18006  * \param input1 Headers from URI 1
18007  * \param input2 Headers from URI 2
18008  * \return Return 0 if the URIs' headers match, 1 if they do not
18009  */
18010 static int sip_uri_headers_cmp(const char *input1, const char *input2)
18011 {
18012    char *headers1 = NULL;
18013    char *headers2 = NULL;
18014    int zerolength1 = 0;
18015    int zerolength2 = 0;
18016    int different = 0;
18017    char *header1;
18018 
18019    if (ast_strlen_zero(input1)) {
18020       zerolength1 = 1;
18021    } else {
18022       headers1 = ast_strdupa(input1);
18023    }
18024    
18025    if (ast_strlen_zero(input2)) {
18026       zerolength2 = 1;
18027    } else {
18028       headers2 = ast_strdupa(input2);
18029    }
18030 
18031    if ((zerolength1 && !zerolength2) ||
18032          (zerolength2 && !zerolength1))
18033       return 1;
18034 
18035    if (zerolength1 && zerolength2)
18036       return 0;
18037 
18038    /* At this point, we can definitively state that both inputs are
18039     * not zero-length. First, one more optimization. If the length
18040     * of the headers is not equal, then we definitely have no match
18041     */
18042    if (strlen(headers1) != strlen(headers2)) {
18043       return 1;
18044    }
18045 
18046    for (header1 = strsep(&headers1, "&"); header1; header1 = strsep(&headers1, "&")) {
18047       if (!strcasestr(headers2, header1)) {
18048          different = 1;
18049          break;
18050       }
18051    }
18052 
18053    return different;
18054 }
18055 
18056 static int sip_uri_cmp(const char *input1, const char *input2)
18057 {
18058    char *uri1 = ast_strdupa(input1);
18059    char *uri2 = ast_strdupa(input2);
18060    char *host1;
18061    char *host2;
18062    char *params1;
18063    char *params2;
18064    char *headers1;
18065    char *headers2;
18066 
18067    /* Strip off "sip:" from the URI. We know this is present
18068     * because it was checked back in parse_request()
18069     */
18070    strsep(&uri1, ":");
18071    strsep(&uri2, ":");
18072 
18073    if ((host1 = strchr(uri1, '@'))) {
18074       *host1++ = '\0';
18075    }
18076    if ((host2 = strchr(uri2, '@'))) {
18077       *host2++ = '\0';
18078    }
18079 
18080    /* Check for mismatched username and passwords. This is the
18081     * only case-sensitive comparison of a SIP URI
18082     */
18083    if ((host1 && !host2) ||
18084          (host2 && !host1) ||
18085          (host1 && host2 && strcmp(uri1, uri2))) {
18086       return 1;
18087    }
18088 
18089    if (!host1)
18090       host1 = uri1;
18091    if (!host2)
18092       host2 = uri2;
18093 
18094    /* Strip off the parameters and headers so we can compare
18095     * host and port
18096     */
18097 
18098    if ((params1 = strchr(host1, ';'))) {
18099       *params1++ = '\0';
18100    }
18101    if ((params2 = strchr(host2, ';'))) {
18102       *params2++ = '\0';
18103    }
18104 
18105    /* Headers come after parameters, but there may be headers without
18106     * parameters, thus the S_OR
18107     */
18108    if ((headers1 = strchr(S_OR(params1, host1), '?'))) {
18109       *headers1++ = '\0';
18110    }
18111    if ((headers2 = strchr(S_OR(params2, host2), '?'))) {
18112       *headers2++ = '\0';
18113    }
18114 
18115    /* Now the host/port are properly isolated. We can get by with a string comparison
18116     * because the SIP URI checking rules have some interesting exceptions that make
18117     * this possible. I will note 2 in particular
18118     * 1. hostnames which resolve to the same IP address as well as a hostname and its
18119     *    IP address are not considered a match with SIP URI's.
18120     * 2. If one URI specifies a port and the other does not, then the URIs do not match.
18121     *    This includes if one URI explicitly contains port 5060 and the other implies it
18122     *    by not having a port specified.
18123     */
18124 
18125    if (strcasecmp(host1, host2)) {
18126       return 1;
18127    }
18128 
18129    /* Headers have easier rules to follow, so do those first */
18130    if (sip_uri_headers_cmp(headers1, headers2)) {
18131       return 1;
18132    }
18133 
18134    /* And now the parameters. Ugh */
18135    return sip_uri_params_cmp(params1, params2);
18136 }
18137 
18138 
18139 static int sip_t38_abort(const void *data)
18140 {
18141    struct sip_pvt *p = (struct sip_pvt *) data;
18142 
18143    change_t38_state(p, T38_DISABLED);
18144    transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
18145    p->t38id = -1;
18146    dialog_unref(p, "unref the dialog ptr from sip_t38_abort, because it held a dialog ptr");
18147 
18148    return 0;
18149 }
18150 
18151 /*! \brief Handle incoming INVITE request
18152 \note    If the INVITE has a Replaces header, it is part of an
18153  * attended transfer. If so, we do not go through the dial
18154  * plan but tries to find the active call and masquerade
18155  * into it 
18156  */
18157 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)
18158 {
18159    int res = 1;
18160    int gotdest;
18161    const char *p_replaces;
18162    char *replace_id = NULL;
18163    const char *required;
18164    unsigned int required_profile = 0;
18165    struct ast_channel *c = NULL;    /* New channel */
18166    int reinvite = 0;
18167    int rtn;
18168 
18169    const char *p_uac_se_hdr;       /* UAC's Session-Expires header string                      */
18170    const char *p_uac_min_se;       /* UAC's requested Min-SE interval (char string)            */
18171    int uac_max_se = -1;            /* UAC's Session-Expires in integer format                  */
18172    int uac_min_se = -1;            /* UAC's Min-SE in integer format                           */
18173    int st_active = FALSE;          /* Session-Timer on/off boolean                             */
18174    int st_interval = 0;            /* Session-Timer negotiated refresh interval                */
18175    enum st_refresher st_ref;       /* Session-Timer session refresher                          */
18176    int dlg_min_se = -1;
18177    st_ref = SESSION_TIMER_REFRESHER_AUTO;
18178 
18179    /* Find out what they support */
18180    if (!p->sipoptions) {
18181       const char *supported = get_header(req, "Supported");
18182       if (!ast_strlen_zero(supported))
18183          parse_sip_options(p, supported);
18184    }
18185 
18186    /* Find out what they require */
18187    required = get_header(req, "Require");
18188    if (!ast_strlen_zero(required)) {
18189       required_profile = parse_sip_options(NULL, required);
18190       if (required_profile && !(required_profile & (SIP_OPT_REPLACES | SIP_OPT_TIMER))) {
18191          /* At this point we only support REPLACES and Session-Timer */
18192          transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, required);
18193          ast_log(LOG_WARNING, "Received SIP INVITE with unsupported required extension: %s\n", required);
18194          p->invitestate = INV_COMPLETED;
18195          if (!p->lastinvite)
18196             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18197          return -1;
18198       }
18199    }
18200 
18201    /* The option tags may be present in Supported: or Require: headers.
18202    Include the Require: option tags for further processing as well */
18203    p->sipoptions |= required_profile;
18204    p->reqsipoptions = required_profile;
18205 
18206    /* Check if this is a loop */
18207    if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && p->owner && (p->invitestate != INV_TERMINATED && p->invitestate != INV_CONFIRMED)) {
18208       /* This is a call to ourself.  Send ourselves an error code and stop
18209          processing immediately, as SIP really has no good mechanism for
18210          being able to call yourself */
18211       /* If pedantic is on, we need to check the tags. If they're different, this is
18212          in fact a forked call through a SIP proxy somewhere. */
18213       int different;
18214       char *initial_rlPart2 = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
18215       char *this_rlPart2 = REQ_OFFSET_TO_STR(req, rlPart2);
18216       if (pedanticsipchecking)
18217          different = sip_uri_cmp(initial_rlPart2, this_rlPart2);
18218       else
18219          different = strcmp(initial_rlPart2, this_rlPart2);
18220       if (!different) {
18221          transmit_response(p, "482 Loop Detected", req);
18222          p->invitestate = INV_COMPLETED;
18223          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18224          return 0;
18225       } else {
18226          /*! This is a spiral. What we need to do is to just change the outgoing INVITE
18227           * so that it now routes to the new Request URI. Since we created the INVITE ourselves
18228           * that should be all we need to do.
18229           * 
18230           * \todo XXX This needs to be reviewed.  YOu don't change the request URI really, you route the packet
18231           * correctly instead...
18232           */
18233          char *uri = ast_strdupa(this_rlPart2);
18234          char *at = strchr(uri, '@');
18235          char *peerorhost;
18236          ast_debug(2, "Potential spiral detected. Original RURI was %s, new RURI is %s\n", initial_rlPart2, this_rlPart2);
18237          if (at) {
18238             *at = '\0';
18239          }
18240          /* Parse out "sip:" */
18241          if ((peerorhost = strchr(uri, ':'))) {
18242             *peerorhost++ = '\0';
18243          }
18244          ast_string_field_set(p, theirtag, NULL);
18245          /* Treat this as if there were a call forward instead...
18246           */
18247          ast_string_field_set(p->owner, call_forward, peerorhost);
18248          ast_queue_control(p->owner, AST_CONTROL_BUSY);
18249          return 0;
18250       }
18251    }
18252 
18253    if (!req->ignore && p->pendinginvite) {
18254       if (!ast_test_flag(&p->flags[0], SIP_OUTGOING) && (p->invitestate == INV_COMPLETED || p->invitestate == INV_TERMINATED)) {
18255          /* What do these circumstances mean? We have received an INVITE for an "incoming" dialog for which we
18256           * have sent a final response. We have not yet received an ACK, though (which is why p->pendinginvite is non-zero).
18257           * We also know that the INVITE is not a retransmission, because otherwise the "ignore" flag would be set.
18258           * This means that either we are receiving a reinvite for a terminated dialog, or we are receiving an INVITE with
18259           * credentials based on one we challenged earlier.
18260           *
18261           * The action to take in either case is to treat the INVITE as though it contains an implicit ACK for the previous
18262           * transaction. Calling __sip_ack will take care of this by clearing the p->pendinginvite and removing the response
18263           * from the previous transaction from the list of outstanding packets.
18264           */
18265          __sip_ack(p, p->pendinginvite, 1, 0);
18266       } else {
18267          /* We already have a pending invite. Sorry. You are on hold. */
18268          p->glareinvite = seqno;
18269          if (p->rtp && find_sdp(req)) {
18270             struct sockaddr_in sin;
18271             if (get_ip_and_port_from_sdp(req, SDP_AUDIO, &sin)) {
18272                ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Audio may not work properly on this call.\n");
18273             } else {
18274                ast_rtp_set_alt_peer(p->rtp, &sin);
18275             }
18276             if (p->vrtp) {
18277                if (get_ip_and_port_from_sdp(req, SDP_VIDEO, &sin)) {
18278                   ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Video may not work properly on this call.\n");
18279                } else {
18280                   ast_rtp_set_alt_peer(p->vrtp, &sin);
18281                }
18282             }
18283          }
18284          transmit_response_reliable(p, "491 Request Pending", req);
18285          ast_debug(1, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
18286          /* Don't destroy dialog here */
18287          return 0;
18288       }
18289    }
18290 
18291    p_replaces = get_header(req, "Replaces");
18292    if (!ast_strlen_zero(p_replaces)) {
18293       /* We have a replaces header */
18294       char *ptr;
18295       char *fromtag = NULL;
18296       char *totag = NULL;
18297       char *start, *to;
18298       int error = 0;
18299 
18300       if (p->owner) {
18301          ast_debug(3, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
18302          transmit_response_reliable(p, "400 Bad request", req);   /* The best way to not not accept the transfer */
18303          /* Do not destroy existing call */
18304          return -1;
18305       }
18306 
18307       if (sipdebug)
18308          ast_debug(3, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
18309       /* Create a buffer we can manipulate */
18310       replace_id = ast_strdupa(p_replaces);
18311       ast_uri_decode(replace_id);
18312 
18313       if (!p->refer && !sip_refer_allocate(p)) {
18314          transmit_response_reliable(p, "500 Server Internal Error", req);
18315          append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
18316          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18317          p->invitestate = INV_COMPLETED;
18318          return -1;
18319       }
18320 
18321       /*  Todo: (When we find phones that support this)
18322          if the replaces header contains ";early-only"
18323          we can only replace the call in early
18324          stage, not after it's up.
18325 
18326          If it's not in early mode, 486 Busy.
18327       */
18328       
18329       /* Skip leading whitespace */
18330       replace_id = ast_skip_blanks(replace_id);
18331 
18332       start = replace_id;
18333       while ( (ptr = strsep(&start, ";")) ) {
18334          ptr = ast_skip_blanks(ptr); /* XXX maybe unnecessary ? */
18335          if ( (to = strcasestr(ptr, "to-tag=") ) )
18336             totag = to + 7;   /* skip the keyword */
18337          else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
18338             fromtag = to + 9; /* skip the keyword */
18339             fromtag = strsep(&fromtag, "&"); /* trim what ? */
18340          }
18341       }
18342 
18343       if (sipdebug) 
18344          ast_debug(4, "Invite/replaces: Will use Replace-Call-ID : %s Fromtag: %s Totag: %s\n", replace_id, fromtag ? fromtag : "<no from tag>", totag ? totag : "<no to tag>");
18345 
18346 
18347       /* Try to find call that we are replacing 
18348          If we have a Replaces  header, we need to cancel that call if we succeed with this call 
18349       */
18350       if ((p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
18351          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
18352          transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
18353          error = 1;
18354       }
18355 
18356       /* At this point, bot the pvt and the owner of the call to be replaced is locked */
18357 
18358       /* The matched call is the call from the transferer to Asterisk .
18359          We want to bridge the bridged part of the call to the 
18360          incoming invite, thus taking over the refered call */
18361 
18362       if (p->refer->refer_call == p) {
18363          ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
18364          p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
18365          transmit_response_reliable(p, "400 Bad request", req);   /* The best way to not not accept the transfer */
18366          error = 1;
18367       }
18368 
18369       if (!error && !p->refer->refer_call->owner) {
18370          /* Oops, someting wrong anyway, no owner, no call */
18371          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
18372          /* Check for better return code */
18373          transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replace)", req);
18374          error = 1;
18375       }
18376 
18377       if (!error && 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 ) {
18378          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
18379          transmit_response_reliable(p, "603 Declined (Replaces)", req);
18380          error = 1;
18381       }
18382 
18383       if (error) {   /* Give up this dialog */
18384          append_history(p, "Xfer", "INVITE/Replace Failed.");
18385          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18386          sip_pvt_unlock(p);
18387          if (p->refer->refer_call) {
18388             sip_pvt_unlock(p->refer->refer_call);
18389             if (p->refer->refer_call->owner) {
18390                ast_channel_unlock(p->refer->refer_call->owner);
18391             }
18392          }
18393          p->invitestate = INV_COMPLETED;
18394          return -1;
18395       }
18396    }
18397 
18398    /* Check if this is an INVITE that sets up a new dialog or
18399       a re-invite in an existing dialog */
18400 
18401    if (!req->ignore) {
18402       int newcall = (p->initreq.headers ? TRUE : FALSE);
18403 
18404       if (sip_cancel_destroy(p))
18405          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
18406       /* This also counts as a pending invite */
18407       p->pendinginvite = seqno;
18408       check_via(p, req);
18409 
18410       copy_request(&p->initreq, req);     /* Save this INVITE as the transaction basis */
18411       if (sipdebug)
18412          ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
18413       if (!p->owner) {  /* Not a re-invite */
18414          if (debug)
18415             ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
18416          if (newcall)
18417             append_history(p, "Invite", "New call: %s", p->callid);
18418          parse_ok_contact(p, req);
18419       } else { /* Re-invite on existing call */
18420          ast_clear_flag(&p->flags[0], SIP_OUTGOING);  /* This is now an inbound dialog */
18421          /* Handle SDP here if we already have an owner */
18422          if (find_sdp(req)) {
18423             if (process_sdp(p, req, SDP_T38_INITIATE)) {
18424                transmit_response_reliable(p, "488 Not acceptable here", req);
18425                if (!p->lastinvite)
18426                   sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18427                return -1;
18428             }
18429          } else {
18430             p->jointcapability = p->capability;
18431             ast_debug(1, "Hm....  No sdp for the moment\n");
18432          }
18433          if (p->do_history) /* This is a response, note what it was for */
18434             append_history(p, "ReInv", "Re-invite received");
18435       }
18436    } else if (debug)
18437       ast_verbose("Ignoring this INVITE request\n");
18438 
18439    
18440    if (!p->lastinvite && !req->ignore && !p->owner) {
18441       /* This is a new invite */
18442       /* Handle authentication if this is our first invite */
18443       res = check_user(p, req, SIP_INVITE, e, XMIT_RELIABLE, sin);
18444       if (res == AUTH_CHALLENGE_SENT) {
18445          p->invitestate = INV_COMPLETED;     /* Needs to restart in another INVITE transaction */
18446          return 0;
18447       }
18448       if (res < 0) { /* Something failed in authentication */
18449          if (res == AUTH_FAKE_AUTH) {
18450             ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
18451             transmit_fake_auth_response(p, SIP_INVITE, req, XMIT_RELIABLE);
18452          } else {
18453             ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
18454             transmit_response_reliable(p, "403 Forbidden", req);
18455          }
18456          p->invitestate = INV_COMPLETED;  
18457          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18458          ast_string_field_set(p, theirtag, NULL);
18459          return 0;
18460       }
18461 
18462       /* If T38 is needed but not present, then make it magically appear */
18463       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && !p->udptl && (p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr))) {
18464          set_t38_capabilities(p);
18465       }
18466 
18467       /* We have a succesful authentication, process the SDP portion if there is one */
18468       if (find_sdp(req)) {
18469          if (process_sdp(p, req, SDP_T38_INITIATE)) {
18470             /* Unacceptable codecs */
18471             transmit_response_reliable(p, "488 Not acceptable here", req);
18472             p->invitestate = INV_COMPLETED;  
18473             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18474             ast_debug(1, "No compatible codecs for this SIP call.\n");
18475             return -1;
18476          }
18477       } else { /* No SDP in invite, call control session */
18478          p->jointcapability = p->capability;
18479          ast_debug(2, "No SDP in Invite, third party call control\n");
18480       }
18481 
18482       /* Queue NULL frame to prod ast_rtp_bridge if appropriate */
18483       /* This seems redundant ... see !p-owner above */
18484       if (p->owner)
18485          ast_queue_frame(p->owner, &ast_null_frame);
18486 
18487 
18488       /* Initialize the context if it hasn't been already */
18489       if (ast_strlen_zero(p->context))
18490          ast_string_field_set(p, context, default_context);
18491 
18492 
18493       /* Check number of concurrent calls -vs- incoming limit HERE */
18494       ast_debug(1, "Checking SIP call limits for device %s\n", p->username);
18495       if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
18496          if (res < 0) {
18497             ast_log(LOG_NOTICE, "Failed to place call for device %s, too many calls\n", p->username);
18498             transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
18499             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18500             p->invitestate = INV_COMPLETED;  
18501          }
18502          return 0;
18503       }
18504       gotdest = get_destination(p, NULL); /* Get destination right away */
18505       get_rdnis(p, NULL);        /* Get redirect information */
18506       extract_uri(p, req);       /* Get the Contact URI */
18507       build_contact(p);       /* Build our contact header */
18508 
18509       if (p->rtp) {
18510          ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
18511          ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
18512       }
18513 
18514       if (!replace_id && gotdest) { /* No matching extension found */
18515          if (gotdest == 1 && ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP))
18516             transmit_response_reliable(p, "484 Address Incomplete", req);
18517          else {
18518             char *decoded_exten = ast_strdupa(p->exten);
18519             
18520             transmit_response_reliable(p, "404 Not Found", req);
18521             ast_uri_decode(decoded_exten);
18522             ast_log(LOG_NOTICE, "Call from '%s' to extension"
18523                " '%s' rejected because extension not found.\n",
18524                S_OR(p->username, p->peername), decoded_exten);
18525          }
18526          p->invitestate = INV_COMPLETED;  
18527          update_call_counter(p, DEC_CALL_LIMIT);
18528          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18529          return 0;
18530       } else {
18531 
18532          /* If no extension was specified, use the s one */
18533          /* Basically for calling to IP/Host name only */
18534          if (ast_strlen_zero(p->exten))
18535             ast_string_field_set(p, exten, "s");
18536          /* Initialize our tag */   
18537 
18538          make_our_tag(p->tag, sizeof(p->tag));
18539          /* First invitation - create the channel */
18540          c = sip_new(p, AST_STATE_DOWN, S_OR(p->peername, NULL));
18541          *recount = 1;
18542 
18543          /* Save Record-Route for any later requests we make on this dialogue */
18544          build_route(p, req, 0);
18545 
18546          if (c) {
18547             /* Pre-lock the call */
18548             ast_channel_lock(c);
18549          }
18550       }
18551    } else {
18552       if (sipdebug) {
18553          if (!req->ignore)
18554             ast_debug(2, "Got a SIP re-invite for call %s\n", p->callid);
18555          else
18556             ast_debug(2, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
18557       }
18558       if (!req->ignore)
18559          reinvite = 1;
18560       c = p->owner;
18561    }
18562 
18563    /* Session-Timers */
18564    if (p->sipoptions & SIP_OPT_TIMER) {
18565       /* The UAC has requested session-timers for this session. Negotiate
18566       the session refresh interval and who will be the refresher */
18567       ast_debug(2, "Incoming INVITE with 'timer' option enabled\n");
18568 
18569       /* Allocate Session-Timers struct w/in the dialog */
18570       if (!p->stimer)
18571          sip_st_alloc(p);
18572 
18573       /* Parse the Session-Expires header */
18574       p_uac_se_hdr = get_header(req, "Session-Expires");
18575       if (!ast_strlen_zero(p_uac_se_hdr)) {
18576          rtn = parse_session_expires(p_uac_se_hdr, &uac_max_se, &st_ref);
18577          if (rtn != 0) {
18578             transmit_response_reliable(p, "400 Session-Expires Invalid Syntax", req);
18579             p->invitestate = INV_COMPLETED;
18580             if (!p->lastinvite) {
18581                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18582             }
18583             return -1;
18584          }
18585       }
18586 
18587       /* Parse the Min-SE header */
18588       p_uac_min_se = get_header(req, "Min-SE");
18589       if (!ast_strlen_zero(p_uac_min_se)) {
18590          rtn = parse_minse(p_uac_min_se, &uac_min_se); 
18591          if (rtn != 0) {
18592                transmit_response_reliable(p, "400 Min-SE Invalid Syntax", req);
18593                      p->invitestate = INV_COMPLETED;
18594                      if (!p->lastinvite) {
18595                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18596             }
18597             return -1;
18598          }
18599       }
18600 
18601       dlg_min_se = st_get_se(p, FALSE);
18602       switch (st_get_mode(p)) {
18603       case SESSION_TIMER_MODE_ACCEPT:
18604       case SESSION_TIMER_MODE_ORIGINATE:
18605          if (uac_max_se > 0 && uac_max_se < dlg_min_se) {
18606             transmit_response_with_minse(p, "422 Session Interval Too Small", req, dlg_min_se);
18607             p->invitestate = INV_COMPLETED;
18608             if (!p->lastinvite) {
18609                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18610             }
18611             return -1;
18612          }
18613 
18614          p->stimer->st_active_peer_ua = TRUE;
18615          st_active = TRUE;
18616          if (st_ref == SESSION_TIMER_REFRESHER_AUTO) {
18617             st_ref = st_get_refresher(p);
18618          }
18619 
18620          if (uac_max_se > 0) {
18621             int dlg_max_se = st_get_se(p, TRUE);
18622             if (dlg_max_se >= uac_min_se) {
18623                st_interval = (uac_max_se < dlg_max_se) ? uac_max_se : dlg_max_se;
18624             } else {
18625                st_interval = uac_max_se;
18626             }
18627          } else {
18628             st_interval = uac_min_se;
18629          }
18630          break;
18631 
18632       case SESSION_TIMER_MODE_REFUSE:
18633          if (p->reqsipoptions & SIP_OPT_TIMER) {
18634             transmit_response_with_unsupported(p, "420 Option Disabled", req, required);
18635             ast_log(LOG_WARNING, "Received SIP INVITE with supported but disabled option: %s\n", required);
18636             p->invitestate = INV_COMPLETED;
18637             if (!p->lastinvite) {
18638                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18639             }
18640             return -1;
18641          }
18642          break;
18643 
18644       default:
18645          ast_log(LOG_ERROR, "Internal Error %d at %s:%d\n", st_get_mode(p), __FILE__, __LINE__);
18646          break;
18647       }
18648    } else {
18649       /* The UAC did not request session-timers.  Asterisk (UAS), will now decide
18650       (based on session-timer-mode in sip.conf) whether to run session-timers for
18651       this session or not. */
18652       switch (st_get_mode(p)) {
18653       case SESSION_TIMER_MODE_ORIGINATE:
18654          st_active = TRUE;
18655          st_interval = st_get_se(p, TRUE);
18656          st_ref = SESSION_TIMER_REFRESHER_UAS;
18657          p->stimer->st_active_peer_ua = FALSE;
18658          break;
18659 
18660       default:
18661          break;
18662       }
18663    }
18664 
18665    if (reinvite == 0) {
18666       /* Session-Timers: Start session refresh timer based on negotiation/config */
18667       if (st_active == TRUE) {
18668          p->stimer->st_active   = TRUE;
18669          p->stimer->st_interval = st_interval;
18670          p->stimer->st_ref      = st_ref;
18671          start_session_timer(p);
18672       }
18673    } else {
18674       if (p->stimer->st_active == TRUE) {
18675          /* Session-Timers:  A re-invite request sent within a dialog will serve as 
18676          a refresh request, no matter whether the re-invite was sent for refreshing 
18677          the session or modifying it.*/
18678          ast_debug (2, "Restarting session-timers on a refresh - %s\n", p->callid);
18679 
18680          /* The UAC may be adjusting the session-timers mid-session */
18681          if (st_interval > 0) {
18682             p->stimer->st_interval = st_interval;
18683             p->stimer->st_ref      = st_ref;
18684          }
18685 
18686          restart_session_timer(p);
18687          if (p->stimer->st_expirys > 0) {
18688             p->stimer->st_expirys--;
18689          }
18690       }
18691    }
18692 
18693    if (!req->ignore && p)
18694       p->lastinvite = seqno;
18695 
18696    if (replace_id) {    /* Attended transfer or call pickup - we're the target */
18697       /* Go and take over the target call */
18698       if (sipdebug)
18699          ast_debug(4, "Sending this call to the invite/replcaes handler %s\n", p->callid);
18700       return handle_invite_replaces(p, req, debug, seqno, sin);
18701    }
18702 
18703 
18704    if (c) { /* We have a call  -either a new call or an old one (RE-INVITE) */
18705       enum ast_channel_state c_state = c->_state;
18706 
18707       if (c_state != AST_STATE_UP && reinvite &&
18708          (p->invitestate == INV_TERMINATED || p->invitestate == INV_CONFIRMED)) {
18709          /* If these conditions are true, and the channel is still in the 'ringing'
18710           * state, then this likely means that we have a situation where the initial
18711           * INVITE transaction has completed *but* the channel's state has not yet been
18712           * changed to UP. The reason this could happen is if the reinvite is received
18713           * on the SIP socket prior to an application calling ast_read on this channel
18714           * to read the answer frame we earlier queued on it. In this case, the reinvite
18715           * is completely legitimate so we need to handle this the same as if the channel 
18716           * were already UP. Thus we are purposely falling through to the AST_STATE_UP case.
18717           */
18718          c_state = AST_STATE_UP;
18719       }
18720 
18721       switch(c_state) {
18722       case AST_STATE_DOWN:
18723          ast_debug(2, "%s: New call is still down.... Trying... \n", c->name);
18724          transmit_response(p, "100 Trying", req);
18725          p->invitestate = INV_PROCEEDING;
18726          ast_setstate(c, AST_STATE_RING);
18727          if (strcmp(p->exten, ast_pickup_ext())) { /* Call to extension -start pbx on this call */
18728             enum ast_pbx_result result;
18729 
18730             result = ast_pbx_start(c);
18731 
18732             switch(result) {
18733             case AST_PBX_FAILED:
18734                ast_log(LOG_WARNING, "Failed to start PBX :(\n");
18735                p->invitestate = INV_COMPLETED;
18736                transmit_response_reliable(p, "503 Unavailable", req);
18737                break;
18738             case AST_PBX_CALL_LIMIT:
18739                ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
18740                p->invitestate = INV_COMPLETED;
18741                transmit_response_reliable(p, "480 Temporarily Unavailable", req);
18742                break;
18743             case AST_PBX_SUCCESS:
18744                /* nothing to do */
18745                break;
18746             }
18747 
18748             if (result) {
18749 
18750                /* Unlock locks so ast_hangup can do its magic */
18751                ast_channel_unlock(c);
18752                sip_pvt_unlock(p);
18753                ast_hangup(c);
18754                sip_pvt_lock(p);
18755                c = NULL;
18756             }
18757          } else { /* Pickup call in call group */
18758             ast_channel_unlock(c);
18759             *nounlock = 1;
18760             if (ast_pickup_call(c)) {
18761                ast_log(LOG_NOTICE, "Nothing to pick up for %s\n", p->callid);
18762                transmit_response_reliable(p, "503 Unavailable", req);
18763                sip_alreadygone(p);
18764                /* Unlock locks so ast_hangup can do its magic */
18765                sip_pvt_unlock(p);
18766                c->hangupcause = AST_CAUSE_CALL_REJECTED;
18767             } else {
18768                sip_pvt_unlock(p);
18769                ast_setstate(c, AST_STATE_DOWN);
18770                c->hangupcause = AST_CAUSE_NORMAL_CLEARING;
18771             }
18772             p->invitestate = INV_COMPLETED;
18773             ast_hangup(c);
18774             sip_pvt_lock(p);
18775             c = NULL;
18776          }
18777          break;
18778       case AST_STATE_RING:
18779          transmit_response(p, "100 Trying", req);
18780          p->invitestate = INV_PROCEEDING;
18781          break;
18782       case AST_STATE_RINGING:
18783          transmit_response(p, "180 Ringing", req);
18784          p->invitestate = INV_PROCEEDING;
18785          break;
18786       case AST_STATE_UP:
18787          ast_debug(2, "%s: This call is UP.... \n", c->name);
18788 
18789          transmit_response(p, "100 Trying", req);
18790 
18791          if (p->t38.state == T38_PEER_REINVITE) {
18792             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."));
18793          } else if (p->t38.state == T38_ENABLED) {
18794             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
18795             transmit_response_with_t38_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ?  XMIT_UNRELIABLE : XMIT_CRITICAL)));
18796          } else if (p->t38.state == T38_DISABLED) {
18797             /* If this is not a re-invite or something to ignore - it's critical */
18798             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
18799             transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ?  XMIT_UNRELIABLE : XMIT_CRITICAL)), p->session_modify == TRUE ? FALSE:TRUE); 
18800          }
18801 
18802          p->invitestate = INV_TERMINATED;
18803          break;
18804       default:
18805          ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
18806          transmit_response(p, "100 Trying", req);
18807          break;
18808       }
18809    } else {
18810       if (p && (p->autokillid == -1)) {
18811          const char *msg;
18812 
18813          if (!p->jointcapability)
18814             msg = "488 Not Acceptable Here (codec error)";
18815          else {
18816             ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
18817             msg = "503 Unavailable";
18818          }
18819          transmit_response_reliable(p, msg, req);
18820          p->invitestate = INV_COMPLETED;
18821          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18822       }
18823    }
18824    return res;
18825 }
18826 
18827 /*! \brief  Find all call legs and bridge transferee with target 
18828  * called from handle_request_refer */
18829 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno)
18830 {
18831    struct sip_dual target;    /* Chan 1: Call from tranferer to Asterisk */
18832                /* Chan 2: Call from Asterisk to target */
18833    int res = 0;
18834    struct sip_pvt *targetcall_pvt;
18835 
18836    /* Check if the call ID of the replaces header does exist locally */
18837    if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag, 
18838       transferer->refer->replaces_callid_fromtag))) {
18839       if (transferer->refer->localtransfer) {
18840          /* We did not find the refered call. Sorry, can't accept then */
18841          transmit_response(transferer, "202 Accepted", req);
18842          /* Let's fake a response from someone else in order
18843             to follow the standard */
18844          transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
18845          append_history(transferer, "Xfer", "Refer failed");
18846          ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);  
18847          transferer->refer->status = REFER_FAILED;
18848          return -1;
18849       }
18850       /* Fall through for remote transfers that we did not find locally */
18851       ast_debug(3, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
18852       return 0;
18853    }
18854 
18855    /* Ok, we can accept this transfer */
18856    transmit_response(transferer, "202 Accepted", req);
18857    append_history(transferer, "Xfer", "Refer accepted");
18858    if (!targetcall_pvt->owner) { /* No active channel */
18859       ast_debug(4, "SIP attended transfer: Error: No owner of target call\n");
18860       /* Cancel transfer */
18861       transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
18862       append_history(transferer, "Xfer", "Refer failed");
18863       ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
18864       transferer->refer->status = REFER_FAILED;
18865       sip_pvt_unlock(targetcall_pvt);
18866       if (targetcall_pvt)
18867          ao2_t_ref(targetcall_pvt, -1, "Drop targetcall_pvt pointer");
18868       return -1;
18869    }
18870 
18871    /* We have a channel, find the bridge */
18872    target.chan1 = targetcall_pvt->owner;           /* Transferer to Asterisk */
18873    target.chan2 = ast_bridged_channel(targetcall_pvt->owner);  /* Asterisk to target */
18874 
18875    if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
18876       /* Wrong state of new channel */
18877       if (target.chan2) 
18878          ast_debug(4, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
18879       else if (target.chan1->_state != AST_STATE_RING)
18880          ast_debug(4, "SIP attended transfer: Error: No target channel\n");
18881       else
18882          ast_debug(4, "SIP attended transfer: Attempting transfer in ringing state\n");
18883    }
18884 
18885    /* Transfer */
18886    if (sipdebug) {
18887       if (current->chan2)  /* We have two bridges */
18888          ast_debug(4, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
18889       else        /* One bridge, propably transfer of IVR/voicemail etc */
18890          ast_debug(4, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
18891    }
18892 
18893    ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);   /* Delay hangup */
18894 
18895    /* Perform the transfer */
18896    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",
18897       transferer->owner->name,
18898       transferer->owner->uniqueid,
18899       transferer->callid,
18900       target.chan1->name,
18901       target.chan1->uniqueid);
18902    res = attempt_transfer(current, &target);
18903    sip_pvt_unlock(targetcall_pvt);
18904    if (res) {
18905       /* Failed transfer */
18906       transmit_notify_with_sipfrag(transferer, seqno, "486 Busy Here", TRUE);
18907       append_history(transferer, "Xfer", "Refer failed");
18908       if (targetcall_pvt->owner)
18909          ast_channel_unlock(targetcall_pvt->owner);
18910       ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
18911    } else {
18912       /* Transfer succeeded! */
18913 
18914       /* Tell transferer that we're done. */
18915       transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
18916       append_history(transferer, "Xfer", "Refer succeeded");
18917       transferer->refer->status = REFER_200OK;
18918       if (targetcall_pvt->owner) {
18919          ast_debug(1, "SIP attended transfer: Unlocking channel %s\n", targetcall_pvt->owner->name);
18920          ast_channel_unlock(targetcall_pvt->owner);
18921       }
18922    }
18923    if (targetcall_pvt)
18924       ao2_t_ref(targetcall_pvt, -1, "drop targetcall_pvt");
18925    return 1;
18926 }
18927 
18928 
18929 /*! \brief Handle incoming REFER request */
18930 /*! \page SIP_REFER SIP transfer Support (REFER)
18931 
18932    REFER is used for call transfer in SIP. We get a REFER
18933    to place a new call with an INVITE somwhere and then
18934    keep the transferor up-to-date of the transfer. If the
18935    transfer fails, get back on line with the orginal call. 
18936 
18937    - REFER can be sent outside or inside of a dialog.
18938      Asterisk only accepts REFER inside of a dialog.
18939 
18940    - If we get a replaces header, it is an attended transfer
18941 
18942    \par Blind transfers
18943    The transferor provides the transferee
18944    with the transfer targets contact. The signalling between
18945    transferer or transferee should not be cancelled, so the
18946    call is recoverable if the transfer target can not be reached 
18947    by the transferee.
18948 
18949    In this case, Asterisk receives a TRANSFER from
18950    the transferor, thus is the transferee. We should
18951    try to set up a call to the contact provided
18952    and if that fails, re-connect the current session.
18953    If the new call is set up, we issue a hangup.
18954    In this scenario, we are following section 5.2
18955    in the SIP CC Transfer draft. (Transfer without
18956    a GRUU)
18957 
18958    \par Transfer with consultation hold
18959    In this case, the transferor
18960    talks to the transfer target before the transfer takes place.
18961    This is implemented with SIP hold and transfer.
18962    Note: The invite From: string could indicate a transfer.
18963    (Section 6. Transfer with consultation hold)
18964    The transferor places the transferee on hold, starts a call
18965    with the transfer target to alert them to the impending
18966    transfer, terminates the connection with the target, then
18967    proceeds with the transfer (as in Blind transfer above)
18968 
18969    \par Attended transfer
18970    The transferor places the transferee
18971    on hold, calls the transfer target to alert them,
18972    places the target on hold, then proceeds with the transfer
18973    using a Replaces header field in the Refer-to header. This
18974    will force the transfee to send an Invite to the target,
18975    with a replaces header that instructs the target to
18976    hangup the call between the transferor and the target.
18977    In this case, the Refer/to: uses the AOR address. (The same
18978    URI that the transferee used to establish the session with
18979    the transfer target (To: ). The Require: replaces header should
18980    be in the INVITE to avoid the wrong UA in a forked SIP proxy
18981    scenario to answer and have no call to replace with.
18982 
18983    The referred-by header is *NOT* required, but if we get it,
18984    can be copied into the INVITE to the transfer target to 
18985    inform the target about the transferor
18986 
18987    "Any REFER request has to be appropriately authenticated.".
18988    
18989    We can't destroy dialogs, since we want the call to continue.
18990    
18991    */
18992 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock)
18993 {
18994    struct sip_dual current;   /* Chan1: Call between asterisk and transferer */
18995                /* Chan2: Call between asterisk and transferee */
18996 
18997    int res = 0;
18998    current.req.data = NULL;
18999 
19000    if (req->debug)
19001       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");
19002 
19003    if (!p->owner) {
19004       /* This is a REFER outside of an existing SIP dialog */
19005       /* We can't handle that, so decline it */
19006       ast_debug(3, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
19007       transmit_response(p, "603 Declined (No dialog)", req);
19008       if (!req->ignore) {
19009          append_history(p, "Xfer", "Refer failed. Outside of dialog.");
19010          sip_alreadygone(p);
19011          p->needdestroy = 1;
19012       }
19013       return 0;
19014    }  
19015 
19016 
19017    /* Check if transfer is allowed from this device */
19018    if (p->allowtransfer == TRANSFER_CLOSED ) {
19019       /* Transfer not allowed, decline */
19020       transmit_response(p, "603 Declined (policy)", req);
19021       append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
19022       /* Do not destroy SIP session */
19023       return 0;
19024    }
19025 
19026    if (!req->ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
19027       /* Already have a pending REFER */  
19028       transmit_response(p, "491 Request pending", req);
19029       append_history(p, "Xfer", "Refer failed. Request pending.");
19030       return 0;
19031    }
19032 
19033    /* Allocate memory for call transfer data */
19034    if (!p->refer && !sip_refer_allocate(p)) {
19035       transmit_response(p, "500 Internal Server Error", req);
19036       append_history(p, "Xfer", "Refer failed. Memory allocation error.");
19037       return -3;
19038    }
19039 
19040    res = get_refer_info(p, req); /* Extract headers */
19041 
19042    p->refer->status = REFER_SENT;
19043 
19044    if (res != 0) {
19045       switch (res) {
19046       case -2: /* Syntax error */
19047          transmit_response(p, "400 Bad Request (Refer-to missing)", req);
19048          append_history(p, "Xfer", "Refer failed. Refer-to missing.");
19049          if (req->debug)
19050             ast_debug(1, "SIP transfer to black hole can't be handled (no refer-to: )\n");
19051          break;
19052       case -3:
19053          transmit_response(p, "603 Declined (Non sip: uri)", req);
19054          append_history(p, "Xfer", "Refer failed. Non SIP uri");
19055          if (req->debug)
19056             ast_debug(1, "SIP transfer to non-SIP uri denied\n");
19057          break;
19058       default:
19059          /* Refer-to extension not found, fake a failed transfer */
19060          transmit_response(p, "202 Accepted", req);
19061          append_history(p, "Xfer", "Refer failed. Bad extension.");
19062          transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
19063          ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
19064          if (req->debug)
19065             ast_debug(1, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
19066          break;
19067       } 
19068       return 0;
19069    }
19070    if (ast_strlen_zero(p->context))
19071       ast_string_field_set(p, context, default_context);
19072 
19073    /* If we do not support SIP domains, all transfers are local */
19074    if (allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
19075       p->refer->localtransfer = 1;
19076       if (sipdebug)
19077          ast_debug(3, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
19078    } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
19079       /* This PBX doesn't bother with SIP domains or domain is local, so this transfer is local */
19080       p->refer->localtransfer = 1;
19081    } else if (sipdebug)
19082          ast_debug(3, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
19083    
19084    /* Is this a repeat of a current request? Ignore it */
19085    /* Don't know what else to do right now. */
19086    if (req->ignore) 
19087       return res;
19088 
19089    /* If this is a blind transfer, we have the following
19090    channels to work with:
19091    - chan1, chan2: The current call between transferer and transferee (2 channels)
19092    - target_channel: A new call from the transferee to the target (1 channel)
19093    We need to stay tuned to what happens in order to be able
19094    to bring back the call to the transferer */
19095 
19096    /* If this is a attended transfer, we should have all call legs within reach:
19097    - chan1, chan2: The call between the transferer and transferee (2 channels)
19098    - target_channel, targetcall_pvt: The call between the transferer and the target (2 channels)
19099    We want to bridge chan2 with targetcall_pvt!
19100    
19101    The replaces call id in the refer message points
19102    to the call leg between Asterisk and the transferer.
19103    So we need to connect the target and the transferee channel
19104    and hangup the two other channels silently 
19105    
19106    If the target is non-local, the call ID could be on a remote
19107    machine and we need to send an INVITE with replaces to the
19108    target. We basically handle this as a blind transfer
19109    and let the sip_call function catch that we need replaces
19110    header in the INVITE.
19111    */
19112 
19113 
19114    /* Get the transferer's channel */
19115    current.chan1 = p->owner;
19116 
19117    /* Find the other part of the bridge (2) - transferee */
19118    current.chan2 = ast_bridged_channel(current.chan1);
19119    
19120    if (sipdebug)
19121       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>");
19122 
19123    if (!current.chan2 && !p->refer->attendedtransfer) {
19124       /* No bridged channel, propably IVR or echo or similar... */
19125       /* Guess we should masquerade or something here */
19126       /* Until we figure it out, refuse transfer of such calls */
19127       if (sipdebug)
19128          ast_debug(3, "Refused SIP transfer on non-bridged channel.\n");
19129       p->refer->status = REFER_FAILED;
19130       append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
19131       transmit_response(p, "603 Declined", req);
19132       return -1;
19133    }
19134 
19135    if (current.chan2) {
19136       if (sipdebug)
19137          ast_debug(4, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);
19138 
19139       ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
19140    }
19141 
19142    ast_set_flag(&p->flags[0], SIP_GOTREFER); 
19143 
19144    /* Attended transfer: Find all call legs and bridge transferee with target*/
19145    if (p->refer->attendedtransfer) {
19146       if ((res = local_attended_transfer(p, &current, req, seqno)))
19147          return res; /* We're done with the transfer */
19148       /* Fall through for remote transfers that we did not find locally */
19149       if (sipdebug)
19150          ast_debug(4, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
19151       /* Fallthrough if we can't find the call leg internally */
19152    }
19153 
19154 
19155    /* Parking a call */
19156    if (p->refer->localtransfer && !strcmp(p->refer->refer_to, ast_parking_ext())) {
19157       /* Must release c's lock now, because it will not longer be accessible after the transfer! */
19158       *nounlock = 1;
19159       ast_channel_unlock(current.chan1);
19160       copy_request(&current.req, req);
19161       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
19162       p->refer->status = REFER_200OK;
19163       append_history(p, "Xfer", "REFER to call parking.");
19164       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",
19165          current.chan1->name,
19166          current.chan1->uniqueid,
19167          p->callid,
19168          current.chan2->name,
19169          current.chan2->uniqueid,
19170          p->refer->refer_to);
19171       if (sipdebug)
19172          ast_debug(4, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
19173       sip_park(current.chan2, current.chan1, req, seqno);
19174       return res;
19175    } 
19176 
19177    /* Blind transfers and remote attended xfers */
19178    transmit_response(p, "202 Accepted", req);
19179 
19180    if (current.chan1 && current.chan2) {
19181       ast_debug(3, "chan1->name: %s\n", current.chan1->name);
19182       pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
19183    }
19184    if (current.chan2) {
19185       pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
19186       pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", p->refer->refer_to_domain);
19187       pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
19188       /* One for the new channel */
19189       pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
19190       /* Attended transfer to remote host, prepare headers for the INVITE */
19191       if (p->refer->referred_by) 
19192          pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", p->refer->referred_by);
19193    }
19194    /* Generate a Replaces string to be used in the INVITE during attended transfer */
19195    if (!ast_strlen_zero(p->refer->replaces_callid)) {
19196       char tempheader[SIPBUFSIZE];
19197       snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid, 
19198             p->refer->replaces_callid_totag ? ";to-tag=" : "", 
19199             p->refer->replaces_callid_totag, 
19200             p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
19201             p->refer->replaces_callid_fromtag);
19202       if (current.chan2)
19203          pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
19204    }
19205    /* Must release lock now, because it will not longer
19206       be accessible after the transfer! */
19207    *nounlock = 1;
19208    ast_channel_unlock(current.chan1);
19209 
19210    /* Connect the call */
19211 
19212    /* FAKE ringing if not attended transfer */
19213    if (!p->refer->attendedtransfer)
19214       transmit_notify_with_sipfrag(p, seqno, "183 Ringing", FALSE); 
19215       
19216    /* For blind transfer, this will lead to a new call */
19217    /* For attended transfer to remote host, this will lead to
19218       a new SIP call with a replaces header, if the dial plan allows it 
19219    */
19220    if (!current.chan2) {
19221       /* We have no bridge, so we're talking with Asterisk somehow */
19222       /* We need to masquerade this call */
19223       /* What to do to fix this situation:
19224          * Set up the new call in a new channel 
19225          * Let the new channel masq into this channel
19226          Please add that code here :-)
19227       */
19228       p->refer->status = REFER_FAILED;
19229       transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
19230       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
19231       append_history(p, "Xfer", "Refer failed (only bridged calls).");
19232       return -1;
19233    }
19234    ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);   /* Delay hangup */
19235 
19236 
19237    /* For blind transfers, move the call to the new extensions. For attended transfers on multiple
19238       servers - generate an INVITE with Replaces. Either way, let the dial plan decided  */
19239    res = ast_async_goto(current.chan2, p->refer->refer_to_context, p->refer->refer_to, 1);
19240 
19241    if (!res) {
19242       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",
19243          current.chan1->name,
19244          current.chan1->uniqueid,
19245          p->callid,
19246          current.chan2->name,
19247          current.chan2->uniqueid,
19248          p->refer->refer_to, p->refer->refer_to_context);
19249       /* Success  - we have a new channel */
19250       ast_debug(3, "%s transfer succeeded. Telling transferer.\n", p->refer->attendedtransfer? "Attended" : "Blind");
19251       transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
19252       if (p->refer->localtransfer)
19253          p->refer->status = REFER_200OK;
19254       if (p->owner)
19255          p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
19256       append_history(p, "Xfer", "Refer succeeded.");
19257       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
19258       /* Do not hangup call, the other side do that when we say 200 OK */
19259       /* We could possibly implement a timer here, auto congestion */
19260       res = 0;
19261    } else {
19262       ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Don't delay hangup */
19263       ast_debug(3, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
19264       append_history(p, "Xfer", "Refer failed.");
19265       /* Failure of some kind */
19266       p->refer->status = REFER_FAILED;
19267       transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
19268       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
19269       res = -1;
19270    }
19271    return res;
19272 }
19273 
19274 /*! \brief Handle incoming CANCEL request */
19275 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
19276 {
19277       
19278    check_via(p, req);
19279    sip_alreadygone(p);
19280 
19281    /* At this point, we could have cancelled the invite at the same time
19282       as the other side sends a CANCEL. Our final reply with error code
19283       might not have been received by the other side before the CANCEL
19284       was sent, so let's just give up retransmissions and waiting for
19285       ACK on our error code. The call is hanging up any way. */
19286    if (p->invitestate == INV_TERMINATED)
19287       __sip_pretend_ack(p);
19288    else
19289       p->invitestate = INV_CANCELLED;
19290    
19291    if (p->owner && p->owner->_state == AST_STATE_UP) {
19292       /* This call is up, cancel is ignored, we need a bye */
19293       transmit_response(p, "200 OK", req);
19294       ast_debug(1, "Got CANCEL on an answered call. Ignoring... \n");
19295       return 0;
19296    }
19297 
19298    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) 
19299       update_call_counter(p, DEC_CALL_LIMIT);
19300 
19301    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
19302    if (p->owner)
19303       ast_queue_hangup(p->owner);
19304    else
19305       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19306    if (p->initreq.len > 0) {
19307       struct sip_pkt *pkt, *prev_pkt;
19308       /* If the CANCEL we are receiving is a retransmission, and we already have scheduled
19309        * a reliable 487, then we don't want to schedule another one on top of the previous
19310        * one.
19311        *
19312        * As odd as this may sound, we can't rely on the previously-transmitted "reliable" 
19313        * response in this situation. What if we've sent all of our reliable responses 
19314        * already and now all of a sudden, we get this second CANCEL?
19315        *
19316        * The only way to do this correctly is to cancel our previously-scheduled reliably-
19317        * transmitted response and send a new one in its place.
19318        */
19319       for (pkt = p->packets, prev_pkt = NULL; pkt; prev_pkt = pkt, pkt = pkt->next) {
19320          if (pkt->seqno == p->lastinvite && pkt->response_code == 487) {
19321             AST_SCHED_DEL(sched, pkt->retransid);
19322             UNLINK(pkt, p->packets, prev_pkt);
19323             ast_free(pkt);
19324             break;
19325          }
19326       }
19327       transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
19328       transmit_response(p, "200 OK", req);
19329       return 1;
19330    } else {
19331       transmit_response(p, "481 Call Leg Does Not Exist", req);
19332       return 0;
19333    }
19334 }
19335 
19336 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen)
19337 {
19338    struct sip_pvt *p = chan->tech_pvt;
19339    char *all = "", *parse = ast_strdupa(preparse);
19340    int res = 0;
19341    AST_DECLARE_APP_ARGS(args,
19342       AST_APP_ARG(param);
19343       AST_APP_ARG(type);
19344       AST_APP_ARG(field);
19345    );
19346    AST_STANDARD_APP_ARGS(args, parse);
19347 
19348    /* Sanity check */
19349    if (!IS_SIP_TECH(chan->tech)) {
19350       ast_log(LOG_ERROR, "Cannot call %s on a non-SIP channel\n", funcname);
19351       return 0;
19352    }
19353 
19354    memset(buf, 0, buflen);
19355 
19356    if (p == NULL) {
19357       return -1;
19358    }
19359 
19360    if (!strcasecmp(args.param, "peerip")) {
19361       ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", buflen);
19362    } else if (!strcasecmp(args.param, "recvip")) {
19363       ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", buflen);
19364    } else if (!strcasecmp(args.param, "from")) {
19365       ast_copy_string(buf, p->from, buflen);
19366    } else if (!strcasecmp(args.param, "uri")) {
19367       ast_copy_string(buf, p->uri, buflen);
19368    } else if (!strcasecmp(args.param, "useragent")) {
19369       ast_copy_string(buf, p->useragent, buflen);
19370    } else if (!strcasecmp(args.param, "peername")) {
19371       ast_copy_string(buf, p->peername, buflen);
19372    } else if (!strcasecmp(args.param, "t38passthrough")) {
19373       ast_copy_string(buf, (p->t38.state == T38_DISABLED) ? "0" : "1", buflen);
19374    } else if (!strcasecmp(args.param, "rtpdest")) {
19375       struct sockaddr_in sin;
19376 
19377       if (ast_strlen_zero(args.type))
19378          args.type = "audio";
19379 
19380       if (!strcasecmp(args.type, "audio"))
19381          ast_rtp_get_peer(p->rtp, &sin);
19382       else if (!strcasecmp(args.type, "video"))
19383          ast_rtp_get_peer(p->vrtp, &sin);
19384       else if (!strcasecmp(args.type, "text"))
19385          ast_rtp_get_peer(p->trtp, &sin);
19386       else
19387          return -1;
19388 
19389       snprintf(buf, buflen, "%s:%d", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
19390    } else if (!strcasecmp(args.param, "rtpqos")) {
19391       struct ast_rtp_quality qos;
19392       struct ast_rtp *rtp = p->rtp;
19393       
19394       memset(&qos, 0, sizeof(qos));
19395 
19396       if (ast_strlen_zero(args.type))
19397          args.type = "audio";
19398       if (ast_strlen_zero(args.field))
19399          args.field = "all";
19400       
19401       if (!strcasecmp(args.type, "AUDIO")) {
19402          all = ast_rtp_get_quality(rtp = p->rtp, &qos, RTPQOS_SUMMARY);
19403       } else if (!strcasecmp(args.type, "VIDEO")) {
19404          all = ast_rtp_get_quality(rtp = p->vrtp, &qos, RTPQOS_SUMMARY);
19405       } else if (!strcasecmp(args.type, "TEXT")) {
19406          all = ast_rtp_get_quality(rtp = p->trtp, &qos, RTPQOS_SUMMARY);
19407       } else {
19408          return -1;
19409       }
19410       
19411       if (!strcasecmp(args.field, "local_ssrc"))
19412          snprintf(buf, buflen, "%u", qos.local_ssrc);
19413       else if (!strcasecmp(args.field, "local_lostpackets"))
19414          snprintf(buf, buflen, "%u", qos.local_lostpackets);
19415       else if (!strcasecmp(args.field, "local_jitter"))
19416          snprintf(buf, buflen, "%.0f", qos.local_jitter * 1000.0);
19417       else if (!strcasecmp(args.field, "local_count"))
19418          snprintf(buf, buflen, "%u", qos.local_count);
19419       else if (!strcasecmp(args.field, "remote_ssrc"))
19420          snprintf(buf, buflen, "%u", qos.remote_ssrc);
19421       else if (!strcasecmp(args.field, "remote_lostpackets"))
19422          snprintf(buf, buflen, "%u", qos.remote_lostpackets);
19423       else if (!strcasecmp(args.field, "remote_jitter"))
19424          snprintf(buf, buflen, "%.0f", qos.remote_jitter * 1000.0);
19425       else if (!strcasecmp(args.field, "remote_count"))
19426          snprintf(buf, buflen, "%u", qos.remote_count);
19427       else if (!strcasecmp(args.field, "rtt"))
19428          snprintf(buf, buflen, "%.0f", qos.rtt * 1000.0);
19429       else if (!strcasecmp(args.field, "all"))
19430          ast_copy_string(buf, all, buflen);
19431       else if (!ast_rtp_get_qos(rtp, args.field, buf, buflen))
19432           ;
19433       else {
19434          ast_log(LOG_WARNING, "Unrecognized argument '%s' to %s\n", preparse, funcname);
19435          return -1;
19436       }
19437    } else {
19438       res = -1;
19439    }
19440    return res;
19441 }
19442 
19443 /*! \brief Handle incoming BYE request */
19444 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
19445 {
19446    struct ast_channel *c=NULL;
19447    int res;
19448    struct ast_channel *bridged_to;
19449    
19450    /* If we have an INCOMING invite that we haven't answered, terminate that transaction */
19451    if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !req->ignore) {
19452       transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
19453    }
19454 
19455    __sip_pretend_ack(p);
19456 
19457    p->invitestate = INV_TERMINATED;
19458 
19459    copy_request(&p->initreq, req);
19460    if (sipdebug)
19461       ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
19462    check_via(p, req);
19463    sip_alreadygone(p);
19464 
19465    /* Get RTCP quality before end of call */
19466    if (p->do_history || p->owner) {
19467       struct ast_channel *bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
19468       char *videoqos, *textqos;
19469 
19470       /* We need to get the lock on bridge because ast_rtp_set_vars will attempt
19471        * to lock the bridge. This may get hairy...
19472        */
19473       while (bridge && ast_channel_trylock(bridge)) {
19474          ast_channel_unlock(p->owner);
19475          do {
19476             /* Can't use DEADLOCK_AVOIDANCE since p is an ao2 object */
19477             sip_pvt_unlock(p);
19478             usleep(1);
19479             sip_pvt_lock(p);
19480          } while (p->owner && ast_channel_trylock(p->owner));
19481          bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
19482       }
19483 
19484       if (p->rtp) {  
19485          if (p->do_history) {
19486             char *audioqos,
19487                  *audioqos_jitter,
19488                  *audioqos_loss,
19489                  *audioqos_rtt;
19490 
19491             audioqos        = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_SUMMARY);
19492             audioqos_jitter = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_JITTER);
19493             audioqos_loss   = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_LOSS);
19494             audioqos_rtt    = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_RTT);
19495 
19496             append_history(p, "RTCPaudio", "Quality:%s", audioqos);
19497             append_history(p, "RTCPaudioJitter", "Quality:%s", audioqos_jitter);
19498             append_history(p, "RTCPaudioLoss", "Quality:%s", audioqos_loss);
19499             append_history(p, "RTCPaudioRTT", "Quality:%s", audioqos_rtt);
19500          }
19501          
19502          if (p->owner) {
19503             ast_rtp_set_vars(p->owner, p->rtp);
19504          }
19505       }
19506 
19507       if (bridge) {
19508          struct sip_pvt *q = bridge->tech_pvt;
19509 
19510          if (IS_SIP_TECH(bridge->tech) && q && q->rtp)
19511             ast_rtp_set_vars(bridge, q->rtp);
19512          ast_channel_unlock(bridge);
19513       }
19514 
19515       if (p->vrtp) {
19516          videoqos = ast_rtp_get_quality(p->vrtp, NULL, RTPQOS_SUMMARY);
19517          if (p->do_history)
19518             append_history(p, "RTCPvideo", "Quality:%s", videoqos);
19519          if (p->owner)
19520             pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", videoqos);
19521       }
19522 
19523       if (p->trtp) {
19524          textqos = ast_rtp_get_quality(p->trtp, NULL, RTPQOS_SUMMARY);
19525          if (p->do_history)
19526             append_history(p, "RTCPtext", "Quality:%s", textqos);
19527          if (p->owner)
19528             pbx_builtin_setvar_helper(p->owner, "RTPTEXTQOS", textqos);
19529       }
19530    }
19531 
19532    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
19533    stop_session_timer(p); /* Stop Session-Timer */
19534 
19535    if (!ast_strlen_zero(get_header(req, "Also"))) {
19536       ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method.  Ask vendor to support REFER instead\n",
19537          ast_inet_ntoa(p->recv.sin_addr));
19538       if (ast_strlen_zero(p->context))
19539          ast_string_field_set(p, context, default_context);
19540       res = get_also_info(p, req);
19541       if (!res) {
19542          c = p->owner;
19543          if (c) {
19544             bridged_to = ast_bridged_channel(c);
19545             if (bridged_to) {
19546                /* Don't actually hangup here... */
19547                ast_queue_control(c, AST_CONTROL_UNHOLD);
19548                ast_async_goto(bridged_to, p->context, p->refer->refer_to, 1);
19549             } else
19550                ast_queue_hangup(p->owner);
19551          }
19552       } else {
19553          ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_inet_ntoa(p->recv.sin_addr));
19554          if (p->owner)
19555             ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
19556       }
19557    } else if (p->owner) {
19558       ast_queue_hangup(p->owner);
19559       ast_debug(3, "Received bye, issuing owner hangup\n");
19560    } else {
19561       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19562       ast_debug(3, "Received bye, no owner, selfdestruct soon.\n");
19563    }
19564    ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
19565    transmit_response(p, "200 OK", req);
19566 
19567    return 1;
19568 }
19569 
19570 /*! \brief Handle incoming MESSAGE request */
19571 static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
19572 {
19573    if (!req->ignore) {
19574       if (req->debug)
19575          ast_verbose("Receiving message!\n");
19576       receive_message(p, req);
19577    } else
19578       transmit_response(p, "202 Accepted", req);
19579    return 1;
19580 }
19581 
19582 static void add_peer_mwi_subs(struct sip_peer *peer)
19583 {
19584    struct sip_mailbox *mailbox;
19585 
19586    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
19587       mailbox->event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, peer,
19588          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
19589          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
19590          AST_EVENT_IE_END);
19591    }
19592 }
19593 
19594 /*! \brief  Handle incoming SUBSCRIBE request */
19595 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
19596 {
19597    int gotdest = 0;
19598    int res = 0;
19599    int firststate = AST_EXTENSION_REMOVED;
19600    struct sip_peer *authpeer = NULL;
19601    const char *eventheader = get_header(req, "Event");   /* Get Event package name */
19602    const char *acceptheader = get_header(req, "Accept");
19603    int resubscribe = (p->subscribed != NONE);
19604    char *temp, *event;
19605    struct ao2_iterator i;
19606 
19607    if (p->initreq.headers) {  
19608       /* We already have a dialog */
19609       if (p->initreq.method != SIP_SUBSCRIBE) {
19610          /* This is a SUBSCRIBE within another SIP dialog, which we do not support */
19611          /* For transfers, this could happen, but since we haven't seen it happening, let us just refuse this */
19612          transmit_response(p, "403 Forbidden (within dialog)", req);
19613          /* Do not destroy session, since we will break the call if we do */
19614          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);
19615          return 0;
19616       } else if (req->debug) {
19617          if (resubscribe)
19618             ast_debug(1, "Got a re-subscribe on existing subscription %s\n", p->callid);
19619          else
19620             ast_debug(1, "Got a new subscription %s (possibly with auth)\n", p->callid);
19621       }
19622    }
19623 
19624    /* Check if we have a global disallow setting on subscriptions. 
19625       if so, we don't have to check peer settings after auth, which saves a lot of processing
19626    */
19627    if (!global_allowsubscribe) {
19628       transmit_response(p, "403 Forbidden (policy)", req);
19629       p->needdestroy = 1;
19630       return 0;
19631    }
19632 
19633    if (!req->ignore && !resubscribe) { /* Set up dialog, new subscription */
19634       const char *to = get_header(req, "To");
19635       char totag[128];
19636 
19637       /* Check to see if a tag was provided, if so this is actually a resubscription of a dialog we no longer know about */
19638       if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
19639          if (req->debug)
19640             ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
19641          transmit_response(p, "481 Subscription does not exist", req);
19642          p->needdestroy = 1;
19643          return 0;
19644       }
19645 
19646       /* Use this as the basis */
19647       if (req->debug)
19648          ast_verbose("Creating new subscription\n");
19649 
19650       copy_request(&p->initreq, req);
19651       if (sipdebug)
19652          ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
19653       check_via(p, req);
19654       build_route(p, req, 0);
19655    } else if (req->debug && req->ignore)
19656       ast_verbose("Ignoring this SUBSCRIBE request\n");
19657 
19658    /* Find parameters to Event: header value and remove them for now */
19659    if (ast_strlen_zero(eventheader)) {
19660       transmit_response(p, "489 Bad Event", req);
19661       ast_debug(2, "Received SIP subscribe for unknown event package: <none>\n");
19662       p->needdestroy = 1;
19663       return 0;
19664    }
19665 
19666    if ( (strchr(eventheader, ';'))) {
19667       event = ast_strdupa(eventheader);   /* Since eventheader is a const, we can't change it */
19668       temp = strchr(event, ';');       
19669       *temp = '\0';           /* Remove any options for now */
19670                      /* We might need to use them later :-) */
19671    } else
19672       event = (char *) eventheader;    /* XXX is this legal ? */
19673 
19674    /* Handle authentication */
19675    res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, sin, &authpeer);
19676    /* if an authentication response was sent, we are done here */
19677    if (res == AUTH_CHALLENGE_SENT)  /* authpeer = NULL here */
19678       return 0;
19679    if (res < 0) {
19680       if (res == AUTH_FAKE_AUTH) {
19681          ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
19682          transmit_fake_auth_response(p, SIP_SUBSCRIBE, req, XMIT_UNRELIABLE);
19683       } else {
19684          ast_log(LOG_NOTICE, "Failed to authenticate device %s for SUBSCRIBE\n", get_header(req, "From"));
19685          transmit_response_reliable(p, "403 Forbidden", req);
19686       }
19687       p->needdestroy = 1;
19688       return 0;
19689    }
19690 
19691    /* At this point, authpeer cannot be NULL. Remember we hold a reference,
19692     * so we must release it when done.
19693     * XXX must remove all the checks for authpeer == NULL.
19694     */
19695 
19696    /* Check if this device  is allowed to subscribe at all */
19697    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
19698       transmit_response(p, "403 Forbidden (policy)", req);
19699       p->needdestroy = 1;
19700       if (authpeer)
19701          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 1)");
19702       return 0;
19703    }
19704 
19705    if (strcmp(event, "message-summary")) {
19706       /* Get destination right away */
19707       gotdest = get_destination(p, NULL);
19708    }
19709 
19710    /* Get full contact header - this needs to be used as a request URI in NOTIFY's */
19711    parse_ok_contact(p, req);
19712 
19713    build_contact(p);
19714    if (gotdest) {
19715       transmit_response(p, "404 Not Found", req);
19716       p->needdestroy = 1;
19717       if (authpeer)
19718          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
19719       return 0;
19720    }
19721 
19722    /* Initialize tag for new subscriptions */   
19723    if (ast_strlen_zero(p->tag))
19724       make_our_tag(p->tag, sizeof(p->tag));
19725 
19726    if (!strcmp(event, "presence") || !strcmp(event, "dialog")) { /* Presence, RFC 3842 */
19727       unsigned int pidf_xml;
19728 
19729       if (authpeer)  /* We do not need the authpeer any more */
19730          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
19731 
19732       /* Header from Xten Eye-beam Accept: multipart/related, application/rlmi+xml, application/pidf+xml, application/xpidf+xml */
19733 
19734       pidf_xml = strstr(acceptheader, "application/pidf+xml") ? 1 : 0;
19735 
19736       /* Older versions of Polycom firmware will claim pidf+xml, but really
19737        * they only support xpidf+xml. */
19738       if (pidf_xml && strstr(p->useragent, "Polycom")) {
19739          p->subscribed = XPIDF_XML;
19740       } else if (pidf_xml) {
19741          p->subscribed = PIDF_XML;         /* RFC 3863 format */
19742       } else if (strstr(acceptheader, "application/dialog-info+xml")) {
19743          p->subscribed = DIALOG_INFO_XML;
19744          /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
19745       } else if (strstr(acceptheader, "application/cpim-pidf+xml")) {
19746          p->subscribed = CPIM_PIDF_XML;    /* RFC 3863 format */
19747       } else if (strstr(acceptheader, "application/xpidf+xml")) {
19748          p->subscribed = XPIDF_XML;        /* Early pre-RFC 3863 format with MSN additions (Microsoft Messenger) */
19749       } else if (ast_strlen_zero(acceptheader)) {
19750          if (p->subscribed == NONE) { /* if the subscribed field is not already set, and there is no accept header... */
19751             transmit_response(p, "489 Bad Event", req);
19752   
19753             ast_log(LOG_WARNING, "SUBSCRIBE failure: no Accept header: pvt: stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
19754                p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
19755             p->needdestroy = 1;
19756             return 0;
19757          }
19758          /* if p->subscribed is non-zero, then accept is not obligatory; according to rfc 3265 section 3.1.3, at least.
19759             so, we'll just let it ride, keeping the value from a previous subscription, and not abort the subscription */
19760       } else {
19761          /* Can't find a format for events that we know about */
19762          char mybuf[200];
19763          snprintf(mybuf, sizeof(mybuf), "489 Bad Event (format %s)", acceptheader);
19764          transmit_response(p, mybuf, req);
19765  
19766          ast_log(LOG_WARNING, "SUBSCRIBE failure: unrecognized format: '%s' pvt: subscribed: %d, stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
19767             acceptheader, (int)p->subscribed, p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
19768          p->needdestroy = 1;
19769          return 0;
19770       }
19771    } else if (!strcmp(event, "message-summary")) { 
19772       if (!ast_strlen_zero(acceptheader) && strcmp(acceptheader, "application/simple-message-summary")) {
19773          /* Format requested that we do not support */
19774          transmit_response(p, "406 Not Acceptable", req);
19775          ast_debug(2, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
19776          p->needdestroy = 1;
19777          if (authpeer)
19778             unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 3)");
19779          return 0;
19780       }
19781       /* Looks like they actually want a mailbox status 
19782         This version of Asterisk supports mailbox subscriptions
19783         The subscribed URI needs to exist in the dial plan
19784         In most devices, this is configurable to the voicemailmain extension you use
19785       */
19786       if (!authpeer || AST_LIST_EMPTY(&authpeer->mailboxes)) {
19787          transmit_response(p, "404 Not found (no mailbox)", req);
19788          p->needdestroy = 1;
19789          ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", authpeer->name);
19790          if (authpeer)
19791             unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 4)");
19792          return 0;
19793       }
19794 
19795       p->subscribed = MWI_NOTIFICATION;
19796       if (ast_test_flag(&authpeer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY)) {
19797          add_peer_mwi_subs(authpeer);
19798       }
19799       if (authpeer->mwipvt && authpeer->mwipvt != p) {   /* Destroy old PVT if this is a new one */
19800          /* We only allow one subscription per peer */
19801          dialog_unlink_all(authpeer->mwipvt, TRUE, TRUE);
19802          authpeer->mwipvt = dialog_unref(authpeer->mwipvt, "unref dialog authpeer->mwipvt");
19803          /* sip_destroy(authpeer->mwipvt); */
19804       }
19805       if (authpeer->mwipvt)
19806          dialog_unref(authpeer->mwipvt, "Unref previously stored mwipvt dialog pointer");
19807       authpeer->mwipvt = dialog_ref(p, "setting peers' mwipvt to p");      /* Link from peer to pvt UH- should this be dialog_ref()? */
19808       if (p->relatedpeer)
19809          unref_peer(p->relatedpeer, "Unref previously stored relatedpeer ptr");
19810       p->relatedpeer = ref_peer(authpeer, "setting dialog's relatedpeer pointer");  /* already refcounted...Link from pvt to peer UH- should this be dialog_ref()? */
19811       /* Do not release authpeer here */
19812    } else { /* At this point, Asterisk does not understand the specified event */
19813       transmit_response(p, "489 Bad Event", req);
19814       ast_debug(2, "Received SIP subscribe for unknown event package: %s\n", event);
19815       p->needdestroy = 1;
19816       if (authpeer)
19817          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 5)");
19818       return 0;
19819    }
19820 
19821    /* Add subscription for extension state from the PBX core */
19822    if (p->subscribed != MWI_NOTIFICATION && !resubscribe) {
19823       if (p->stateid > -1) {
19824          ast_extension_state_del(p->stateid, cb_extensionstate);
19825          /* we need to dec the refcount, now that the extensionstate is removed */
19826          dialog_unref(p, "the extensionstate containing this dialog ptr was deleted");
19827       }
19828       p->stateid = ast_extension_state_add(p->context, p->exten, cb_extensionstate, dialog_ref(p,"copying dialog ptr into extension state struct"));
19829    }
19830 
19831    if (!req->ignore && p)
19832       p->lastinvite = seqno;
19833    if (p && !p->needdestroy) {
19834       p->expiry = atoi(get_header(req, "Expires"));
19835 
19836       /* check if the requested expiry-time is within the approved limits from sip.conf */
19837       if (p->expiry > max_expiry)
19838          p->expiry = max_expiry;
19839       if (p->expiry < min_expiry && p->expiry > 0)
19840          p->expiry = min_expiry;
19841 
19842       if (sipdebug) {
19843          if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
19844             ast_debug(2, "Adding subscription for mailbox notification - peer %s\n", p->relatedpeer->name);
19845          else
19846             ast_debug(2, "Adding subscription for extension %s context %s for peer %s\n", p->exten, p->context, p->username);
19847       }
19848       if (p->autokillid > -1 && sip_cancel_destroy(p))   /* Remove subscription expiry for renewals */
19849          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
19850       if (p->expiry > 0)
19851          sip_scheddestroy(p, (p->expiry + 10) * 1000);   /* Set timer for destruction of call at expiration */
19852 
19853       if (p->subscribed == MWI_NOTIFICATION) {
19854          ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
19855          transmit_response(p, "200 OK", req);
19856          if (p->relatedpeer) {   /* Send first notification */
19857             ao2_lock(p->relatedpeer); /* was WRLOCK */
19858             sip_send_mwi_to_peer(p->relatedpeer, NULL, 0);
19859             ao2_unlock(p->relatedpeer);
19860          }
19861       } else {
19862          struct sip_pvt *p_old;
19863 
19864          if ((firststate = ast_extension_state(NULL, p->context, p->exten)) < 0) {
19865 
19866             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));
19867             transmit_response(p, "404 Not found", req);
19868             p->needdestroy = 1;
19869             return 0;
19870          }
19871          ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
19872          transmit_response(p, "200 OK", req);
19873          transmit_state_notify(p, firststate, 1, FALSE); /* Send first notification */
19874          append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
19875          /* hide the 'complete' exten/context in the refer_to field for later display */
19876          ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
19877 
19878          /* remove any old subscription from this peer for the same exten/context,
19879          as the peer has obviously forgotten about it and it's wasteful to wait
19880          for it to expire and send NOTIFY messages to the peer only to have them
19881          ignored (or generate errors)
19882          */
19883          i = ao2_iterator_init(dialogs, 0);
19884 
19885          while ((p_old = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
19886             if (p_old == p) {
19887                ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before continue");
19888                continue;
19889             }
19890             if (p_old->initreq.method != SIP_SUBSCRIBE) {
19891                ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before continue");
19892                continue;
19893             }
19894             if (p_old->subscribed == NONE) {
19895                ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before continue");
19896                continue;
19897             }
19898             sip_pvt_lock(p_old);
19899             if (!strcmp(p_old->username, p->username)) {
19900                if (!strcmp(p_old->exten, p->exten) &&
19901                    !strcmp(p_old->context, p->context)) {
19902                   p_old->needdestroy = 1;
19903                   sip_pvt_unlock(p_old);
19904                   ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before break");
19905                   break;
19906                }
19907             }
19908             sip_pvt_unlock(p_old);
19909             ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next");
19910          }
19911       }
19912       if (!p->expiry)
19913          p->needdestroy = 1;
19914    }
19915    return 1;
19916 }
19917 
19918 /*! \brief Handle incoming REGISTER request */
19919 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e)
19920 {
19921    enum check_auth_result res;
19922 
19923    /* Use this as the basis */
19924    copy_request(&p->initreq, req);
19925    if (sipdebug)
19926       ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
19927    check_via(p, req);
19928    if ((res = register_verify(p, sin, req, e)) < 0) {
19929       const char *reason;
19930 
19931       switch (res) {
19932       case AUTH_SECRET_FAILED:
19933          reason = "Wrong password";
19934          break;
19935       case AUTH_USERNAME_MISMATCH:
19936          reason = "Username/auth name mismatch";
19937          break;
19938       case AUTH_NOT_FOUND:
19939          reason = "No matching peer found";
19940          break;
19941       case AUTH_UNKNOWN_DOMAIN:
19942          reason = "Not a local domain";
19943          break;
19944       case AUTH_PEER_NOT_DYNAMIC:
19945          reason = "Peer is not supposed to register";
19946          break;
19947       case AUTH_ACL_FAILED:
19948          reason = "Device does not match ACL";
19949          break;
19950       case AUTH_BAD_TRANSPORT:
19951          reason = "Device not configured to use this transport type";
19952          break;
19953       default:
19954          reason = "Unknown failure";
19955          break;
19956       }
19957       ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
19958          get_header(req, "To"), ast_inet_ntoa(sin->sin_addr),
19959          reason);
19960       append_history(p, "RegRequest", "Failed : Account %s : %s", get_header(req, "To"), reason);
19961    } else
19962       append_history(p, "RegRequest", "Succeeded : Account %s", get_header(req, "To"));
19963 
19964    if (res < 1) {
19965       /* Destroy the session, but keep us around for just a bit in case they don't
19966          get our 200 OK */
19967       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19968    }
19969    return res;
19970 }
19971 
19972 /*! \brief Handle incoming SIP requests (methods) 
19973 \note This is where all incoming requests go first   */
19974 /* called with p and p->owner locked */
19975 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock)
19976 {
19977    /* Called with p->lock held, as well as p->owner->lock if appropriate, keeping things
19978       relatively static */
19979    const char *cmd;
19980    const char *cseq;
19981    const char *useragent;
19982    int seqno;
19983    int len;
19984    int respid;
19985    int res = 0;
19986    int debug = sip_debug_test_pvt(p);
19987    char *e;
19988    int error = 0;
19989 
19990    /* Get Method and Cseq */
19991    cseq = get_header(req, "Cseq");
19992    cmd = REQ_OFFSET_TO_STR(req, header[0]);
19993 
19994    /* Must have Cseq */
19995    if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq)) {
19996       ast_log(LOG_ERROR, "Missing Cseq. Dropping this SIP message, it's incomplete.\n");
19997       error = 1;
19998    }
19999    if (!error && sscanf(cseq, "%30d%n", &seqno, &len) != 1) {
20000       ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
20001       error = 1;
20002    }
20003    if (error) {
20004       if (!p->initreq.headers)   /* New call */
20005          p->needdestroy = 1; /* Make sure we destroy this dialog */
20006       return -1;
20007    }
20008    /* Get the command XXX */
20009 
20010    cmd = REQ_OFFSET_TO_STR(req, rlPart1);
20011    e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlPart2));
20012 
20013    /* Save useragent of the client */
20014    useragent = get_header(req, "User-Agent");
20015    if (!ast_strlen_zero(useragent))
20016       ast_string_field_set(p, useragent, useragent);
20017 
20018    /* Find out SIP method for incoming request */
20019    if (req->method == SIP_RESPONSE) {  /* Response to our request */
20020       /* ignore means "don't do anything with it" but still have to 
20021        * respond appropriately.
20022        * But in this case this is a response already, so we really
20023        * have nothing to do with this message, and even setting the
20024        * ignore flag is pointless.
20025        */
20026       if (ast_strlen_zero(e)) {
20027          return 0;
20028       }
20029       if (sscanf(e, "%30d %n", &respid, &len) != 1) {
20030          ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
20031          return 0;
20032       }
20033       if (respid <= 0) {
20034          ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
20035          return 0;
20036       }
20037       if (p->ocseq && (p->ocseq < seqno)) {
20038          if (option_debug)
20039             ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
20040          return -1;
20041       } else {
20042          if ((respid == 200) || ((respid >= 300) && (respid <= 399))) {
20043             extract_uri(p, req);
20044          }
20045          handle_response(p, respid, e + len, req, seqno);
20046       }
20047       return 0;
20048    }
20049 
20050    /* New SIP request coming in 
20051       (could be new request in existing SIP dialog as well...) 
20052     */         
20053    
20054    p->method = req->method;   /* Find out which SIP method they are using */
20055    ast_debug(4, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd); 
20056 
20057    if (p->icseq && (p->icseq > seqno) ) {
20058       if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
20059          ast_debug(2, "Got CANCEL or ACK on INVITE with transactions in between.\n");
20060       }  else {
20061          ast_debug(1, "Ignoring too old SIP packet packet %d (expecting >= %d)\n", seqno, p->icseq);
20062          if (req->method != SIP_ACK)
20063             transmit_response(p, "503 Server error", req);  /* We must respond according to RFC 3261 sec 12.2 */
20064          return -1;
20065       }
20066    } else if (p->icseq &&
20067          p->icseq == seqno &&
20068          req->method != SIP_ACK &&
20069          (p->method != SIP_CANCEL || p->alreadygone)) {
20070       /* ignore means "don't do anything with it" but still have to 
20071          respond appropriately.  We do this if we receive a repeat of
20072          the last sequence number  */
20073       req->ignore = 1;
20074       ast_debug(3, "Ignoring SIP message because of retransmit (%s Seqno %d, ours %d)\n", sip_methods[p->method].text, p->icseq, seqno);
20075    }
20076       
20077    if (seqno >= p->icseq)
20078       /* Next should follow monotonically (but not necessarily 
20079          incrementally -- thanks again to the genius authors of SIP --
20080          increasing */
20081       p->icseq = seqno;
20082 
20083    /* Find their tag if we haven't got it */
20084    if (ast_strlen_zero(p->theirtag)) {
20085       char tag[128];
20086 
20087       gettag(req, "From", tag, sizeof(tag));
20088       ast_string_field_set(p, theirtag, tag);
20089    }
20090    snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
20091 
20092    if (pedanticsipchecking) {
20093       /* If this is a request packet without a from tag, it's not
20094          correct according to RFC 3261  */
20095       /* Check if this a new request in a new dialog with a totag already attached to it,
20096          RFC 3261 - section 12.2 - and we don't want to mess with recovery  */
20097       if (!p->initreq.headers && req->has_to_tag) {
20098          /* If this is a first request and it got a to-tag, it is not for us */
20099          if (!req->ignore && req->method == SIP_INVITE) {
20100             transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
20101             /* Will cease to exist after ACK */
20102          } else if (req->method != SIP_ACK) {
20103             transmit_response(p, "481 Call/Transaction Does Not Exist", req);
20104             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20105          } else {
20106             ast_debug(1, "Got ACK for unknown dialog... strange.\n");
20107          }
20108          return res;
20109       }
20110    }
20111 
20112    if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY)) {
20113       transmit_response(p, "400 Bad request", req);
20114       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20115       return -1;
20116    }
20117 
20118    /* Handle various incoming SIP methods in requests */
20119    switch (p->method) {
20120    case SIP_OPTIONS:
20121       res = handle_request_options(p, req);
20122       break;
20123    case SIP_INVITE:
20124       res = handle_request_invite(p, req, debug, seqno, sin, recount, e, nounlock);
20125       break;
20126    case SIP_REFER:
20127       res = handle_request_refer(p, req, debug, seqno, nounlock);
20128       break;
20129    case SIP_CANCEL:
20130       res = handle_request_cancel(p, req);
20131       break;
20132    case SIP_BYE:
20133       res = handle_request_bye(p, req);
20134       break;
20135    case SIP_MESSAGE:
20136       res = handle_request_message(p, req);
20137       break;
20138    case SIP_SUBSCRIBE:
20139       res = handle_request_subscribe(p, req, sin, seqno, e);
20140       break;
20141    case SIP_REGISTER:
20142       res = handle_request_register(p, req, sin, e);
20143       break;
20144    case SIP_INFO:
20145       if (req->debug)
20146          ast_verbose("Receiving INFO!\n");
20147       if (!req->ignore) 
20148          handle_request_info(p, req);
20149       else  /* if ignoring, transmit response */
20150          transmit_response(p, "200 OK", req);
20151       break;
20152    case SIP_NOTIFY:
20153       res = handle_request_notify(p, req, sin, seqno, e);
20154       break;
20155    case SIP_ACK:
20156       /* Make sure we don't ignore this */
20157       if (seqno == p->pendinginvite) {
20158          p->invitestate = INV_TERMINATED;
20159          p->pendinginvite = 0;
20160          __sip_ack(p, seqno, 1 /* response */, 0);
20161          if (find_sdp(req)) {
20162             if (process_sdp(p, req, SDP_T38_NONE))
20163                return -1;
20164          }
20165          check_pendings(p);
20166       } else if (p->glareinvite == seqno) {
20167          /* handle ack for the 491 pending sent for glareinvite */
20168          p->glareinvite = 0;
20169          __sip_ack(p, seqno, 1, 0);
20170       }
20171       /* Got an ACK that we did not match. Ignore silently */
20172       if (!p->lastinvite && ast_strlen_zero(p->randdata))
20173          p->needdestroy = 1;
20174       break;
20175    default:
20176       transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
20177       ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n", 
20178          cmd, ast_inet_ntoa(p->sa.sin_addr));
20179       /* If this is some new method, and we don't have a call, destroy it now */
20180       if (!p->initreq.headers)
20181          p->needdestroy = 1;
20182       break;
20183    }
20184    return res;
20185 }
20186 
20187 static void process_request_queue(struct sip_pvt *p, int *recount, int *nounlock)
20188 {
20189    struct sip_request *req;
20190 
20191    while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
20192       if (handle_incoming(p, req, &p->recv, recount, nounlock) == -1) {
20193          /* Request failed */
20194          if (option_debug) {
20195             ast_log(LOG_DEBUG, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
20196          }
20197       }
20198       ast_free(req);
20199    }
20200 }
20201 
20202 static int scheduler_process_request_queue(const void *data)
20203 {
20204    struct sip_pvt *p = (struct sip_pvt *) data;
20205    int recount = 0;
20206    int nounlock = 0;
20207    int lockretry;
20208 
20209    for (lockretry = 10; lockretry > 0; lockretry--) {
20210       sip_pvt_lock(p);
20211 
20212       /* lock the owner if it has one -- we may need it */
20213       /* because this is deadlock-prone, we need to try and unlock if failed */
20214       if (!p->owner || !ast_channel_trylock(p->owner)) {
20215          break;   /* locking succeeded */
20216       }
20217 
20218       if (lockretry != 1) {
20219          sip_pvt_unlock(p);
20220          /* Sleep for a very short amount of time */
20221          usleep(1);
20222       }
20223    }
20224 
20225    if (!lockretry) {
20226       int retry = !AST_LIST_EMPTY(&p->request_queue);
20227 
20228       /* we couldn't get the owner lock, which is needed to process
20229          the queued requests, so return a non-zero value, which will
20230          cause the scheduler to run this request again later if there
20231          still requests to be processed
20232       */
20233       sip_pvt_unlock(p);
20234       if (!retry) {
20235          dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
20236       }
20237       return retry;
20238    };
20239 
20240    process_request_queue(p, &recount, &nounlock);
20241    p->request_queue_sched_id = -1;
20242 
20243    if (p->owner && !nounlock) {
20244       ast_channel_unlock(p->owner);
20245    }
20246    sip_pvt_unlock(p);
20247 
20248    if (recount) {
20249       ast_update_use_count();
20250    }
20251 
20252    dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
20253 
20254    return 0;
20255 }
20256 
20257 static int queue_request(struct sip_pvt *p, const struct sip_request *req)
20258 {
20259    struct sip_request *newreq;
20260 
20261    if (!(newreq = ast_calloc(1, sizeof(*newreq)))) {
20262       return -1;
20263    }
20264 
20265    copy_request(newreq, req);
20266    AST_LIST_INSERT_TAIL(&p->request_queue, newreq, next);
20267    if (p->request_queue_sched_id == -1) {
20268       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) {
20269          dialog_unref(p, "Decrement refcount due to sched_add failure");
20270       }
20271    }
20272 
20273    return 0;
20274 }
20275 
20276 /*! \brief Read data from SIP socket
20277 \note sipsock_read locks the owner channel while we are processing the SIP message
20278 \return 1 on error, 0 on success
20279 \note Successful messages is connected to SIP call and forwarded to handle_incoming() 
20280 */
20281 static int sipsock_read(int *id, int fd, short events, void *ignore)
20282 {
20283    struct sip_request req;
20284    struct sockaddr_in sin = { 0, };
20285    int res;
20286    socklen_t len = sizeof(sin);
20287    static char readbuf[65535];
20288 
20289    memset(&req, 0, sizeof(req));
20290    res = recvfrom(fd, readbuf, sizeof(readbuf) - 1, 0, (struct sockaddr *)&sin, &len);
20291    if (res < 0) {
20292 #if !defined(__FreeBSD__)
20293       if (errno == EAGAIN)
20294          ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
20295       else 
20296 #endif
20297       if (errno != ECONNREFUSED)
20298          ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
20299       return 1;
20300    }
20301 
20302    readbuf[res] = '\0';
20303 
20304    if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
20305       return 1;
20306    }
20307 
20308    if (ast_str_set(&req.data, 0, "%s", readbuf) == AST_DYNSTR_BUILD_FAILED) {
20309       return -1;
20310    }
20311 
20312    req.len = res;
20313    req.socket.fd = sipsock;
20314    set_socket_transport(&req.socket, SIP_TRANSPORT_UDP);
20315    req.socket.tcptls_session  = NULL;
20316    req.socket.port = bindaddr.sin_port;
20317 
20318    handle_request_do(&req, &sin);
20319    if (req.data) {
20320       ast_free(req.data);
20321       req.data = NULL;
20322    }
20323 
20324    return 1;
20325 }
20326 
20327 static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin) 
20328 {
20329    struct sip_pvt *p;
20330    int recount = 0;
20331    int nounlock = 0;
20332    int lockretry;
20333 
20334    if (sip_debug_test_addr(sin)) /* Set the debug flag early on packet level */
20335       req->debug = 1;
20336    if (pedanticsipchecking)
20337       req->len = lws2sws(req->data->str, req->len);   /* Fix multiline headers */
20338    if (req->debug) {
20339       ast_verbose("\n<--- SIP read from %s://%s:%d --->\n%s\n<------------->\n", 
20340          get_transport(req->socket.type), ast_inet_ntoa(sin->sin_addr), 
20341          ntohs(sin->sin_port), req->data->str);
20342    }
20343 
20344    if (parse_request(req) == -1) { /* Bad packet, can't parse */
20345       ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
20346       return 1;
20347    }
20348    req->method = find_sip_method(REQ_OFFSET_TO_STR(req, rlPart1));
20349 
20350    if (req->debug)
20351       ast_verbose("--- (%d headers %d lines)%s ---\n", req->headers, req->lines, (req->headers + req->lines == 0) ? " Nat keepalive" : "");
20352 
20353    if (req->headers < 2) { /* Must have at least two headers */
20354       ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
20355       return 1;
20356    }
20357 
20358    /* Process request, with netlock held, and with usual deadlock avoidance */
20359    for (lockretry = 10; lockretry > 0; lockretry--) {
20360       ast_mutex_lock(&netlock);
20361 
20362       /* Find the active SIP dialog or create a new one */
20363       p = find_call(req, sin, req->method);  /* returns p locked */
20364       if (p == NULL) {
20365          ast_debug(1, "Invalid SIP message - rejected , no callid, len %d\n", req->len);
20366          ast_mutex_unlock(&netlock);
20367          return 1;
20368       }
20369 
20370       copy_socket_data(&p->socket, &req->socket);
20371 
20372       /* Go ahead and lock the owner if it has one -- we may need it */
20373       /* becaues this is deadlock-prone, we need to try and unlock if failed */
20374       if (!p->owner || !ast_channel_trylock(p->owner))
20375          break;   /* locking succeeded */
20376 
20377       if (lockretry != 1) {
20378          sip_pvt_unlock(p);
20379          ao2_t_ref(p, -1, "release p (from find_call) inside lockretry loop"); /* we'll look for it again, but p is dead now */
20380          ast_mutex_unlock(&netlock);
20381          /* Sleep for a very short amount of time */
20382          usleep(1);
20383       }
20384    }
20385    p->recv = *sin;
20386 
20387    if (p->do_history) /* This is a request or response, note what it was for */
20388       append_history(p, "Rx", "%s / %s / %s", req->data->str, get_header(req, "CSeq"), REQ_OFFSET_TO_STR(req, rlPart2));
20389 
20390    if (!lockretry) {
20391       if (!queue_request(p, req)) {
20392          /* the request has been queued for later handling */
20393          sip_pvt_unlock(p);
20394          ao2_t_ref(p, -1, "release p (from find_call) after queueing request");
20395          ast_mutex_unlock(&netlock);
20396          return 1;
20397       }
20398 
20399       if (p->owner)
20400          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 ??? - "));
20401       ast_log(LOG_ERROR, "SIP transaction failed: %s \n", p->callid);
20402       if (req->method != SIP_ACK)
20403          transmit_response(p, "503 Server error", req);  /* We must respond according to RFC 3261 sec 12.2 */
20404       /* XXX We could add retry-after to make sure they come back */
20405       append_history(p, "LockFail", "Owner lock failed, transaction failed.");
20406       sip_pvt_unlock(p);
20407       ao2_t_ref(p, -1, "release p (from find_call) at end of lockretry"); /* p is gone after the return */
20408       ast_mutex_unlock(&netlock);
20409       return 1;
20410    }
20411 
20412    /* if there are queued requests on this sip_pvt, process them first, so that everything is
20413       handled in order
20414    */
20415    if (!AST_LIST_EMPTY(&p->request_queue)) {
20416       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"));
20417       process_request_queue(p, &recount, &nounlock);
20418    }
20419 
20420    if (handle_incoming(p, req, sin, &recount, &nounlock) == -1) {
20421       /* Request failed */
20422       ast_debug(1, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
20423    }
20424       
20425    if (recount)
20426       ast_update_use_count();
20427 
20428    if (p->owner && !nounlock)
20429       ast_channel_unlock(p->owner);
20430    sip_pvt_unlock(p);
20431    ast_mutex_unlock(&netlock);
20432    ao2_t_ref(p, -1, "throw away dialog ptr from find_call at end of routine"); /* p is gone after the return */
20433    return 1;
20434 }
20435 
20436 /*! \brief Returns the port to use for this socket
20437  *
20438  * \param type The type of transport used
20439  * \param port Port we are checking to see if it's the standard port.
20440  * \note port is expected in host byte order
20441  */
20442 static int sip_standard_port(enum sip_transport type, int port)
20443 {
20444    if (type & SIP_TRANSPORT_TLS)
20445       return port == STANDARD_TLS_PORT;
20446    else
20447       return port == STANDARD_SIP_PORT;
20448 }
20449 
20450 /*! 
20451  * \brief Find thread for TCP/TLS session (based on IP/Port 
20452  *
20453  * \note This function returns an astobj2 reference
20454  */
20455 static struct ast_tcptls_session_instance *sip_tcp_locate(struct sockaddr_in *s)
20456 {
20457    struct sip_threadinfo *th;
20458    struct ast_tcptls_session_instance *tcptls_instance = NULL;
20459 
20460    AST_LIST_LOCK(&threadl);
20461    AST_LIST_TRAVERSE(&threadl, th, list) {
20462       if ((s->sin_family == th->tcptls_session->remote_address.sin_family) &&
20463          (s->sin_addr.s_addr == th->tcptls_session->remote_address.sin_addr.s_addr) &&
20464          (s->sin_port == th->tcptls_session->remote_address.sin_port))  {
20465             tcptls_instance = (ao2_ref(th->tcptls_session, +1), th->tcptls_session);
20466             break;
20467          }
20468    }
20469    AST_LIST_UNLOCK(&threadl);
20470 
20471    return tcptls_instance;
20472 }
20473 
20474 /*! \todo document this function. */
20475 static int sip_prepare_socket(struct sip_pvt *p) 
20476 {
20477    struct sip_socket *s = &p->socket;
20478    static const char name[] = "SIP socket";
20479    struct ast_tcptls_session_instance *tcptls_session;
20480    struct ast_tcptls_session_args ca = {
20481       .name = name,
20482       .accept_fd = -1,
20483    };
20484 
20485    if (s->fd != -1)
20486       return s->fd;
20487 
20488    if (p->outboundproxy && p->outboundproxy->transport) {
20489       s->type = p->outboundproxy->transport;
20490    }
20491 
20492    if (s->type & SIP_TRANSPORT_UDP) {
20493       s->fd = sipsock;
20494       return s->fd;
20495    }
20496 
20497    ca.remote_address = *(sip_real_dst(p));
20498 
20499    if ((tcptls_session = sip_tcp_locate(&ca.remote_address))) {   /* Check if we have a thread handling a socket connected to this IP/port */
20500       s->fd = tcptls_session->fd;
20501       if (s->tcptls_session) {
20502          ao2_ref(s->tcptls_session, -1);
20503          s->tcptls_session = NULL;
20504       }
20505       s->tcptls_session = tcptls_session;
20506       return s->fd;
20507    }
20508 
20509    if (s->tcptls_session && s->tcptls_session->parent->tls_cfg) {
20510       ca.tls_cfg = s->tcptls_session->parent->tls_cfg;
20511    } else {
20512       if (s->type & SIP_TRANSPORT_TLS) {
20513          ca.tls_cfg = ast_calloc(1, sizeof(*ca.tls_cfg));
20514          if (!ca.tls_cfg)
20515             return -1;
20516          memcpy(ca.tls_cfg, &default_tls_cfg, sizeof(*ca.tls_cfg));
20517          if (!ast_strlen_zero(p->tohost))
20518             ast_copy_string(ca.hostname, p->tohost, sizeof(ca.hostname));
20519       }
20520    }
20521    
20522    if (s->tcptls_session) {
20523       /* the pvt socket already has a server instance ... */
20524    } else {
20525       s->tcptls_session = ast_tcptls_client_start(&ca); /* Start a client connection to this address */
20526    }
20527 
20528    if (!s->tcptls_session) {
20529       if (ca.tls_cfg)
20530          ast_free(ca.tls_cfg);
20531       return -1;
20532    }
20533 
20534    s->fd = ca.accept_fd;
20535 
20536    /* Give the new thread a reference */
20537    ao2_ref(s->tcptls_session, +1);
20538 
20539    if (ast_pthread_create_background(&ca.master, NULL, sip_tcp_worker_fn, s->tcptls_session)) {
20540       ast_debug(1, "Unable to launch '%s'.", ca.name);
20541       ao2_ref(s->tcptls_session, -1);
20542       close(ca.accept_fd);
20543       s->fd = ca.accept_fd = -1;
20544    }
20545 
20546    return s->fd;
20547 }
20548 
20549 /*!
20550  * \brief Small function to parse a config line for a host with a transport
20551  *        i.e. tls://www.google.com:8056
20552  */
20553 static int sip_parse_host(char *line, int lineno, char **hostname, int *portnum, enum sip_transport *transport)
20554 {
20555    char *port;
20556 
20557    if ((*hostname = strstr(line, "://"))) {
20558       *hostname += 3;
20559 
20560       if (!strncasecmp(line, "tcp", 3))
20561          *transport = SIP_TRANSPORT_TCP;
20562       else if (!strncasecmp(line, "tls", 3))
20563          *transport = SIP_TRANSPORT_TLS;
20564       else if (!strncasecmp(line, "udp", 3))
20565          *transport = SIP_TRANSPORT_UDP;
20566       else
20567          ast_log(LOG_NOTICE, "'%.3s' is not a valid transport type on line %d of sip.conf. defaulting to udp.\n", line, lineno);
20568    } else {
20569       *hostname = line;
20570       *transport = SIP_TRANSPORT_UDP;
20571    }
20572 
20573    if ((line = strrchr(*hostname, '@')))
20574       line++;
20575    else
20576       line = *hostname;
20577 
20578    if ((port = strrchr(line, ':'))) {
20579       *port++ = '\0';
20580 
20581       if (!sscanf(port, "%5u", portnum)) {
20582          ast_log(LOG_NOTICE, "'%s' is not a valid port number on line %d of sip.conf. using default.\n", port, lineno);
20583          port = NULL;
20584       }
20585    }
20586 
20587    if (!port) {
20588       if (*transport & SIP_TRANSPORT_TLS) {
20589          *portnum = STANDARD_TLS_PORT;
20590       } else {
20591          *portnum = STANDARD_SIP_PORT;
20592       }
20593    }
20594 
20595    return 0;
20596 }
20597 
20598 /*!
20599  * \brief Get cached MWI info
20600  * \retval 0 At least one message is waiting
20601  * \retval 1 no messages waiting
20602  */
20603 static int get_cached_mwi(struct sip_peer *peer, int *new, int *old)
20604 {
20605    struct sip_mailbox *mailbox;
20606 
20607    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
20608       struct ast_event *event;
20609       event = ast_event_get_cached(AST_EVENT_MWI,
20610          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
20611          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
20612          AST_EVENT_IE_END);
20613       if (!event)
20614          continue;
20615       *new += ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
20616       *old += ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
20617       ast_event_destroy(event);
20618    }
20619 
20620    return (*new || *old) ? 0 : 1;
20621 }
20622 
20623 /*! \brief Send message waiting indication to alert peer that they've got voicemail */
20624 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only)
20625 {
20626    /* Called with peerl lock, but releases it */
20627    struct sip_pvt *p;
20628    int newmsgs = 0, oldmsgs = 0;
20629 
20630    if (ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY) && !peer->mwipvt)
20631       return 0;
20632 
20633    /* Do we have an IP address? If not, skip this peer */
20634    if (!peer->addr.sin_addr.s_addr && !peer->defaddr.sin_addr.s_addr) 
20635       return 0;
20636 
20637    if (event) {
20638       newmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
20639       oldmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
20640    } else if (!get_cached_mwi(peer, &newmsgs, &oldmsgs)) {
20641       /* got it!  Don't keep looking. */
20642    } else if (cache_only) {
20643       return 0;
20644    } else { /* Fall back to manually checking the mailbox */
20645       struct ast_str *mailbox_str = ast_str_alloca(512);
20646       peer_mailboxes_to_str(&mailbox_str, peer);
20647       ast_app_inboxcount(mailbox_str->str, &newmsgs, &oldmsgs);
20648    }
20649    
20650    if (peer->mwipvt) {
20651       /* Base message on subscription */
20652       p = dialog_ref(peer->mwipvt, "sip_send_mwi_to_peer: Setting dialog ptr p from peer->mwipvt-- should this be done?");
20653    } else {
20654       /* Build temporary dialog for this message */
20655       if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) 
20656          return -1;
20657       /* If we don't set the socket type to 0, then create_addr_from_peer will fail immediately if the peer
20658        * uses any transport other than UDP. We set the type to 0 here and then let create_addr_from_peer copy 
20659        * the peer's socket information to the sip_pvt we just allocated
20660        */
20661       set_socket_transport(&p->socket, 0);
20662       if (create_addr_from_peer(p, peer)) {
20663          /* Maybe they're not registered, etc. */
20664          dialog_unlink_all(p, TRUE, TRUE);
20665          dialog_unref(p, "unref dialog p just created via sip_alloc");
20666          /* sip_destroy(p); */
20667          return 0;
20668       }
20669       /* Recalculate our side, and recalculate Call ID */
20670       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
20671       build_via(p);
20672       ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
20673       build_callid_pvt(p);
20674       ao2_t_link(dialogs, p, "Linking in under new name");
20675       /* Destroy this session after 32 secs */
20676       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20677    }
20678 
20679    /* Send MWI */
20680    ast_set_flag(&p->flags[0], SIP_OUTGOING);
20681    /* the following will decrement the refcount on p as it finishes */
20682    transmit_notify_with_mwi(p, newmsgs, oldmsgs, peer->vmexten);
20683    dialog_unref(p, "unref dialog ptr p just before it goes out of scope at the end of sip_send_mwi_to_peer.");
20684    return 0;
20685 }
20686 
20687 /*! \brief helper function for the monitoring thread -- seems to be called with the assumption that the dialog is locked */
20688 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t)
20689 {
20690    /* If we have no RTP or no active owner, no need to check timers */
20691    if (!dialog->rtp || !dialog->owner)
20692       return;
20693    /* If the call is not in UP state or redirected outside Asterisk, no need to check timers */
20694 
20695    if (dialog->owner->_state != AST_STATE_UP || dialog->redirip.sin_addr.s_addr)
20696       return;
20697 
20698    /* If the call is involved in a T38 fax session do not check RTP timeout */
20699    if (dialog->t38.state == T38_ENABLED)
20700       return;
20701 
20702    /* If we have no timers set, return now */
20703    if ((ast_rtp_get_rtpkeepalive(dialog->rtp) == 0) && (ast_rtp_get_rtptimeout(dialog->rtp) == 0) && (ast_rtp_get_rtpholdtimeout(dialog->rtp) == 0))
20704       return;
20705 
20706    /* Check AUDIO RTP keepalives */
20707    if (dialog->lastrtptx && ast_rtp_get_rtpkeepalive(dialog->rtp) &&
20708           (t > dialog->lastrtptx + ast_rtp_get_rtpkeepalive(dialog->rtp))) {
20709       /* Need to send an empty RTP packet */
20710       dialog->lastrtptx = time(NULL);
20711       ast_rtp_sendcng(dialog->rtp, 0);
20712    }
20713 
20714    /*! \todo Check video RTP keepalives
20715 
20716       Do we need to move the lastrtptx to the RTP structure to have one for audio and one
20717       for video? It really does belong to the RTP structure.
20718    */
20719 
20720    /* Check AUDIO RTP timers */
20721    if (dialog->lastrtprx && (ast_rtp_get_rtptimeout(dialog->rtp) || ast_rtp_get_rtpholdtimeout(dialog->rtp)) &&
20722           (t > dialog->lastrtprx + ast_rtp_get_rtptimeout(dialog->rtp))) {
20723 
20724       /* Might be a timeout now -- see if we're on hold */
20725       struct sockaddr_in sin;
20726       ast_rtp_get_peer(dialog->rtp, &sin);
20727       if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD) || (ast_rtp_get_rtpholdtimeout(dialog->rtp) &&
20728            (t > dialog->lastrtprx + ast_rtp_get_rtpholdtimeout(dialog->rtp)))) {
20729          /* Needs a hangup */
20730          if (ast_rtp_get_rtptimeout(dialog->rtp)) {
20731             while (dialog->owner && ast_channel_trylock(dialog->owner)) {
20732                sip_pvt_unlock(dialog);
20733                usleep(1);
20734                sip_pvt_lock(dialog);
20735             }
20736             ast_log(LOG_NOTICE, "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
20737                dialog->owner->name, (long) (t - dialog->lastrtprx));
20738             /* Issue a softhangup */
20739             ast_softhangup_nolock(dialog->owner, AST_SOFTHANGUP_DEV);
20740             ast_channel_unlock(dialog->owner);
20741             /* forget the timeouts for this call, since a hangup
20742                has already been requested and we don't want to
20743                repeatedly request hangups
20744             */
20745             ast_rtp_set_rtptimeout(dialog->rtp, 0);
20746             ast_rtp_set_rtpholdtimeout(dialog->rtp, 0);
20747             if (dialog->vrtp) {
20748                ast_rtp_set_rtptimeout(dialog->vrtp, 0);
20749                ast_rtp_set_rtpholdtimeout(dialog->vrtp, 0);
20750             }
20751          }
20752       }
20753    }
20754 }
20755 
20756 /*! \brief The SIP monitoring thread 
20757 \note This thread monitors all the SIP sessions and peers that needs notification of mwi
20758    (and thus do not have a separate thread) indefinitely 
20759 */
20760 static void *do_monitor(void *data)
20761 {
20762    int res;
20763    time_t t;
20764    int reloading;
20765 
20766    /* Add an I/O event to our SIP UDP socket */
20767    if (sipsock > -1) 
20768       sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
20769 
20770    /* From here on out, we die whenever asked */
20771    for(;;) {
20772       /* Check for a reload request */
20773       ast_mutex_lock(&sip_reload_lock);
20774       reloading = sip_reloading;
20775       sip_reloading = FALSE;
20776       ast_mutex_unlock(&sip_reload_lock);
20777       if (reloading) {
20778          ast_verb(1, "Reloading SIP\n");
20779          sip_do_reload(sip_reloadreason);
20780 
20781          /* Change the I/O fd of our UDP socket */
20782          if (sipsock > -1) {
20783             if (sipsock_read_id)
20784                sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
20785             else
20786                sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
20787          } else if (sipsock_read_id) {
20788             ast_io_remove(io, sipsock_read_id);
20789             sipsock_read_id = NULL;
20790          }
20791       }
20792 
20793       /* Check for dialogs needing to be killed */
20794       t = time(NULL);
20795       /* don't scan the dialogs list if it hasn't been a reasonable period
20796          of time since the last time we did it (when MWI is being sent, we can
20797          get back to this point every millisecond or less)
20798       */
20799       ao2_t_callback(dialogs, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, dialog_needdestroy, &t, 
20800             "callback to remove dialogs w/needdestroy");
20801 
20802       /* the old methodology would be to restart the search for dialogs to delete with every 
20803          dialog that was found and destroyed, probably because the list contents would change,
20804          so we'd need to restart. This isn't the best thing to do with callbacks. */
20805 
20806       /* XXX TODO The scheduler usage in this module does not have sufficient 
20807        * synchronization being done between running the scheduler and places 
20808        * scheduling tasks.  As it is written, any scheduled item may not run 
20809        * any sooner than about  1 second, regardless of whether a sooner time 
20810        * was asked for. */
20811 
20812       pthread_testcancel();
20813       /* Wait for sched or io */
20814       res = ast_sched_wait(sched);
20815       if ((res < 0) || (res > 1000))
20816          res = 1000;
20817       res = ast_io_wait(io, res);
20818       if (res > 20)
20819          ast_debug(1, "chan_sip: ast_io_wait ran %d all at once\n", res);
20820       ast_mutex_lock(&monlock);
20821       res = ast_sched_runq(sched);
20822       if (res >= 20)
20823          ast_debug(1, "chan_sip: ast_sched_runq ran %d all at once\n", res);
20824       ast_mutex_unlock(&monlock);
20825    }
20826 
20827    /* Never reached */
20828    return NULL;
20829 }
20830 
20831 /*! \brief Start the channel monitor thread */
20832 static int restart_monitor(void)
20833 {
20834    /* If we're supposed to be stopped -- stay stopped */
20835    if (monitor_thread == AST_PTHREADT_STOP)
20836       return 0;
20837    ast_mutex_lock(&monlock);
20838    if (monitor_thread == pthread_self()) {
20839       ast_mutex_unlock(&monlock);
20840       ast_log(LOG_WARNING, "Cannot kill myself\n");
20841       return -1;
20842    }
20843    if (monitor_thread != AST_PTHREADT_NULL) {
20844       /* Wake up the thread */
20845       pthread_kill(monitor_thread, SIGURG);
20846    } else {
20847       /* Start a new monitor */
20848       if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
20849          ast_mutex_unlock(&monlock);
20850          ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
20851          return -1;
20852       }
20853    }
20854    ast_mutex_unlock(&monlock);
20855    return 0;
20856 }
20857 
20858 
20859 /*! \brief Session-Timers: Restart session timer */
20860 static void restart_session_timer(struct sip_pvt *p)
20861 {
20862    if (!p->stimer) {
20863       ast_log(LOG_WARNING, "Null stimer in restart_session_timer - %s\n", p->callid);
20864       return;
20865    }
20866 
20867    if (p->stimer->st_active == TRUE) {
20868       AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
20869             dialog_unref(p, "Removing session timer ref"));
20870       ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
20871       start_session_timer(p);
20872    }
20873 }
20874 
20875 
20876 /*! \brief Session-Timers: Stop session timer */
20877 static void stop_session_timer(struct sip_pvt *p)
20878 {
20879    if (!p->stimer) {
20880       ast_log(LOG_WARNING, "Null stimer in stop_session_timer - %s\n", p->callid);
20881       return;
20882    }
20883 
20884    if (p->stimer->st_active == TRUE) {
20885       p->stimer->st_active = FALSE;
20886       AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
20887             dialog_unref(p, "removing session timer ref"));
20888       ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
20889    }
20890 }
20891 
20892 
20893 /*! \brief Session-Timers: Start session timer */
20894 static void start_session_timer(struct sip_pvt *p)
20895 {
20896    if (!p->stimer) {
20897       ast_log(LOG_WARNING, "Null stimer in start_session_timer - %s\n", p->callid);
20898       return;
20899    }
20900 
20901    p->stimer->st_schedid  = ast_sched_add(sched, p->stimer->st_interval * 1000 / 2, proc_session_timer, 
20902          dialog_ref(p, "adding session timer ref"));
20903    if (p->stimer->st_schedid < 0) {
20904       dialog_unref(p, "removing session timer ref");
20905       ast_log(LOG_ERROR, "ast_sched_add failed.\n");
20906    }
20907    ast_debug(2, "Session timer started: %d - %s\n", p->stimer->st_schedid, p->callid);
20908 }
20909 
20910 
20911 /*! \brief Session-Timers: Process session refresh timeout event */
20912 static int proc_session_timer(const void *vp)
20913 {
20914    struct sip_pvt *p = (struct sip_pvt *) vp;
20915    int sendreinv = FALSE;
20916    int res = 0;
20917 
20918    if (!p->stimer) {
20919       ast_log(LOG_WARNING, "Null stimer in proc_session_timer - %s\n", p->callid);
20920       goto return_unref;
20921    }
20922 
20923    ast_debug(2, "Session timer expired: %d - %s\n", p->stimer->st_schedid, p->callid);
20924 
20925    if (!p->owner) {
20926       goto return_unref;
20927    }
20928 
20929    if ((p->stimer->st_active != TRUE) || (p->owner->_state != AST_STATE_UP)) {
20930       goto return_unref;
20931    }
20932 
20933    switch (p->stimer->st_ref) {
20934    case SESSION_TIMER_REFRESHER_UAC:
20935       if (p->outgoing_call == TRUE) {
20936          sendreinv = TRUE;
20937       }
20938       break;
20939    case SESSION_TIMER_REFRESHER_UAS:
20940       if (p->outgoing_call != TRUE) {
20941          sendreinv = TRUE;
20942       }
20943       break;
20944    default:
20945       ast_log(LOG_ERROR, "Unknown session refresher %d\n", p->stimer->st_ref);
20946       goto return_unref;
20947    }
20948 
20949    if (sendreinv == TRUE) {
20950       res = 1;
20951       transmit_reinvite_with_sdp(p, FALSE, TRUE);
20952    } else {
20953       p->stimer->st_expirys++;
20954       if (p->stimer->st_expirys >= 2) {
20955          ast_log(LOG_WARNING, "Session-Timer expired - %s\n", p->callid);
20956 
20957          while (p->owner && ast_channel_trylock(p->owner)) {
20958             sip_pvt_unlock(p);
20959             usleep(1);
20960             sip_pvt_lock(p);
20961          }
20962 
20963          ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
20964          ast_channel_unlock(p->owner);
20965       }
20966    }
20967 
20968 return_unref:
20969    if (!res) {
20970       /* An error occurred.  Stop session timer processing */
20971       p->stimer->st_schedid = -1;
20972       stop_session_timer(p);
20973       
20974       /* If we are not asking to be rescheduled, then we need to release our
20975        * reference to the dialog. */
20976       dialog_unref(p, "removing session timer ref");
20977    }
20978 
20979    return res;
20980 }
20981 
20982 
20983 /*! \brief Session-Timers: Function for parsing Min-SE header */
20984 int parse_minse (const char *p_hdrval, int *const p_interval)
20985 {
20986    if (ast_strlen_zero(p_hdrval)) {
20987       ast_log(LOG_WARNING, "Null Min-SE header\n");
20988       return -1;
20989    }
20990 
20991    *p_interval = 0;
20992    p_hdrval = ast_skip_blanks(p_hdrval);
20993    if (!sscanf(p_hdrval, "%30d", p_interval)) {
20994       ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
20995       return -1;
20996    }
20997 
20998    ast_debug(2, "Received Min-SE: %d\n", *p_interval);
20999    return 0;
21000 }
21001 
21002 
21003 /*! \brief Session-Timers: Function for parsing Session-Expires header */
21004 int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref)
21005 {
21006    char *p_token;
21007    int  ref_idx;
21008    char *p_se_hdr;
21009 
21010    if (ast_strlen_zero(p_hdrval)) {
21011       ast_log(LOG_WARNING, "Null Session-Expires header\n");
21012       return -1;
21013    }
21014 
21015    *p_ref = SESSION_TIMER_REFRESHER_AUTO;
21016    *p_interval = 0;
21017 
21018    p_se_hdr = ast_strdupa(p_hdrval);
21019    p_se_hdr = ast_skip_blanks(p_se_hdr);
21020 
21021    while ((p_token = strsep(&p_se_hdr, ";"))) {
21022       p_token = ast_skip_blanks(p_token);
21023       if (!sscanf(p_token, "%30d", p_interval)) {
21024          ast_log(LOG_WARNING, "Parsing of Session-Expires failed\n");
21025          return -1;
21026       }
21027 
21028       ast_debug(2, "Session-Expires: %d\n", *p_interval);
21029 
21030       if (!p_se_hdr)
21031          continue;
21032       
21033       ref_idx = strlen("refresher=");
21034       if (!strncasecmp(p_se_hdr, "refresher=", ref_idx)) {
21035          p_se_hdr += ref_idx;
21036          p_se_hdr = ast_skip_blanks(p_se_hdr);
21037 
21038          if (!strncasecmp(p_se_hdr, "uac", strlen("uac"))) {
21039             *p_ref = SESSION_TIMER_REFRESHER_UAC;
21040             ast_debug(2, "Refresher: UAC\n");
21041          } else if (!strncasecmp(p_se_hdr, "uas", strlen("uas"))) {
21042             *p_ref = SESSION_TIMER_REFRESHER_UAS;
21043             ast_debug(2, "Refresher: UAS\n");
21044          } else {
21045             ast_log(LOG_WARNING, "Invalid refresher value %s\n", p_se_hdr);
21046             return -1;
21047          }
21048          break;
21049       }
21050    }
21051    return 0;
21052 }
21053 
21054 
21055 /*! \brief Handle 422 response to INVITE with session-timer requested
21056 
21057    Session-Timers:   An INVITE originated by Asterisk that asks for session-timers support
21058    from the UAS can result into a 422 response. This is how a UAS or an intermediary proxy 
21059    server tells Asterisk that the session refresh interval offered by Asterisk is too low 
21060    for them.  The proc_422_rsp() function handles a 422 response.  It extracts the Min-SE 
21061    header that comes back in 422 and sends a new INVITE accordingly. */
21062 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp)
21063 {
21064    int rtn;
21065    const char *p_hdrval;
21066    int minse;
21067 
21068    p_hdrval = get_header(rsp, "Min-SE");
21069    if (ast_strlen_zero(p_hdrval)) {
21070       ast_log(LOG_WARNING, "422 response without a Min-SE header %s\n", p_hdrval);
21071       return;
21072    }
21073    rtn = parse_minse(p_hdrval, &minse);
21074    if (rtn != 0) {
21075       ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
21076       return;
21077    }
21078    p->stimer->st_interval = minse;
21079    transmit_invite(p, SIP_INVITE, 1, 2); 
21080 }
21081 
21082 
21083 /*! \brief Get Max or Min SE (session timer expiry)
21084  * \param p pointer to the SIP dialog 
21085  * \param max if true, get max se, otherwise min se
21086 */
21087 int st_get_se(struct sip_pvt *p, int max)
21088 {
21089    if (max == TRUE) {
21090       if (p->stimer->st_cached_max_se) {
21091          return p->stimer->st_cached_max_se;
21092       } else if (p->peername) {
21093          struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE);
21094          if (pp) {
21095             p->stimer->st_cached_max_se = pp->stimer.st_max_se;
21096             unref_peer(pp, "unref peer pointer from find_peer call in st_get_se");
21097             return (p->stimer->st_cached_max_se);
21098          }
21099       }
21100       p->stimer->st_cached_max_se = global_max_se;
21101       return (p->stimer->st_cached_max_se);
21102    } else {
21103       if (p->stimer->st_cached_min_se) {
21104          return p->stimer->st_cached_min_se;
21105       } else if (p->peername) {
21106          struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE);
21107          if (pp) {
21108             p->stimer->st_cached_min_se = pp->stimer.st_min_se;
21109             unref_peer(pp, "unref peer pointer from find_peer call in st_get_se (2)");
21110             return (p->stimer->st_cached_min_se);
21111          }
21112       }
21113       p->stimer->st_cached_min_se = global_min_se;
21114       return (p->stimer->st_cached_min_se);
21115    }
21116 }
21117 
21118 
21119 /*! \brief Get the entity (UAC or UAS) that's acting as the session-timer refresher 
21120  * \param p pointer to the SIP dialog 
21121 */
21122 enum st_refresher st_get_refresher(struct sip_pvt *p)
21123 {
21124    if (p->stimer->st_cached_ref != SESSION_TIMER_REFRESHER_AUTO) 
21125       return p->stimer->st_cached_ref;
21126 
21127    if (p->peername) {
21128       struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE);
21129       if (pp) {
21130          p->stimer->st_cached_ref = pp->stimer.st_ref;
21131          unref_peer(pp, "unref peer pointer from find_peer call in st_get_refresher");
21132          return pp->stimer.st_ref;
21133       }
21134    }
21135    
21136    p->stimer->st_cached_ref = global_st_refresher;
21137    return global_st_refresher;
21138 }
21139 
21140 
21141 /*! \brief Get the session-timer mode 
21142  * \param p pointer to the SIP dialog 
21143 */
21144 enum st_mode st_get_mode(struct sip_pvt *p)
21145 {
21146    if (!p->stimer) 
21147       sip_st_alloc(p);
21148 
21149    if (p->stimer->st_cached_mode != SESSION_TIMER_MODE_INVALID) 
21150       return p->stimer->st_cached_mode;
21151 
21152    if (p->peername) {
21153       struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE);
21154       if (pp) {
21155          p->stimer->st_cached_mode = pp->stimer.st_mode_oper;
21156          unref_peer(pp, "unref peer pointer from find_peer call in st_get_mode");
21157          return pp->stimer.st_mode_oper;
21158       }
21159    }
21160 
21161    p->stimer->st_cached_mode = global_st_mode;
21162    return global_st_mode;
21163 }
21164 
21165 
21166 /*! \brief React to lack of answer to Qualify poke */
21167 static int sip_poke_noanswer(const void *data)
21168 {
21169    struct sip_peer *peer = (struct sip_peer *)data;
21170    
21171    peer->pokeexpire = -1;
21172 
21173    if (peer->lastms > -1) {
21174       ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE!  Last qualify: %d\n", peer->name, peer->lastms);
21175       if (sip_cfg.peer_rtupdate) {
21176          ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", "-1", SENTINEL);
21177       }
21178       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
21179       if (global_regextenonqualify) {
21180          register_peer_exten(peer, FALSE);
21181       }
21182    }
21183 
21184    if (peer->call) {
21185       dialog_unlink_all(peer->call, TRUE, TRUE);
21186       peer->call = dialog_unref(peer->call, "unref dialog peer->call");
21187       /* peer->call = sip_destroy(peer->call);*/
21188    }
21189    
21190    peer->lastms = -1;
21191    ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
21192 
21193    /* Try again quickly */
21194    AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, 
21195          DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer,
21196          unref_peer(_data, "removing poke peer ref"),
21197          unref_peer(peer, "removing poke peer ref"),
21198          ref_peer(peer, "adding poke peer ref"));
21199 
21200    /* Release the ref held by the running scheduler entry */
21201    unref_peer(peer, "release peer poke noanswer ref");
21202 
21203    return 0;
21204 }
21205 
21206 /*! \brief Check availability of peer, also keep NAT open
21207 \note This is done with 60 seconds between each ping,
21208    unless forced by cli or manager. If peer is unreachable,
21209    we check every 10th second by default. 
21210 */
21211 static int sip_poke_peer(struct sip_peer *peer, int force)
21212 {
21213    struct sip_pvt *p;
21214    int xmitres = 0;
21215    
21216    if ((!peer->maxms && !force) || !peer->addr.sin_addr.s_addr) {
21217       /* IF we have no IP, or this isn't to be monitored, return
21218         immediately after clearing things out */
21219       AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
21220             unref_peer(peer, "removing poke peer ref"));
21221       
21222       peer->lastms = 0;
21223       if (peer->call) {
21224          peer->call = dialog_unref(peer->call, "unref dialog peer->call");
21225       }
21226       return 0;
21227    }
21228    if (peer->call) {
21229       if (sipdebug) {
21230          ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
21231       }
21232       dialog_unlink_all(peer->call, TRUE, TRUE);
21233       peer->call = dialog_unref(peer->call, "unref dialog peer->call");
21234       /* peer->call = sip_destroy(peer->call); */
21235    }
21236    if (!(p = sip_alloc(NULL, NULL, 0, SIP_OPTIONS, NULL))) {
21237       return -1;
21238    }
21239    peer->call = dialog_ref(p, "copy sip alloc from p to peer->call");
21240    
21241    p->sa = peer->addr;
21242    p->recv = peer->addr;
21243    copy_socket_data(&p->socket, &peer->socket);
21244    ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
21245    ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
21246 
21247    /* Send OPTIONs to peer's fullcontact */
21248    if (!ast_strlen_zero(peer->fullcontact))
21249       ast_string_field_set(p, fullcontact, peer->fullcontact);
21250 
21251    if (!ast_strlen_zero(peer->tohost))
21252       ast_string_field_set(p, tohost, peer->tohost);
21253    else
21254       ast_string_field_set(p, tohost, ast_inet_ntoa(peer->addr.sin_addr));
21255 
21256    /* Recalculate our side, and recalculate Call ID */
21257    ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
21258    build_via(p);
21259    ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
21260    build_callid_pvt(p);
21261    ao2_t_link(dialogs, p, "Linking in under new name");
21262 
21263    AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
21264          unref_peer(peer, "removing poke peer ref"));
21265    
21266    if (p->relatedpeer)
21267       p->relatedpeer = unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
21268    p->relatedpeer = ref_peer(peer, "setting the relatedpeer field in the dialog");
21269    ast_set_flag(&p->flags[0], SIP_OUTGOING);
21270 #ifdef VOCAL_DATA_HACK
21271    ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
21272    xmitres = transmit_invite(p, SIP_INVITE, 0, 2); /* sinks the p refcount */
21273 #else
21274    xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2); /* sinks the p refcount */
21275 #endif
21276    peer->ps = ast_tvnow();
21277    if (xmitres == XMIT_ERROR) {
21278       sip_poke_noanswer(peer);   /* Immediately unreachable, network problems */
21279    } else if (!force) {
21280       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, peer->maxms * 2, sip_poke_noanswer, peer,
21281             unref_peer(_data, "removing poke peer ref"),
21282             unref_peer(peer, "removing poke peer ref"),
21283             ref_peer(peer, "adding poke peer ref"));
21284    }
21285    dialog_unref(p, "unref dialog at end of sip_poke_peer, obtained from sip_alloc, just before it goes out of scope");
21286    return 0;
21287 }
21288 
21289 /*! \brief Part of PBX channel interface
21290 \note
21291 \par  Return values:---
21292 
21293    If we have qualify on and the device is not reachable, regardless of registration
21294    state we return AST_DEVICE_UNAVAILABLE
21295 
21296    For peers with call limit:
21297       - not registered        AST_DEVICE_UNAVAILABLE
21298       - registered, no call         AST_DEVICE_NOT_INUSE
21299       - registered, active calls    AST_DEVICE_INUSE
21300       - registered, call limit reached AST_DEVICE_BUSY
21301       - registered, onhold       AST_DEVICE_ONHOLD
21302       - registered, ringing         AST_DEVICE_RINGING
21303 
21304    For peers without call limit:
21305       - not registered        AST_DEVICE_UNAVAILABLE
21306       - registered            AST_DEVICE_NOT_INUSE
21307       - fixed IP (!dynamic)         AST_DEVICE_NOT_INUSE
21308    
21309    Peers that does not have a known call and can't be reached by OPTIONS
21310       - unreachable           AST_DEVICE_UNAVAILABLE
21311 
21312    If we return AST_DEVICE_UNKNOWN, the device state engine will try to find
21313    out a state by walking the channel list.
21314 
21315    The queue system (\ref app_queue.c) treats a member as "active"
21316    if devicestate is != AST_DEVICE_UNAVAILBALE && != AST_DEVICE_INVALID
21317 
21318    When placing a call to the queue member, queue system sets a member to busy if
21319    != AST_DEVICE_NOT_INUSE and != AST_DEVICE_UNKNOWN
21320 
21321 */
21322 static int sip_devicestate(void *data)
21323 {
21324    char *host;
21325    char *tmp;
21326    struct sip_peer *p;
21327 
21328    int res = AST_DEVICE_INVALID;
21329 
21330    /* make sure data is not null. Maybe unnecessary, but better be safe */
21331    host = ast_strdupa(data ? data : "");
21332    if ((tmp = strchr(host, '@')))
21333       host = tmp + 1;
21334 
21335    ast_debug(3, "Checking device state for peer %s\n", host);
21336 
21337    /* If find_peer asks for a realtime peer, then this breaks rtautoclear.  This
21338     * is because when a peer tries to autoexpire, the last thing it does is to
21339     * queue up an event telling the system that the devicestate has changed
21340     * (presumably to unavailable).  If we ask for a realtime peer here, this would
21341     * load it BACK into memory, thus defeating the point of trying to clear dead
21342     * hosts out of memory.
21343     */
21344    if ((p = find_peer(host, NULL, FALSE, FINDALLDEVICES, TRUE))) {
21345       if (p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) {
21346          /* we have an address for the peer */
21347       
21348          /* Check status in this order
21349             - Hold
21350             - Ringing
21351             - Busy (enforced only by call limit)
21352             - Inuse (we have a call)
21353             - Unreachable (qualify)
21354             If we don't find any of these state, report AST_DEVICE_NOT_INUSE
21355             for registered devices */
21356 
21357          if (p->onHold)
21358             /* First check for hold or ring states */
21359             res = AST_DEVICE_ONHOLD;
21360          else if (p->inRinging) {
21361             if (p->inRinging == p->inUse)
21362                res = AST_DEVICE_RINGING;
21363             else
21364                res = AST_DEVICE_RINGINUSE;
21365          } else if (p->call_limit && (p->inUse == p->call_limit))
21366             /* check call limit */
21367             res = AST_DEVICE_BUSY;
21368          else if (p->call_limit && p->busy_level && p->inUse >= p->busy_level)
21369             /* We're forcing busy before we've reached the call limit */
21370             res = AST_DEVICE_BUSY;
21371          else if (p->call_limit && p->inUse)
21372             /* Not busy, but we do have a call */
21373             res = AST_DEVICE_INUSE;
21374          else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0))) 
21375             /* We don't have a call. Are we reachable at all? Requires qualify= */
21376             res = AST_DEVICE_UNAVAILABLE;
21377          else  /* Default reply if we're registered and have no other data */
21378             res = AST_DEVICE_NOT_INUSE;
21379       } else {
21380          /* there is no address, it's unavailable */
21381          res = AST_DEVICE_UNAVAILABLE;
21382       }
21383       unref_peer(p, "unref_peer, from sip_devicestate, release ref from find_peer");
21384    } else {
21385       res = AST_DEVICE_UNKNOWN;
21386    }
21387 
21388    return res;
21389 }
21390 
21391 /*! \brief PBX interface function -build SIP pvt structure 
21392  * SIP calls initiated by the PBX arrive here. 
21393  *
21394  * \verbatim   
21395  *    SIP Dial string syntax
21396  *    SIP/exten@host!dnid
21397  * or SIP/host/exten!dnid
21398  * or SIP/host!dnid
21399  * \endverbatim
21400 */
21401 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause)
21402 {
21403    struct sip_pvt *p;
21404    struct ast_channel *tmpc = NULL;
21405    char *ext = NULL, *host;
21406    char tmp[256];
21407    char *dest = data;
21408    char *dnid;
21409    char *secret = NULL;
21410    char *md5secret = NULL;
21411    char *authname = NULL;
21412    char *trans = NULL;
21413    enum sip_transport transport = 0;
21414    int oldformat = format;
21415 
21416    /* mask request with some set of allowed formats.
21417     * XXX this needs to be fixed.
21418     * The original code uses AST_FORMAT_AUDIO_MASK, but it is
21419     * unclear what to use here. We have global_capabilities, which is
21420     * configured from sip.conf, and sip_tech.capabilities, which is
21421     * hardwired to all audio formats.
21422     */
21423    format &= AST_FORMAT_AUDIO_MASK;
21424    if (!format) {
21425       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));
21426       *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;   /* Can't find codec to connect to host */
21427       return NULL;
21428    }
21429    ast_debug(1, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));
21430 
21431    if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE, NULL))) {
21432       ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", dest);
21433       *cause = AST_CAUSE_SWITCH_CONGESTION;
21434       return NULL;
21435    }
21436 
21437    p->outgoing_call = TRUE;
21438 
21439    if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
21440       dialog_unlink_all(p, TRUE, TRUE);
21441       dialog_unref(p, "unref dialog p from mem fail");
21442       /* sip_destroy(p); */
21443       ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
21444       *cause = AST_CAUSE_SWITCH_CONGESTION;
21445       return NULL;
21446    }
21447 
21448    /* Save the destination, the SIP dial string */
21449    ast_copy_string(tmp, dest, sizeof(tmp));
21450 
21451 
21452    /* Find DNID and take it away */
21453    dnid = strchr(tmp, '!');
21454    if (dnid != NULL) {
21455       *dnid++ = '\0';
21456       ast_string_field_set(p, todnid, dnid);
21457    }
21458 
21459    /* Find at sign - @ */
21460    host = strchr(tmp, '@');
21461    if (host) {
21462       *host++ = '\0';
21463       ext = tmp;
21464       secret = strchr(ext, ':');
21465    }
21466    if (secret) {
21467       *secret++ = '\0';
21468       md5secret = strchr(secret, ':');
21469    }
21470    if (md5secret) {
21471       *md5secret++ = '\0';
21472       authname = strchr(md5secret, ':');
21473    }
21474    if (authname) {
21475       *authname++ = '\0';
21476       trans = strchr(authname, ':');
21477    }
21478    if (trans) {
21479       *trans++ = '\0';
21480       if (!strcasecmp(trans, "tcp"))
21481          transport = SIP_TRANSPORT_TCP;
21482       else if (!strcasecmp(trans, "tls"))
21483          transport = SIP_TRANSPORT_TLS;
21484       else {
21485          if (strcasecmp(trans, "udp"))
21486             ast_log(LOG_WARNING, "'%s' is not a valid transport option to Dial() for SIP calls, using udp by default.\n", trans);
21487          transport = SIP_TRANSPORT_UDP;
21488       }
21489    } else { /* use default */
21490       transport = SIP_TRANSPORT_UDP;
21491    }
21492 
21493    if (!host) {
21494       ext = strchr(tmp, '/');
21495       if (ext) 
21496          *ext++ = '\0';
21497       host = tmp;
21498    }
21499 
21500    set_socket_transport(&p->socket, transport);
21501 
21502    /* We now have 
21503       host = peer name, DNS host name or DNS domain (for SRV) 
21504       ext = extension (user part of URI)
21505       dnid = destination of the call (applies to the To: header)
21506    */
21507    if (create_addr(p, host, NULL, 1)) {
21508       *cause = AST_CAUSE_UNREGISTERED;
21509       ast_debug(3, "Cant create SIP call - target device not registered\n");
21510       dialog_unlink_all(p, TRUE, TRUE);
21511       dialog_unref(p, "unref dialog p UNREGISTERED");
21512       /* sip_destroy(p); */
21513       return NULL;
21514    }
21515    if (ast_strlen_zero(p->peername) && ext)
21516       ast_string_field_set(p, peername, ext);
21517    /* Recalculate our side, and recalculate Call ID */
21518    ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
21519    build_via(p);
21520    ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
21521    build_callid_pvt(p);
21522    ao2_t_link(dialogs, p, "Linking in under new name");
21523    
21524    /* We have an extension to call, don't use the full contact here */
21525    /* This to enable dialing registered peers with extension dialling,
21526       like SIP/peername/extension   
21527       SIP/peername will still use the full contact 
21528     */
21529    if (ext) {
21530       ast_string_field_set(p, username, ext);
21531       ast_string_field_set(p, fullcontact, NULL);
21532    }
21533    if (secret && !ast_strlen_zero(secret))
21534       ast_string_field_set(p, peersecret, secret);
21535 
21536    if (md5secret && !ast_strlen_zero(md5secret))
21537       ast_string_field_set(p, peermd5secret, md5secret);
21538 
21539    if (authname && !ast_strlen_zero(authname))
21540       ast_string_field_set(p, authname, authname);
21541 #if 0
21542    printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
21543 #endif
21544    p->prefcodec = oldformat;           /* Format for this call */
21545    p->jointcapability = oldformat;
21546    sip_pvt_lock(p);
21547    tmpc = sip_new(p, AST_STATE_DOWN, host);  /* Place the call */
21548    if (global_callevents)
21549       manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
21550          "Channel: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
21551          p->owner? p->owner->name : "", "SIP", p->callid, p->fullcontact, p->peername);
21552    sip_pvt_unlock(p);
21553    if (!tmpc) {
21554       dialog_unlink_all(p, TRUE, TRUE);
21555       /* sip_destroy(p); */
21556    }
21557    dialog_unref(p, "toss pvt ptr at end of sip_request_call");
21558    ast_update_use_count();
21559    restart_monitor();
21560    return tmpc;
21561 }
21562 
21563 /*! \brief Parse insecure= setting in sip.conf and set flags according to setting */
21564 static void set_insecure_flags (struct ast_flags *flags, const char *value, int lineno)
21565 {
21566    if (ast_strlen_zero(value))
21567       return;
21568 
21569    if (!ast_false(value)) {
21570       char buf[64];
21571       char *word, *next;
21572 
21573       ast_copy_string(buf, value, sizeof(buf));
21574       next = buf;
21575       while ((word = strsep(&next, ","))) {
21576          if (!strcasecmp(word, "port"))
21577             ast_set_flag(&flags[0], SIP_INSECURE_PORT);
21578          else if (!strcasecmp(word, "invite"))
21579             ast_set_flag(&flags[0], SIP_INSECURE_INVITE);
21580          else
21581             ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
21582       }
21583    }
21584 }
21585 
21586 /*!
21587   \brief Handle flag-type options common to configuration of devices - peers
21588   \param flags array of two struct ast_flags
21589   \param mask array of two struct ast_flags
21590   \param v linked list of config variables to process
21591   \returns non-zero if any config options were handled, zero otherwise
21592 */
21593 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
21594 {
21595    int res = 1;
21596 
21597    if (!strcasecmp(v->name, "trustrpid")) {
21598       ast_set_flag(&mask[0], SIP_TRUSTRPID);
21599       ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
21600    } else if (!strcasecmp(v->name, "sendrpid")) {
21601       ast_set_flag(&mask[0], SIP_SENDRPID);
21602       ast_set2_flag(&flags[0], ast_true(v->value), SIP_SENDRPID);
21603    } else if (!strcasecmp(v->name, "g726nonstandard")) {
21604       ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
21605       ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
21606    } else if (!strcasecmp(v->name, "useclientcode")) {
21607       ast_set_flag(&mask[0], SIP_USECLIENTCODE);
21608       ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
21609    } else if (!strcasecmp(v->name, "dtmfmode")) {
21610       ast_set_flag(&mask[0], SIP_DTMF);
21611       ast_clear_flag(&flags[0], SIP_DTMF);
21612       if (!strcasecmp(v->value, "inband"))
21613          ast_set_flag(&flags[0], SIP_DTMF_INBAND);
21614       else if (!strcasecmp(v->value, "rfc2833"))
21615          ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
21616       else if (!strcasecmp(v->value, "info"))
21617          ast_set_flag(&flags[0], SIP_DTMF_INFO);
21618       else if (!strcasecmp(v->value, "shortinfo"))
21619          ast_set_flag(&flags[0], SIP_DTMF_SHORTINFO);
21620       else if (!strcasecmp(v->value, "auto"))
21621          ast_set_flag(&flags[0], SIP_DTMF_AUTO);
21622       else {
21623          ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
21624          ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
21625       }
21626    } else if (!strcasecmp(v->name, "nat")) {
21627       ast_set_flag(&mask[0], SIP_NAT);
21628       ast_clear_flag(&flags[0], SIP_NAT);
21629       if (!strcasecmp(v->value, "never"))
21630          ast_set_flag(&flags[0], SIP_NAT_NEVER);
21631       else if (!strcasecmp(v->value, "route"))
21632          ast_set_flag(&flags[0], SIP_NAT_ROUTE);
21633       else if (ast_true(v->value))
21634          ast_set_flag(&flags[0], SIP_NAT_ALWAYS);
21635       else
21636          ast_set_flag(&flags[0], SIP_NAT_RFC3581);
21637    } else if (!strcasecmp(v->name, "canreinvite")) {
21638       ast_set_flag(&mask[0], SIP_REINVITE);
21639       ast_clear_flag(&flags[0], SIP_REINVITE);
21640       if (ast_true(v->value)) {
21641          ast_set_flag(&flags[0], SIP_CAN_REINVITE | SIP_CAN_REINVITE_NAT);
21642       } else if (!ast_false(v->value)) {
21643          char buf[64];
21644          char *word, *next = buf;
21645 
21646          ast_copy_string(buf, v->value, sizeof(buf));
21647          while ((word = strsep(&next, ","))) {
21648             if (!strcasecmp(word, "update")) {
21649                ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_CAN_REINVITE);
21650             } else if (!strcasecmp(word, "nonat")) {
21651                ast_set_flag(&flags[0], SIP_CAN_REINVITE);
21652                ast_clear_flag(&flags[0], SIP_CAN_REINVITE_NAT);
21653             } else {
21654                ast_log(LOG_WARNING, "Unknown canreinvite mode '%s' on line %d\n", v->value, v->lineno);
21655             }
21656          }
21657       }
21658    } else if (!strcasecmp(v->name, "insecure")) {
21659       ast_set_flag(&mask[0], SIP_INSECURE);
21660       ast_clear_flag(&flags[0], SIP_INSECURE);
21661       set_insecure_flags(&flags[0], v->value, v->lineno);   
21662    } else if (!strcasecmp(v->name, "progressinband")) {
21663       ast_set_flag(&mask[0], SIP_PROG_INBAND);
21664       ast_clear_flag(&flags[0], SIP_PROG_INBAND);
21665       if (ast_true(v->value))
21666          ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
21667       else if (strcasecmp(v->value, "never"))
21668          ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
21669    } else if (!strcasecmp(v->name, "promiscredir")) {
21670       ast_set_flag(&mask[0], SIP_PROMISCREDIR);
21671       ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
21672    } else if (!strcasecmp(v->name, "videosupport")) {
21673       if (!strcasecmp(v->value, "always")) {
21674          ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
21675          ast_set_flag(&flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
21676       } else {
21677          ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
21678          ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
21679       }
21680    } else if (!strcasecmp(v->name, "textsupport")) {
21681       ast_set_flag(&mask[1], SIP_PAGE2_TEXTSUPPORT);
21682       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_TEXTSUPPORT);
21683       res = 1;
21684    } else if (!strcasecmp(v->name, "allowoverlap")) {
21685       ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
21686       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWOVERLAP);
21687    } else if (!strcasecmp(v->name, "allowsubscribe")) {
21688       ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
21689       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
21690    } else if (!strcasecmp(v->name, "ignoresdpversion")) {
21691       ast_set_flag(&mask[1], SIP_PAGE2_IGNORESDPVERSION);
21692       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_IGNORESDPVERSION);
21693    } else if (!strcasecmp(v->name, "t38pt_udptl")) {
21694       char buf[16], *word, *next = buf;
21695 
21696       ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT);
21697 
21698       ast_copy_string(buf, v->value, sizeof(buf));
21699 
21700       while ((word = strsep(&next, ","))) {
21701          if (ast_true(word) || !strcasecmp(word, "fec")) {
21702             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
21703             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_FEC);
21704          } else if (!strcasecmp(word, "redundancy")) {
21705             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
21706             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY);
21707          } else if (!strcasecmp(word, "none")) {
21708             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
21709             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
21710          }
21711       }
21712    } else if (!strcasecmp(v->name, "rfc2833compensate")) {
21713       ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
21714       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
21715    } else if (!strcasecmp(v->name, "buggymwi")) {
21716       ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
21717       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
21718    } else if (!strcasecmp(v->name, "t38pt_usertpsource")) {
21719       ast_set_flag(&mask[1], SIP_PAGE2_UDPTL_DESTINATION);
21720       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_UDPTL_DESTINATION);
21721    } else
21722       res = 0;
21723 
21724    return res;
21725 }
21726 
21727 /*! \brief Add SIP domain to list of domains we are responsible for */
21728 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
21729 {
21730    struct domain *d;
21731 
21732    if (ast_strlen_zero(domain)) {
21733       ast_log(LOG_WARNING, "Zero length domain.\n");
21734       return 1;
21735    }
21736 
21737    if (!(d = ast_calloc(1, sizeof(*d))))
21738       return 0;
21739 
21740    ast_copy_string(d->domain, domain, sizeof(d->domain));
21741 
21742    if (!ast_strlen_zero(context))
21743       ast_copy_string(d->context, context, sizeof(d->context));
21744 
21745    d->mode = mode;
21746 
21747    AST_LIST_LOCK(&domain_list);
21748    AST_LIST_INSERT_TAIL(&domain_list, d, list);
21749    AST_LIST_UNLOCK(&domain_list);
21750 
21751    if (sipdebug)  
21752       ast_debug(1, "Added local SIP domain '%s'\n", domain);
21753 
21754    return 1;
21755 }
21756 
21757 /*! \brief  check_sip_domain: Check if domain part of uri is local to our server */
21758 static int check_sip_domain(const char *domain, char *context, size_t len)
21759 {
21760    struct domain *d;
21761    int result = 0;
21762 
21763    AST_LIST_LOCK(&domain_list);
21764    AST_LIST_TRAVERSE(&domain_list, d, list) {
21765       if (strcasecmp(d->domain, domain))
21766          continue;
21767 
21768       if (len && !ast_strlen_zero(d->context))
21769          ast_copy_string(context, d->context, len);
21770       
21771       result = 1;
21772       break;
21773    }
21774    AST_LIST_UNLOCK(&domain_list);
21775 
21776    return result;
21777 }
21778 
21779 /*! \brief Clear our domain list (at reload) */
21780 static void clear_sip_domains(void)
21781 {
21782    struct domain *d;
21783 
21784    AST_LIST_LOCK(&domain_list);
21785    while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
21786       ast_free(d);
21787    AST_LIST_UNLOCK(&domain_list);
21788 }
21789 
21790 
21791 /*! \brief Add realm authentication in list */
21792 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno)
21793 {
21794    char authcopy[256];
21795    char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
21796    char *stringp;
21797    struct sip_auth *a, *b, *auth;
21798 
21799    if (ast_strlen_zero(configuration))
21800       return authlist;
21801 
21802    ast_debug(1, "Auth config ::  %s\n", configuration);
21803 
21804    ast_copy_string(authcopy, configuration, sizeof(authcopy));
21805    stringp = authcopy;
21806 
21807    username = stringp;
21808    realm = strrchr(stringp, '@');
21809    if (realm)
21810       *realm++ = '\0';
21811    if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
21812       ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
21813       return authlist;
21814    }
21815    stringp = username;
21816    username = strsep(&stringp, ":");
21817    if (username) {
21818       secret = strsep(&stringp, ":");
21819       if (!secret) {
21820          stringp = username;
21821          md5secret = strsep(&stringp, "#");
21822       }
21823    }
21824    if (!(auth = ast_calloc(1, sizeof(*auth))))
21825       return authlist;
21826 
21827    ast_copy_string(auth->realm, realm, sizeof(auth->realm));
21828    ast_copy_string(auth->username, username, sizeof(auth->username));
21829    if (secret)
21830       ast_copy_string(auth->secret, secret, sizeof(auth->secret));
21831    if (md5secret)
21832       ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
21833 
21834    /* find the end of the list */
21835    for (b = NULL, a = authlist; a ; b = a, a = a->next)
21836       ;
21837    if (b)
21838       b->next = auth;   /* Add structure add end of list */
21839    else
21840       authlist = auth;
21841 
21842    ast_verb(3, "Added authentication for realm %s\n", realm);
21843 
21844    return authlist;
21845 
21846 }
21847 
21848 /*! \brief Clear realm authentication list (at reload) */
21849 static int clear_realm_authentication(struct sip_auth *authlist)
21850 {
21851    struct sip_auth *a = authlist;
21852    struct sip_auth *b;
21853 
21854    while (a) {
21855       b = a;
21856       a = a->next;
21857       ast_free(b);
21858    }
21859 
21860    return 1;
21861 }
21862 
21863 /*! \brief Find authentication for a specific realm */
21864 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm)
21865 {
21866    struct sip_auth *a;
21867 
21868    for (a = authlist; a; a = a->next) {
21869       if (!strcasecmp(a->realm, realm))
21870          break;
21871    }
21872 
21873    return a;
21874 }
21875 
21876 /*! \brief
21877  * implement the setvar config line
21878  */
21879 static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
21880 {
21881    struct ast_variable *tmpvar = NULL;
21882    char *varname = ast_strdupa(buf), *varval = NULL;
21883    
21884    if ((varval = strchr(varname, '='))) {
21885       *varval++ = '\0';
21886       if ((tmpvar = ast_variable_new(varname, varval, ""))) {
21887          tmpvar->next = list;
21888          list = tmpvar;
21889       }
21890    }
21891    return list;
21892 }
21893 
21894 /*! \brief Set peer defaults before configuring specific configurations */
21895 static void set_peer_defaults(struct sip_peer *peer)
21896 {
21897    if (peer->expire == 0) {
21898       /* Don't reset expire or port time during reload 
21899          if we have an active registration 
21900       */
21901       peer->expire = -1;
21902       peer->pokeexpire = -1;
21903       peer->addr.sin_port = htons(STANDARD_SIP_PORT);
21904       set_socket_transport(&peer->socket, SIP_TRANSPORT_UDP);
21905    }
21906    peer->type = SIP_TYPE_PEER;
21907    ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
21908    ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
21909    strcpy(peer->context, default_context);
21910    strcpy(peer->subscribecontext, default_subscribecontext);
21911    strcpy(peer->language, default_language);
21912    strcpy(peer->mohinterpret, default_mohinterpret);
21913    strcpy(peer->mohsuggest, default_mohsuggest);
21914    peer->addr.sin_family = AF_INET;
21915    peer->defaddr.sin_family = AF_INET;
21916    peer->capability = global_capability;
21917    peer->maxcallbitrate = default_maxcallbitrate;
21918    peer->rtptimeout = global_rtptimeout;
21919    peer->rtpholdtimeout = global_rtpholdtimeout;
21920    peer->rtpkeepalive = global_rtpkeepalive;
21921    peer->allowtransfer = global_allowtransfer;
21922    peer->autoframing = global_autoframing;
21923    peer->qualifyfreq = global_qualifyfreq;
21924    if (global_callcounter)
21925       peer->call_limit=999;
21926    strcpy(peer->vmexten, default_vmexten);
21927    peer->secret[0] = '\0';
21928    peer->md5secret[0] = '\0';
21929    peer->cid_num[0] = '\0';
21930    peer->cid_name[0] = '\0';
21931    peer->fromdomain[0] = '\0';
21932    peer->fromuser[0] = '\0';
21933    peer->regexten[0] = '\0';
21934    peer->callgroup = 0;
21935    peer->pickupgroup = 0;
21936    peer->maxms = default_qualify;
21937    peer->prefs = default_prefs;
21938    peer->stimer.st_mode_oper = global_st_mode;  /* Session-Timers */
21939    peer->stimer.st_ref = global_st_refresher;
21940    peer->stimer.st_min_se = global_min_se;
21941    peer->stimer.st_max_se = global_max_se;
21942    peer->timer_t1 = global_t1;
21943    peer->timer_b = global_timer_b;
21944    clear_peer_mailboxes(peer);
21945 }
21946 
21947 /*! \brief Create temporary peer (used in autocreatepeer mode) */
21948 static struct sip_peer *temp_peer(const char *name)
21949 {
21950    struct sip_peer *peer;
21951 
21952    if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
21953       return NULL;
21954 
21955    ast_atomic_fetchadd_int(&apeerobjs, 1);
21956    set_peer_defaults(peer);
21957 
21958    ast_copy_string(peer->name, name, sizeof(peer->name));
21959 
21960    peer->selfdestruct = TRUE;
21961    peer->host_dynamic = TRUE;
21962    peer->prefs = default_prefs;
21963    reg_source_db(peer);
21964 
21965    return peer;
21966 }
21967 
21968 /*! \todo document this function */
21969 static void add_peer_mailboxes(struct sip_peer *peer, const char *value)
21970 {
21971    char *next, *mbox, *context;
21972 
21973    next = ast_strdupa(value);
21974 
21975    while ((mbox = context = strsep(&next, ","))) {
21976       struct sip_mailbox *mailbox;
21977 
21978       if (!(mailbox = ast_calloc(1, sizeof(*mailbox))))
21979          continue;
21980 
21981       strsep(&context, "@");
21982       if (ast_strlen_zero(mbox)) {
21983          ast_free(mailbox);
21984          continue;
21985       }
21986       mailbox->mailbox = ast_strdup(mbox);
21987       mailbox->context = ast_strdup(context);
21988 
21989       AST_LIST_INSERT_TAIL(&peer->mailboxes, mailbox, entry);
21990    }
21991 }
21992 
21993 /*! \brief Build peer from configuration (file or realtime static/dynamic) */
21994 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime)
21995 {
21996    struct sip_peer *peer = NULL;
21997    struct ast_ha *oldha = NULL;
21998    int found = 0;
21999    int firstpass = 1;
22000    int format = 0;      /* Ama flags */
22001    time_t regseconds = 0;
22002    struct ast_flags peerflags[2] = {{(0)}};
22003    struct ast_flags mask[2] = {{(0)}};
22004    char callback[256] = "";
22005    struct sip_peer tmp_peer;
22006    const char *srvlookup = NULL;
22007    static int deprecation_warning = 1;
22008    int alt_fullcontact = alt ? 1 : 0;
22009    struct ast_str *fullcontact = ast_str_alloca(512);
22010 
22011    if (!realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
22012       /* Note we do NOT use find_peer here, to avoid realtime recursion */
22013       /* We also use a case-sensitive comparison (unlike find_peer) so
22014          that case changes made to the peer name will be properly handled
22015          during reload
22016       */
22017       ast_copy_string(tmp_peer.name, name, sizeof(tmp_peer.name));
22018       peer = ao2_t_find(peers, &tmp_peer, OBJ_POINTER | OBJ_UNLINK, "find and unlink peer from peers table");
22019    }
22020 
22021    if (peer) {
22022       /* Already in the list, remove it and it will be added back (or FREE'd)  */
22023       found++;
22024       if (!(peer->the_mark))
22025          firstpass = 0;
22026    } else {
22027       if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
22028          return NULL;
22029 
22030       if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
22031          ast_atomic_fetchadd_int(&rpeerobjs, 1);
22032          ast_debug(3, "-REALTIME- peer built. Name: %s. Peer objects: %d\n", name, rpeerobjs);
22033       } else
22034          ast_atomic_fetchadd_int(&speerobjs, 1);
22035    }
22036 
22037    /* Note that our peer HAS had its reference count increased */
22038    if (firstpass) {
22039       peer->lastmsgssent = -1;
22040       oldha = peer->ha;
22041       peer->ha = NULL;
22042       set_peer_defaults(peer);   /* Set peer defaults */
22043       peer->type = 0;
22044    }
22045    if (!found && name)
22046       ast_copy_string(peer->name, name, sizeof(peer->name));
22047 
22048    /* If we have channel variables, remove them (reload) */
22049    if (peer->chanvars) {
22050       ast_variables_destroy(peer->chanvars);
22051       peer->chanvars = NULL;
22052       /* XXX should unregister ? */
22053    }
22054 
22055    /* If we have realm authentication information, remove them (reload) */
22056    clear_realm_authentication(peer->auth);
22057    peer->auth = NULL;
22058    peer->default_outbound_transport = 0;
22059    peer->transports = 0;
22060 
22061    for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
22062       if (handle_common_options(&peerflags[0], &mask[0], v))
22063          continue;
22064       if (!strcasecmp(v->name, "transport") && !ast_strlen_zero(v->value)) {
22065          char *val = ast_strdupa(v->value);
22066          char *trans;
22067 
22068          while ((trans = strsep(&val, ","))) {
22069             trans = ast_skip_blanks(trans);
22070 
22071             if (!strncasecmp(trans, "udp", 3))
22072                peer->transports |= SIP_TRANSPORT_UDP;
22073             else if (!strncasecmp(trans, "tcp", 3))
22074                peer->transports |= SIP_TRANSPORT_TCP;
22075             else if (!strncasecmp(trans, "tls", 3))
22076                peer->transports |= SIP_TRANSPORT_TLS;
22077             else
22078                ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
22079 
22080             if (!peer->default_outbound_transport) { /*!< The first transport listed should be default outbound */
22081                peer->default_outbound_transport = peer->transports;
22082             }
22083          }
22084       } else if (realtime && !strcasecmp(v->name, "regseconds")) {
22085          ast_get_time_t(v->value, &regseconds, 0, NULL);
22086       } else if (realtime && !strcasecmp(v->name, "lastms")) {
22087          sscanf(v->value, "%30d", &peer->lastms);
22088       } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
22089          inet_aton(v->value, &(peer->addr.sin_addr));
22090       } else if (realtime && !strcasecmp(v->name, "name"))
22091          ast_copy_string(peer->name, v->value, sizeof(peer->name));
22092       else if (realtime && !strcasecmp(v->name, "fullcontact")) {
22093          if (alt_fullcontact && !alt) {
22094             /* Reset, because the alternate also has a fullcontact and we
22095              * do NOT want the field value to be doubled. It might be
22096              * tempting to skip this, but the first table might not have
22097              * fullcontact and since we're here, we know that the alternate
22098              * absolutely does. */
22099             alt_fullcontact = 0;
22100             ast_str_reset(fullcontact);
22101          }
22102          /* Reconstruct field, because realtime separates our value at the ';' */
22103          if (fullcontact->used > 0) {
22104             ast_str_append(&fullcontact, 0, ";%s", v->value);
22105          } else {
22106             ast_str_set(&fullcontact, 0, "%s", v->value);
22107          }
22108       } else if (!strcasecmp(v->name, "type")) {
22109          if (!strcasecmp(v->value, "peer")) {
22110             peer->type |= SIP_TYPE_PEER;
22111          } else if (!strcasecmp(v->value, "user")) {
22112             peer->type |= SIP_TYPE_USER;
22113          } else if (!strcasecmp(v->value, "friend")) {
22114             peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
22115          }
22116       } else if (!strcasecmp(v->name, "secret")) 
22117          ast_copy_string(peer->secret, v->value, sizeof(peer->secret));
22118       else if (!strcasecmp(v->name, "md5secret")) 
22119          ast_copy_string(peer->md5secret, v->value, sizeof(peer->md5secret));
22120       else if (!strcasecmp(v->name, "auth"))
22121          peer->auth = add_realm_authentication(peer->auth, v->value, v->lineno);
22122       else if (!strcasecmp(v->name, "callerid")) {
22123          ast_callerid_split(v->value, peer->cid_name, sizeof(peer->cid_name), peer->cid_num, sizeof(peer->cid_num));
22124       } else if (!strcasecmp(v->name, "fullname")) {
22125          ast_copy_string(peer->cid_name, v->value, sizeof(peer->cid_name));
22126       } else if (!strcasecmp(v->name, "cid_number")) {
22127          ast_copy_string(peer->cid_num, v->value, sizeof(peer->cid_num));
22128       } else if (!strcasecmp(v->name, "context")) {
22129          ast_copy_string(peer->context, v->value, sizeof(peer->context));
22130       } else if (!strcasecmp(v->name, "subscribecontext")) {
22131          ast_copy_string(peer->subscribecontext, v->value, sizeof(peer->subscribecontext));
22132       } else if (!strcasecmp(v->name, "fromdomain")) {
22133          ast_copy_string(peer->fromdomain, v->value, sizeof(peer->fromdomain));
22134       } else if (!strcasecmp(v->name, "usereqphone")) {
22135          ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
22136       } else if (!strcasecmp(v->name, "fromuser")) {
22137          ast_copy_string(peer->fromuser, v->value, sizeof(peer->fromuser));
22138       } else if (!strcasecmp(v->name, "outboundproxy")) {
22139          char *port, *next, *force, *proxyname;
22140          int forceopt = FALSE;
22141          /* Set peer channel variable */
22142          next = proxyname = ast_strdupa(v->value);
22143          if ((port = strchr(proxyname, ':'))) {
22144             *port++ = '\0';
22145             next = port;
22146          }
22147          if ((force = strchr(next, ','))) {
22148             *force++ = '\0';
22149             forceopt = strcmp(force, "force");
22150          }
22151          /* Allocate proxy object */
22152          peer->outboundproxy = proxy_allocate(proxyname, port, forceopt);
22153       } else if (!strcasecmp(v->name, "host")) {
22154          if (!strcasecmp(v->value, "dynamic")) {
22155             /* They'll register with us */
22156             if (!found || !peer->host_dynamic) {
22157                /* Initialize stuff if this is a new peer, or if it used to
22158                 * not be dynamic before the reload. */
22159                memset(&peer->addr.sin_addr, 0, 4);
22160                if (peer->addr.sin_port) {
22161                   /* If we've already got a port, make it the default rather than absolute */
22162                   peer->defaddr.sin_port = peer->addr.sin_port;
22163                   peer->addr.sin_port = 0;
22164                }
22165             }
22166             peer->host_dynamic = TRUE;
22167          } else {
22168             /* Non-dynamic.  Make sure we become that way if we're not */
22169             AST_SCHED_DEL_UNREF(sched, peer->expire,
22170                   unref_peer(peer, "removing register expire ref"));
22171             peer->host_dynamic = FALSE;
22172             srvlookup = v->value;
22173             if (global_dynamic_exclude_static) {
22174                int err = 0;
22175                global_contact_ha = ast_append_ha("deny", (char *)ast_inet_ntoa(peer->addr.sin_addr), global_contact_ha, &err);
22176                if (err) {
22177                   ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
22178                }
22179             }
22180          }
22181       } else if (!strcasecmp(v->name, "defaultip")) {
22182          if (ast_get_ip(&peer->defaddr, v->value)) {
22183             unref_peer(peer, "unref_peer: from build_peer defaultip");
22184             return NULL;
22185          }
22186       } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
22187          int ha_error = 0;
22188 
22189          peer->ha = ast_append_ha(v->name, v->value, peer->ha, &ha_error);
22190          if (ha_error)
22191             ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
22192       } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
22193          int ha_error = 0;
22194          peer->contactha = ast_append_ha(v->name + 7, v->value, peer->contactha, &ha_error);
22195          if (ha_error) {
22196             ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
22197          }
22198       } else if (!strcasecmp(v->name, "port")) {
22199          if (!realtime && peer->host_dynamic)
22200             peer->defaddr.sin_port = htons(atoi(v->value));
22201          else
22202             peer->addr.sin_port = htons(atoi(v->value));
22203       } else if (!strcasecmp(v->name, "callingpres")) {
22204          peer->callingpres = ast_parse_caller_presentation(v->value);
22205          if (peer->callingpres == -1)
22206             peer->callingpres = atoi(v->value);
22207       } else if (!strcasecmp(v->name, "username") || !strcmp(v->name, "defaultuser")) {   /* "username" is deprecated */
22208          ast_copy_string(peer->username, v->value, sizeof(peer->username));
22209          if (!strcasecmp(v->name, "username")) {
22210             if (deprecation_warning) {
22211                ast_log(LOG_NOTICE, "The 'username' field for sip peers has been deprecated in favor of the term 'defaultuser'\n");
22212                deprecation_warning = 0;
22213             }
22214             peer->deprecated_username = 1;
22215          }
22216       } else if (!strcasecmp(v->name, "language")) {
22217          ast_copy_string(peer->language, v->value, sizeof(peer->language));
22218       } else if (!strcasecmp(v->name, "regexten")) {
22219          ast_copy_string(peer->regexten, v->value, sizeof(peer->regexten));
22220       } else if (!strcasecmp(v->name, "callbackextension")) {
22221          ast_copy_string(callback, v->value, sizeof(callback));
22222       } else if (!strcasecmp(v->name, "callcounter")) {
22223          peer->call_limit = ast_true(v->value) ? 999 : 0;
22224       } else if (!strcasecmp(v->name, "call-limit")) {
22225          peer->call_limit = atoi(v->value);
22226          if (peer->call_limit < 0)
22227             peer->call_limit = 0;
22228       } else if (!strcasecmp(v->name, "busylevel")) {
22229          peer->busy_level = atoi(v->value);
22230          if (peer->busy_level < 0)
22231             peer->busy_level = 0;
22232       } else if (!strcasecmp(v->name, "amaflags")) {
22233          format = ast_cdr_amaflags2int(v->value);
22234          if (format < 0) {
22235             ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
22236          } else {
22237             peer->amaflags = format;
22238          }
22239       } else if (!strcasecmp(v->name, "accountcode")) {
22240          ast_copy_string(peer->accountcode, v->value, sizeof(peer->accountcode));
22241       } else if (!strcasecmp(v->name, "mohinterpret")) {
22242          ast_copy_string(peer->mohinterpret, v->value, sizeof(peer->mohinterpret));
22243       } else if (!strcasecmp(v->name, "mohsuggest")) {
22244          ast_copy_string(peer->mohsuggest, v->value, sizeof(peer->mohsuggest));
22245       } else if (!strcasecmp(v->name, "parkinglot")) {
22246          ast_copy_string(peer->parkinglot, v->value, sizeof(peer->parkinglot));
22247       } else if (!strcasecmp(v->name, "mailbox")) {
22248          add_peer_mailboxes(peer, v->value);
22249       } else if (!strcasecmp(v->name, "hasvoicemail")) {
22250          /* People expect that if 'hasvoicemail' is set, that the mailbox will
22251           * be also set, even if not explicitly specified. */
22252          if (ast_true(v->value) && AST_LIST_EMPTY(&peer->mailboxes)) {
22253             add_peer_mailboxes(peer, name);
22254          }
22255       } else if (!strcasecmp(v->name, "subscribemwi")) {
22256          ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
22257       } else if (!strcasecmp(v->name, "vmexten")) {
22258          ast_copy_string(peer->vmexten, v->value, sizeof(peer->vmexten));
22259       } else if (!strcasecmp(v->name, "callgroup")) {
22260          peer->callgroup = ast_get_group(v->value);
22261       } else if (!strcasecmp(v->name, "allowtransfer")) {
22262          peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
22263       } else if (!strcasecmp(v->name, "pickupgroup")) {
22264          peer->pickupgroup = ast_get_group(v->value);
22265       } else if (!strcasecmp(v->name, "allow")) {
22266          int error =  ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, TRUE);
22267          if (error)
22268             ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
22269       } else if (!strcasecmp(v->name, "disallow")) {
22270          int error =  ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, FALSE);
22271          if (error)
22272             ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
22273       } else if (!strcasecmp(v->name, "registertrying")) {
22274          ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_REGISTERTRYING);
22275       } else if (!strcasecmp(v->name, "autoframing")) {
22276          peer->autoframing = ast_true(v->value);
22277       } else if (!strcasecmp(v->name, "rtptimeout")) {
22278          if ((sscanf(v->value, "%30d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
22279             ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
22280             peer->rtptimeout = global_rtptimeout;
22281          }
22282       } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
22283          if ((sscanf(v->value, "%30d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
22284             ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
22285             peer->rtpholdtimeout = global_rtpholdtimeout;
22286          }
22287       } else if (!strcasecmp(v->name, "rtpkeepalive")) {
22288          if ((sscanf(v->value, "%30d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
22289             ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d.  Using default.\n", v->value, v->lineno);
22290             peer->rtpkeepalive = global_rtpkeepalive;
22291          }
22292       } else if (!strcasecmp(v->name, "timert1")) {
22293          if ((sscanf(v->value, "%30d", &peer->timer_t1) != 1) || (peer->timer_t1 < 0)) {
22294             ast_log(LOG_WARNING, "'%s' is not a valid T1 time at line %d.  Using default.\n", v->value, v->lineno);
22295             peer->timer_t1 = global_t1;
22296          }
22297          /* Note that Timer B is dependent upon T1 and MUST NOT be lower
22298           * than T1 * 64, according to RFC 3261, Section 17.1.1.2 */
22299          if (peer->timer_b < peer->timer_t1 * 64) {
22300             peer->timer_b = peer->timer_t1 * 64;
22301          }
22302       } else if (!strcasecmp(v->name, "timerb")) {
22303          if ((sscanf(v->value, "%30d", &peer->timer_b) != 1) || (peer->timer_b < 0)) {
22304             ast_log(LOG_WARNING, "'%s' is not a valid Timer B time at line %d.  Using default.\n", v->value, v->lineno);
22305             peer->timer_b = global_timer_b;
22306          }
22307          if (peer->timer_b < peer->timer_t1 * 64) {
22308             static int warning = 0;
22309             if (warning++ % 20 == 0) {
22310                ast_log(LOG_WARNING, "Timer B has been set lower than recommended. (RFC 3261, 17.1.1.2)\n");
22311             }
22312          }
22313       } else if (!strcasecmp(v->name, "setvar")) {
22314          peer->chanvars = add_var(v->value, peer->chanvars);
22315       } else if (!strcasecmp(v->name, "qualify")) {
22316          if (!strcasecmp(v->value, "no")) {
22317             peer->maxms = 0;
22318          } else if (!strcasecmp(v->value, "yes")) {
22319             peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
22320          } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
22321             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);
22322             peer->maxms = 0;
22323          }
22324          if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->maxms > 0) {
22325             /* This would otherwise cause a network storm, where the
22326              * qualify response refreshes the peer from the database,
22327              * which in turn causes another qualify to be sent, ad
22328              * infinitum. */
22329             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);
22330             peer->maxms = 0;
22331          }
22332       } else if (!strcasecmp(v->name, "qualifyfreq")) {
22333          int i;
22334          if (sscanf(v->value, "%30d", &i) == 1)
22335             peer->qualifyfreq = i * 1000;  
22336          else {
22337             ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
22338             peer->qualifyfreq = global_qualifyfreq;
22339          }
22340       } else if (!strcasecmp(v->name, "maxcallbitrate")) {
22341          peer->maxcallbitrate = atoi(v->value);
22342          if (peer->maxcallbitrate < 0)
22343             peer->maxcallbitrate = default_maxcallbitrate;
22344       } else if (!strcasecmp(v->name, "session-timers")) {
22345          int i = (int) str2stmode(v->value); 
22346          if (i < 0) {
22347             ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
22348             peer->stimer.st_mode_oper = global_st_mode;
22349          } else {
22350             peer->stimer.st_mode_oper = i;
22351          }
22352       } else if (!strcasecmp(v->name, "session-expires")) {
22353          if (sscanf(v->value, "%30d", &peer->stimer.st_max_se) != 1) {
22354             ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
22355             peer->stimer.st_max_se = global_max_se;
22356          } 
22357       } else if (!strcasecmp(v->name, "session-minse")) {
22358          if (sscanf(v->value, "%30d", &peer->stimer.st_min_se) != 1) {
22359             ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
22360             peer->stimer.st_min_se = global_min_se;
22361          } 
22362          if (peer->stimer.st_min_se < 90) {
22363             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);
22364             peer->stimer.st_min_se = global_min_se;
22365          } 
22366       } else if (!strcasecmp(v->name, "session-refresher")) {
22367          int i = (int) str2strefresher(v->value); 
22368          if (i < 0) {
22369             ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
22370             peer->stimer.st_ref = global_st_refresher;
22371          } else {
22372             peer->stimer.st_ref = i;
22373          }
22374       }
22375    }
22376 
22377    if (!peer->default_outbound_transport) {
22378       peer->transports  = SIP_TRANSPORT_UDP;
22379       peer->default_outbound_transport = SIP_TRANSPORT_UDP;
22380    }
22381 
22382    /* The default transport type set during build_peer should only replace the socket.type when...
22383     * 1. Registration is not present and the socket.type and default transport types are different.
22384     * 2. The socket.type is not an acceptable transport type after rebuilding peer.
22385     * 3. The socket.type is not set yet. */
22386    if (((peer->socket.type != peer->default_outbound_transport) && (peer->expire == -1)) ||
22387       !(peer->socket.type & peer->transports) || !(peer->socket.type)) {
22388 
22389       set_socket_transport(&peer->socket, peer->default_outbound_transport);
22390    }
22391 
22392    if (fullcontact->used > 0) {
22393       ast_copy_string(peer->fullcontact, fullcontact->str, sizeof(peer->fullcontact));
22394       peer->rt_fromcontact = TRUE;
22395       /* We have a hostname in the fullcontact, but if we don't have an
22396        * address listed on the entry (or if it's 'dynamic'), then we need to
22397        * parse the entry to obtain the IP address, so a dynamic host can be
22398        * contacted immediately after reload (as opposed to waiting for it to
22399        * register once again). But if we have an address for this peer and NAT was
22400        * specified, use that address instead. */
22401       /* XXX May need to revisit the final argument; does the realtime DB store whether
22402        * the original contact was over TLS or not? XXX */
22403       if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) || !peer->addr.sin_addr.s_addr) {
22404          __set_address_from_contact(fullcontact->str, &peer->addr, 0);
22405       }
22406    }
22407 
22408    if (srvlookup && peer->dnsmgr == NULL) {
22409       char transport[MAXHOSTNAMELEN];
22410       char _srvlookup[MAXHOSTNAMELEN];
22411       char *params;
22412 
22413       ast_copy_string(_srvlookup, srvlookup, sizeof(_srvlookup));
22414       if ((params = strchr(_srvlookup, ';'))) {
22415          *params++ = '\0';
22416       }
22417 
22418       snprintf(transport, sizeof(transport), "_sip._%s", get_transport(peer->socket.type));
22419 
22420       if (ast_dnsmgr_lookup(_srvlookup, &peer->addr, &peer->dnsmgr, global_srvlookup ? transport : NULL)) {
22421          ast_log(LOG_ERROR, "srvlookup failed for host: %s, on peer %s, removing peer\n", _srvlookup, peer->name);
22422          unref_peer(peer, "getting rid of a peer pointer");
22423          return NULL;
22424       }
22425 
22426       ast_copy_string(peer->tohost, srvlookup, sizeof(peer->tohost));
22427    }
22428 
22429    if (!peer->addr.sin_port)
22430       peer->addr.sin_port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
22431 
22432    if (!peer->socket.port)
22433       peer->socket.port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
22434 
22435    if (!sip_cfg.ignore_regexpire && peer->host_dynamic && realtime) {
22436       time_t nowtime = time(NULL);
22437 
22438       if ((nowtime - regseconds) > 0) {
22439          destroy_association(peer);
22440          memset(&peer->addr, 0, sizeof(peer->addr));
22441          peer->lastms = -1;
22442          ast_debug(1, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
22443       }
22444    }
22445 
22446    /* Startup regular pokes */
22447    if (realtime && peer->lastms > 0) {
22448       ref_peer(peer, "schedule qualify");
22449       sip_poke_peer(peer, 0);
22450    }
22451 
22452    ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
22453    ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
22454    if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE))
22455       global_allowsubscribe = TRUE; /* No global ban any more */
22456    if (!found && peer->host_dynamic && !peer->is_realtime)
22457       reg_source_db(peer);
22458 
22459    /* If they didn't request that MWI is sent *only* on subscribe, go ahead and
22460     * subscribe to it now. */
22461    if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) && 
22462       !AST_LIST_EMPTY(&peer->mailboxes)) {
22463       add_peer_mwi_subs(peer);
22464       /* Send MWI from the event cache only.  This is so we can send initial
22465        * MWI if app_voicemail got loaded before chan_sip.  If it is the other
22466        * way, then we will get events when app_voicemail gets loaded. */
22467       sip_send_mwi_to_peer(peer, NULL, 1);
22468    }
22469    peer->the_mark = 0;
22470 
22471    ast_free_ha(oldha);
22472    if (!ast_strlen_zero(callback)) { /* build string from peer info */
22473       char *reg_string;
22474 
22475       if (asprintf(&reg_string, "%s?%s:%s@%s/%s", peer->name, peer->username, peer->secret, peer->tohost, callback) < 0) {
22476          ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
22477       } else   if (reg_string) {
22478          sip_register(reg_string, 0); /* XXX TODO: count in registry_count */
22479          ast_free(reg_string);
22480       }
22481    }
22482    return peer;
22483 }
22484 
22485 static int peer_markall_func(void *device, void *arg, int flags)
22486 {
22487    struct sip_peer *peer = device;
22488    peer->the_mark = 1;
22489    return 0;
22490 }
22491 
22492 /*! \brief Re-read SIP.conf config file
22493 \note This function reloads all config data, except for
22494    active peers (with registrations). They will only
22495    change configuration data at restart, not at reload.
22496    SIP debug and recordhistory state will not change
22497  */
22498 static int reload_config(enum channelreloadreason reason)
22499 {
22500    struct ast_config *cfg, *ucfg;
22501    struct ast_variable *v;
22502    struct sip_peer *peer;
22503    char *cat, *stringp, *context, *oldregcontext;
22504    char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
22505    struct ast_flags dummy[2];
22506    struct ast_flags config_flags = { reason == CHANNEL_MODULE_LOAD ? 0 : CONFIG_FLAG_FILEUNCHANGED };
22507    int auto_sip_domains = FALSE;
22508    struct sockaddr_in old_bindaddr = bindaddr;
22509    int registry_count = 0, peer_count = 0;
22510    time_t run_start, run_end;
22511    
22512    run_start = time(0);
22513    ast_unload_realtime("sipregs");     
22514    ast_unload_realtime("sippeers");
22515    cfg = ast_config_load(config, config_flags);
22516 
22517    /* We *must* have a config file otherwise stop immediately */
22518    if (!cfg) {
22519       ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
22520       return -1;
22521    } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
22522       ucfg = ast_config_load("users.conf", config_flags);
22523       if (ucfg == CONFIG_STATUS_FILEUNCHANGED)
22524          return 1;
22525       /* Must reread both files, because one changed */
22526       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
22527       cfg = ast_config_load(config, config_flags);
22528    } else {
22529       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
22530       ucfg = ast_config_load("users.conf", config_flags);
22531    }
22532 
22533    /* Initialize tcp sockets */
22534    memset(&sip_tcp_desc.local_address, 0, sizeof(sip_tcp_desc.local_address));
22535    memset(&sip_tls_desc.local_address, 0, sizeof(sip_tls_desc.local_address));
22536 
22537    ast_free_ha(global_contact_ha);
22538    global_contact_ha = NULL;
22539 
22540    default_tls_cfg.enabled = FALSE;    /* Default: Disable TLS */
22541 
22542    sip_tcp_desc.local_address.sin_port = htons(STANDARD_SIP_PORT);
22543    sip_tls_desc.local_address.sin_port = htons(STANDARD_TLS_PORT);
22544 
22545    if (reason != CHANNEL_MODULE_LOAD) {
22546       ast_debug(4, "--------------- SIP reload started\n");
22547 
22548       clear_realm_authentication(authl);
22549       clear_sip_domains();
22550       authl = NULL;
22551 
22552       /* First, destroy all outstanding registry calls */
22553       /* This is needed, since otherwise active registry entries will not be destroyed */
22554       ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {  /* regl is locked */
22555 
22556             ASTOBJ_RDLOCK(iterator); /* now regl is locked, and the object is also locked */
22557             if (iterator->call) {
22558                ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
22559                /* This will also remove references to the registry */
22560                dialog_unlink_all(iterator->call, TRUE, TRUE);
22561                iterator->call = dialog_unref(iterator->call, "remove iterator->call from registry traversal");
22562             }
22563             if (iterator->expire > -1) {
22564                AST_SCHED_DEL_UNREF(sched, iterator->expire, registry_unref(iterator, "reg ptr unref from reload config"));
22565             }
22566             if (iterator->timeout > -1) {
22567                AST_SCHED_DEL_UNREF(sched, iterator->timeout, registry_unref(iterator, "reg ptr unref from reload config"));
22568             }
22569             ASTOBJ_UNLOCK(iterator);
22570             
22571       } while(0));
22572 
22573       /* Then, actually destroy users and registry */
22574       ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
22575       ast_debug(4, "--------------- Done destroying registry list\n");
22576       ao2_t_callback(peers, OBJ_NODATA, peer_markall_func, 0, "callback to mark all peers");
22577    }
22578    
22579    /* Reset certificate handling for TLS sessions */
22580    if (reason != CHANNEL_MODULE_LOAD) {
22581       ast_free(default_tls_cfg.certfile);
22582       ast_free(default_tls_cfg.cipher);
22583       ast_free(default_tls_cfg.cafile);
22584       ast_free(default_tls_cfg.capath);
22585    }
22586    default_tls_cfg.certfile = ast_strdup(AST_CERTFILE); /*XXX Not sure if this is useful */
22587    default_tls_cfg.cipher = ast_strdup("");
22588    default_tls_cfg.cafile = ast_strdup("");
22589    default_tls_cfg.capath = ast_strdup("");
22590    
22591    /* Initialize copy of current global_regcontext for later use in removing stale contexts */
22592    ast_copy_string(oldcontexts, global_regcontext, sizeof(oldcontexts));
22593    oldregcontext = oldcontexts;
22594 
22595    /* Clear all flags before setting default values */
22596    /* Preserve debugging settings for console */
22597    sipdebug &= sip_debug_console;
22598    ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
22599    ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
22600 
22601    /* Reset IP addresses  */
22602    memset(&bindaddr, 0, sizeof(bindaddr));
22603    memset(&stunaddr, 0, sizeof(stunaddr));
22604    memset(&internip, 0, sizeof(internip));
22605 
22606    /* Free memory for local network address mask */
22607    ast_free_ha(localaddr);
22608    memset(&localaddr, 0, sizeof(localaddr));
22609    memset(&externip, 0, sizeof(externip));
22610    memset(&default_prefs, 0 , sizeof(default_prefs));
22611    memset(&global_outboundproxy, 0, sizeof(struct sip_proxy));
22612    global_outboundproxy.ip.sin_port = htons(STANDARD_SIP_PORT);
22613    global_outboundproxy.ip.sin_family = AF_INET;   /*!< Type of address: IPv4 */
22614    global_outboundproxy.force = FALSE;    /*!< Don't force proxy usage, use route: headers */
22615    ourport_tcp = STANDARD_SIP_PORT;
22616    ourport_tls = STANDARD_TLS_PORT;
22617    bindaddr.sin_port = htons(STANDARD_SIP_PORT);
22618    global_srvlookup = DEFAULT_SRVLOOKUP;
22619    global_tos_sip = DEFAULT_TOS_SIP;
22620    global_tos_audio = DEFAULT_TOS_AUDIO;
22621    global_tos_video = DEFAULT_TOS_VIDEO;
22622    global_tos_text = DEFAULT_TOS_TEXT;
22623    global_cos_sip = DEFAULT_COS_SIP;
22624    global_cos_audio = DEFAULT_COS_AUDIO;
22625    global_cos_video = DEFAULT_COS_VIDEO;
22626    global_cos_text = DEFAULT_COS_TEXT;
22627 
22628    externhost[0] = '\0';         /* External host name (for behind NAT DynDNS support) */
22629    externexpire = 0;       /* Expiration for DNS re-issuing */
22630    externrefresh = 10;
22631 
22632    /* Reset channel settings to default before re-configuring */
22633    allow_external_domains = DEFAULT_ALLOW_EXT_DOM;          /* Allow external invites */
22634    global_regcontext[0] = '\0';
22635    global_regextenonqualify = DEFAULT_REGEXTENONQUALIFY;
22636    global_notifyringing = DEFAULT_NOTIFYRINGING;
22637    global_notifyhold = FALSE;    /*!< Keep track of hold status for a peer */
22638    global_directrtpsetup = FALSE;      /* Experimental feature, disabled by default */
22639    global_alwaysauthreject = 0;
22640    global_allowsubscribe = FALSE;
22641    snprintf(global_useragent, sizeof(global_useragent), "%s %s", DEFAULT_USERAGENT, ast_get_version());
22642    snprintf(global_sdpsession, sizeof(global_sdpsession), "%s %s", DEFAULT_SDPSESSION, ast_get_version());
22643    snprintf(global_sdpowner, sizeof(global_sdpowner), "%s", DEFAULT_SDPOWNER);
22644    ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
22645    ast_copy_string(global_realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM), sizeof(global_realm));
22646    ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
22647    compactheaders = DEFAULT_COMPACTHEADERS;
22648    global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
22649    global_regattempts_max = 0;
22650    pedanticsipchecking = DEFAULT_PEDANTIC;
22651    autocreatepeer = DEFAULT_AUTOCREATEPEER;
22652    global_autoframing = 0;
22653    global_allowguest = DEFAULT_ALLOWGUEST;
22654    global_callcounter = DEFAULT_CALLCOUNTER;
22655    global_match_auth_username = FALSE;    /*!< Match auth username if available instead of From: Default off. */
22656    global_rtptimeout = 0;
22657    global_rtpholdtimeout = 0;
22658    global_rtpkeepalive = 0;
22659    global_allowtransfer = TRANSFER_OPENFORALL;  /* Merrily accept all transfers by default */
22660    global_rtautoclear = 120;
22661    ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE);   /* Default for all devices: TRUE */
22662    ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP);     /* Default for all devices: TRUE */
22663    sip_cfg.peer_rtupdate = TRUE;
22664 
22665    /* Session-Timers */
22666    global_st_mode = SESSION_TIMER_MODE_ACCEPT;    
22667    global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
22668    global_min_se  = DEFAULT_MIN_SE;
22669    global_max_se  = DEFAULT_MAX_SE;
22670 
22671    /* Initialize some reasonable defaults at SIP reload (used both for channel and as default for devices */
22672    ast_copy_string(default_context, DEFAULT_CONTEXT, sizeof(default_context));
22673    default_subscribecontext[0] = '\0';
22674    default_language[0] = '\0';
22675    default_fromdomain[0] = '\0';
22676    default_qualify = DEFAULT_QUALIFY;
22677    default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
22678    ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
22679    ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
22680    ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
22681    ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833);        /*!< Default DTMF setting: RFC2833 */
22682    ast_set_flag(&global_flags[0], SIP_NAT_RFC3581);         /*!< NAT support if requested by device with rport */
22683    ast_set_flag(&global_flags[0], SIP_CAN_REINVITE);        /*!< Allow re-invites */
22684 
22685    /* Debugging settings, always default to off */
22686    dumphistory = FALSE;
22687    recordhistory = FALSE;
22688    sipdebug &= ~sip_debug_config;
22689 
22690    /* Misc settings for the channel */
22691    global_relaxdtmf = FALSE;
22692    global_callevents = FALSE;
22693    global_authfailureevents = FALSE;
22694    global_t1 = SIP_TIMER_T1;
22695    global_timer_b = 64 * SIP_TIMER_T1;
22696    global_t1min = DEFAULT_T1MIN;
22697    global_qualifyfreq = DEFAULT_QUALIFYFREQ;
22698 
22699    global_matchexterniplocally = FALSE;
22700 
22701    /* Copy the default jb config over global_jbconf */
22702    memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
22703 
22704    ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
22705    ast_clear_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT);
22706    ast_clear_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION);
22707 
22708 
22709    /* Read the [general] config section of sip.conf (or from realtime config) */
22710    for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
22711       if (handle_common_options(&global_flags[0], &dummy[0], v))
22712          continue;
22713       /* handle jb conf */
22714       if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
22715          continue;
22716 
22717       if (!strcasecmp(v->name, "context")) {
22718          ast_copy_string(default_context, v->value, sizeof(default_context));
22719       } else if (!strcasecmp(v->name, "subscribecontext")) {
22720          ast_copy_string(default_subscribecontext, v->value, sizeof(default_subscribecontext));
22721       } else if (!strcasecmp(v->name, "callcounter")) {
22722          global_callcounter = ast_true(v->value) ? 1 : 0;
22723       } else if (!strcasecmp(v->name, "allowguest")) {
22724          global_allowguest = ast_true(v->value) ? 1 : 0;
22725       } else if (!strcasecmp(v->name, "realm")) {
22726          ast_copy_string(global_realm, v->value, sizeof(global_realm));
22727       } else if (!strcasecmp(v->name, "useragent")) {
22728          ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
22729          ast_debug(1, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
22730       } else if (!strcasecmp(v->name, "sdpsession")) {
22731          ast_copy_string(global_sdpsession, v->value, sizeof(global_sdpsession));
22732       } else if (!strcasecmp(v->name, "sdpowner")) {
22733          /* Field cannot contain spaces */
22734          if (!strstr(v->value, " "))
22735             ast_copy_string(global_sdpowner, v->value, sizeof(global_sdpowner));
22736          else
22737             ast_log(LOG_WARNING, "'%s' must not contain spaces at line %d.  Using default.\n", v->value, v->lineno);
22738       } else if (!strcasecmp(v->name, "allowtransfer")) {
22739          global_allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
22740       } else if (!strcasecmp(v->name, "rtcachefriends")) {
22741          ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);   
22742       } else if (!strcasecmp(v->name, "rtsavesysname")) {
22743          sip_cfg.rtsave_sysname = ast_true(v->value);
22744       } else if (!strcasecmp(v->name, "rtupdate")) {
22745          sip_cfg.peer_rtupdate = ast_true(v->value);
22746       } else if (!strcasecmp(v->name, "ignoreregexpire")) {
22747          sip_cfg.ignore_regexpire = ast_true(v->value);
22748       } else if (!strcasecmp(v->name, "timert1")) {
22749          /* Defaults to 500ms, but RFC 3261 states that it is recommended
22750           * for the value to be set higher, though a lower value is only
22751           * allowed on private networks unconnected to the Internet. */
22752          global_t1 = atoi(v->value);
22753          /* Note that timer B is dependent on the value of T1 */
22754          global_timer_b = global_t1 * 64;
22755       } else if (!strcasecmp(v->name, "t1min")) {
22756          global_t1min = atoi(v->value);
22757       } else if (!strcasecmp(v->name, "tcpenable")) {
22758          sip_tcp_desc.local_address.sin_family = ast_false(v->value) ? 0 : AF_INET;
22759          ast_debug(2, "Enabling TCP socket for listening\n");
22760       } else if (!strcasecmp(v->name, "tcpbindaddr")) {
22761          int family = sip_tcp_desc.local_address.sin_family;
22762          if (ast_parse_arg(v->value, PARSE_INADDR, &sip_tcp_desc.local_address))
22763             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n", v->name, v->value, v->lineno, config);
22764          sip_tcp_desc.local_address.sin_family = family;
22765          ast_debug(2, "Setting TCP socket address to %s\n", v->value);
22766       } else if (!strcasecmp(v->name, "tlsenable")) {
22767          default_tls_cfg.enabled = ast_true(v->value) ? TRUE : FALSE;
22768          sip_tls_desc.local_address.sin_family = AF_INET;
22769       } else if (!strcasecmp(v->name, "tlscertfile")) {
22770          ast_free(default_tls_cfg.certfile);
22771          default_tls_cfg.certfile = ast_strdup(v->value);
22772       } else if (!strcasecmp(v->name, "tlscipher")) {
22773          ast_free(default_tls_cfg.cipher);
22774          default_tls_cfg.cipher = ast_strdup(v->value);
22775       } else if (!strcasecmp(v->name, "tlscafile")) {
22776          ast_free(default_tls_cfg.cafile);
22777          default_tls_cfg.cafile = ast_strdup(v->value);
22778       } else if (!strcasecmp(v->name, "tlscapath")) {
22779          ast_free(default_tls_cfg.capath);
22780          default_tls_cfg.capath = ast_strdup(v->value);
22781       } else if (!strcasecmp(v->name, "tlsverifyclient")) {
22782          ast_set2_flag(&default_tls_cfg.flags, ast_true(v->value), AST_SSL_VERIFY_CLIENT);   
22783       } else if (!strcasecmp(v->name, "tlsdontverifyserver")) {
22784          ast_set2_flag(&default_tls_cfg.flags, ast_true(v->value), AST_SSL_DONT_VERIFY_SERVER); 
22785       } else if (!strcasecmp(v->name, "tlsbindaddr")) {
22786          if (ast_parse_arg(v->value, PARSE_INADDR, &sip_tls_desc.local_address))
22787             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n", v->name, v->value, v->lineno, config);
22788       } else if (!strcasecmp(v->name, "dynamic_exclude_static") || !strcasecmp(v->name, "dynamic_excludes_static")) {
22789          global_dynamic_exclude_static = ast_true(v->value);
22790       } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
22791          int ha_error = 0;
22792          global_contact_ha = ast_append_ha(v->name + 7, v->value, global_contact_ha, &ha_error);
22793          if (ha_error) {
22794             ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
22795          }
22796       } else if (!strcasecmp(v->name, "rtautoclear")) {
22797          int i = atoi(v->value);
22798          if (i > 0)
22799             global_rtautoclear = i;
22800          else
22801             i = 0;
22802          ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
22803       } else if (!strcasecmp(v->name, "usereqphone")) {
22804          ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);   
22805       } else if (!strcasecmp(v->name, "relaxdtmf")) {
22806          global_relaxdtmf = ast_true(v->value);
22807       } else if (!strcasecmp(v->name, "vmexten")) {
22808          ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
22809       } else if (!strcasecmp(v->name, "rtptimeout")) {
22810          if ((sscanf(v->value, "%30d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
22811             ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
22812             global_rtptimeout = 0;
22813          }
22814       } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
22815          if ((sscanf(v->value, "%30d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
22816             ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
22817             global_rtpholdtimeout = 0;
22818          }
22819       } else if (!strcasecmp(v->name, "rtpkeepalive")) {
22820          if ((sscanf(v->value, "%30d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
22821             ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d.  Using default.\n", v->value, v->lineno);
22822             global_rtpkeepalive = 0;
22823          }
22824       } else if (!strcasecmp(v->name, "compactheaders")) {
22825          compactheaders = ast_true(v->value);
22826       } else if (!strcasecmp(v->name, "notifymimetype")) {
22827          ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
22828       } else if (!strcasecmp(v->name, "directrtpsetup")) {
22829          global_directrtpsetup = ast_true(v->value);
22830       } else if (!strcasecmp(v->name, "notifyringing")) {
22831          global_notifyringing = ast_true(v->value);
22832       } else if (!strcasecmp(v->name, "notifyhold")) {
22833          global_notifyhold = ast_true(v->value);
22834       } else if (!strcasecmp(v->name, "alwaysauthreject")) {
22835          global_alwaysauthreject = ast_true(v->value);
22836       } else if (!strcasecmp(v->name, "mohinterpret")) {
22837          ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
22838       } else if (!strcasecmp(v->name, "mohsuggest")) {
22839          ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
22840       } else if (!strcasecmp(v->name, "language")) {
22841          ast_copy_string(default_language, v->value, sizeof(default_language));
22842       } else if (!strcasecmp(v->name, "regcontext")) {
22843          ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
22844          stringp = newcontexts;
22845          /* Let's remove any contexts that are no longer defined in regcontext */
22846          cleanup_stale_contexts(stringp, oldregcontext);
22847          /* Create contexts if they don't exist already */
22848          while ((context = strsep(&stringp, "&"))) {
22849             ast_copy_string(used_context, context, sizeof(used_context));
22850             ast_context_find_or_create(NULL, NULL, context, "SIP");
22851          }
22852          ast_copy_string(global_regcontext, v->value, sizeof(global_regcontext));
22853       } else if (!strcasecmp(v->name, "regextenonqualify")) {
22854          global_regextenonqualify = ast_true(v->value);
22855       } else if (!strcasecmp(v->name, "callerid")) {
22856          ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
22857       } else if (!strcasecmp(v->name, "fromdomain")) {
22858          ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
22859       } else if (!strcasecmp(v->name, "outboundproxy")) {
22860          int portnum;
22861          char *tok, *proxyname;
22862 
22863          if (ast_strlen_zero(v->value)) {
22864             ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf.", v->lineno);
22865             continue;
22866          }
22867 
22868          tok = ast_skip_blanks(strtok(ast_strdupa(v->value), ","));
22869 
22870          sip_parse_host(tok, v->lineno, &proxyname, &portnum, &global_outboundproxy.transport);
22871 
22872          global_outboundproxy.ip.sin_port = htons(portnum);
22873    
22874          if ((tok = strtok(NULL, ","))) {
22875             global_outboundproxy.force = !strncasecmp(ast_skip_blanks(tok), "force", 5);
22876          } else {
22877             global_outboundproxy.force = FALSE;
22878          }
22879 
22880          if (ast_strlen_zero(proxyname)) {
22881             ast_log(LOG_WARNING, "you must specify a name for the outboundproxy on line %d of sip.conf.", v->lineno);
22882             global_outboundproxy.name[0] = '\0';
22883             continue;
22884          }
22885 
22886          ast_copy_string(global_outboundproxy.name, proxyname, sizeof(global_outboundproxy.name));
22887 
22888          proxy_update(&global_outboundproxy);
22889       } else if (!strcasecmp(v->name, "autocreatepeer")) {
22890          autocreatepeer = ast_true(v->value);
22891       } else if (!strcasecmp(v->name, "match_auth_username")) {
22892          global_match_auth_username = ast_true(v->value);
22893       } else if (!strcasecmp(v->name, "srvlookup")) {
22894          global_srvlookup = ast_true(v->value);
22895       } else if (!strcasecmp(v->name, "pedantic")) {
22896          pedanticsipchecking = ast_true(v->value);
22897       } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
22898          max_expiry = atoi(v->value);
22899          if (max_expiry < 1)
22900             max_expiry = DEFAULT_MAX_EXPIRY;
22901       } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
22902          min_expiry = atoi(v->value);
22903          if (min_expiry < 1)
22904             min_expiry = DEFAULT_MIN_EXPIRY;
22905       } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
22906          default_expiry = atoi(v->value);
22907          if (default_expiry < 1)
22908             default_expiry = DEFAULT_DEFAULT_EXPIRY;
22909       } else if (!strcasecmp(v->name, "sipdebug")) {
22910          if (ast_true(v->value))
22911             sipdebug |= sip_debug_config;
22912       } else if (!strcasecmp(v->name, "dumphistory")) {
22913          dumphistory = ast_true(v->value);
22914       } else if (!strcasecmp(v->name, "recordhistory")) {
22915          recordhistory = ast_true(v->value);
22916       } else if (!strcasecmp(v->name, "registertimeout")) {
22917          global_reg_timeout = atoi(v->value);
22918          if (global_reg_timeout < 1)
22919             global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
22920       } else if (!strcasecmp(v->name, "registerattempts")) {
22921          global_regattempts_max = atoi(v->value);
22922       } else if (!strcasecmp(v->name, "stunaddr")) {
22923          stunaddr.sin_port = htons(3478);
22924          if (ast_parse_arg(v->value, PARSE_INADDR, &stunaddr))
22925             ast_log(LOG_WARNING, "Invalid STUN server address: %s\n", v->value);
22926          externexpire = time(NULL);
22927       } else if (!strcasecmp(v->name, "bindaddr") || !strcasecmp(v->name, "udpbindaddr")) {
22928          if (ast_parse_arg(v->value, PARSE_INADDR, &bindaddr))
22929             ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
22930       } else if (!strcasecmp(v->name, "localnet")) {
22931          struct ast_ha *na;
22932          int ha_error = 0;
22933 
22934          if (!(na = ast_append_ha("d", v->value, localaddr, &ha_error)))
22935             ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
22936          else
22937             localaddr = na;
22938          if (ha_error)
22939             ast_log(LOG_ERROR, "Bad localnet configuration value line %d : %s\n", v->lineno, v->value);
22940       } else if (!strcasecmp(v->name, "externip")) {
22941          if (ast_parse_arg(v->value, PARSE_INADDR, &externip))
22942             ast_log(LOG_WARNING, "Invalid address for externip keyword: %s\n", v->value);
22943          externexpire = 0;
22944          /* If no port was specified use the value of bindport */
22945          if (!externip.sin_port)
22946             externip.sin_port = bindaddr.sin_port;
22947       } else if (!strcasecmp(v->name, "externhost")) {
22948          ast_copy_string(externhost, v->value, sizeof(externhost));
22949          if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
22950             ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
22951          externexpire = time(NULL);
22952          /* If no port was specified use the value of bindport */
22953          if (!externip.sin_port)
22954             externip.sin_port = bindaddr.sin_port;
22955       } else if (!strcasecmp(v->name, "externrefresh")) {
22956          if (sscanf(v->value, "%30d", &externrefresh) != 1) {
22957             ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
22958             externrefresh = 10;
22959          }
22960       } else if (!strcasecmp(v->name, "allow")) {
22961          int error =  ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, TRUE);
22962          if (error)
22963             ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
22964       } else if (!strcasecmp(v->name, "disallow")) {
22965          int error =  ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, FALSE);
22966          if (error)
22967             ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
22968       } else if (!strcasecmp(v->name, "autoframing")) {
22969          global_autoframing = ast_true(v->value);
22970       } else if (!strcasecmp(v->name, "allowexternaldomains")) {
22971          allow_external_domains = ast_true(v->value);
22972       } else if (!strcasecmp(v->name, "autodomain")) {
22973          auto_sip_domains = ast_true(v->value);
22974       } else if (!strcasecmp(v->name, "domain")) {
22975          char *domain = ast_strdupa(v->value);
22976          char *cntx = strchr(domain, ',');
22977 
22978          if (cntx)
22979             *cntx++ = '\0';
22980 
22981          if (ast_strlen_zero(cntx))
22982             ast_debug(1, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
22983          if (ast_strlen_zero(domain))
22984             ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
22985          else
22986             add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, cntx ? ast_strip(cntx) : "");
22987       } else if (!strcasecmp(v->name, "register")) {
22988          if (sip_register(v->value, v->lineno) == 0)
22989             registry_count++;
22990       } else if (!strcasecmp(v->name, "tos_sip")) {
22991          if (ast_str2tos(v->value, &global_tos_sip))
22992             ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, refer to QoS documentation\n", v->lineno);
22993       } else if (!strcasecmp(v->name, "tos_audio")) {
22994          if (ast_str2tos(v->value, &global_tos_audio))
22995             ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, refer to QoS documentation\n", v->lineno);
22996       } else if (!strcasecmp(v->name, "tos_video")) {
22997          if (ast_str2tos(v->value, &global_tos_video))
22998             ast_log(LOG_WARNING, "Invalid tos_video value at line %d, refer to QoS documentation\n", v->lineno);
22999       } else if (!strcasecmp(v->name, "tos_text")) {
23000          if (ast_str2tos(v->value, &global_tos_text))
23001             ast_log(LOG_WARNING, "Invalid tos_text value at line %d, refer to QoS documentation\n", v->lineno);
23002       } else if (!strcasecmp(v->name, "cos_sip")) {
23003          if (ast_str2cos(v->value, &global_cos_sip))
23004             ast_log(LOG_WARNING, "Invalid cos_sip value at line %d, refer to QoS documentation\n", v->lineno);
23005       } else if (!strcasecmp(v->name, "cos_audio")) {
23006          if (ast_str2cos(v->value, &global_cos_audio))
23007             ast_log(LOG_WARNING, "Invalid cos_audio value at line %d, refer to QoS documentation\n", v->lineno);
23008       } else if (!strcasecmp(v->name, "cos_video")) {
23009          if (ast_str2cos(v->value, &global_cos_video))
23010             ast_log(LOG_WARNING, "Invalid cos_video value at line %d, refer to QoS documentation\n", v->lineno);
23011       } else if (!strcasecmp(v->name, "cos_text")) {
23012          if (ast_str2cos(v->value, &global_cos_text))
23013             ast_log(LOG_WARNING, "Invalid cos_text value at line %d, refer to QoS documentation\n", v->lineno);
23014       } else if (!strcasecmp(v->name, "bindport")) {
23015          int i;
23016          if (sscanf(v->value, "%5d", &i) == 1) {
23017             bindaddr.sin_port = htons(i);
23018          } else {
23019             ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
23020          }
23021       } else if (!strcasecmp(v->name, "hash_user")) {
23022          int i;
23023          if (sscanf(v->value, "%30d", &i) == 1 && i > 2) {
23024             hash_user_size = i;
23025          } else {
23026             ast_log(LOG_WARNING, "Invalid hash_user size '%s' at line %d of %s -- should be much larger than 2\n", v->value, v->lineno, config);
23027          }
23028       } else if (!strcasecmp(v->name, "hash_peer")) {
23029          int i;
23030          if (sscanf(v->value, "%30d", &i) == 1 && i > 2) {
23031             hash_peer_size = i;
23032          } else {
23033             ast_log(LOG_WARNING, "Invalid hash_peer size '%s' at line %d of %s -- should be much larger than 2\n", v->value, v->lineno, config);
23034          }
23035       } else if (!strcasecmp(v->name, "hash_dialog")) {
23036          int i;
23037          if (sscanf(v->value, "%30d", &i) == 1 && i > 2) {
23038             hash_dialog_size = i;
23039          } else {
23040             ast_log(LOG_WARNING, "Invalid hash_dialog size '%s' at line %d of %s -- should be much larger than 2\n", v->value, v->lineno, config);
23041          }
23042       } else if (!strcasecmp(v->name, "qualify")) {
23043          if (!strcasecmp(v->value, "no")) {
23044             default_qualify = 0;
23045          } else if (!strcasecmp(v->value, "yes")) {
23046             default_qualify = DEFAULT_MAXMS;
23047          } else if (sscanf(v->value, "%30d", &default_qualify) != 1) {
23048             ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
23049             default_qualify = 0;
23050          }
23051       } else if (!strcasecmp(v->name, "qualifyfreq")) {
23052          int i;
23053          if (sscanf(v->value, "%30d", &i) == 1)
23054             global_qualifyfreq = i * 1000;
23055          else {
23056             ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
23057             global_qualifyfreq = DEFAULT_QUALIFYFREQ;
23058          }
23059       } else if (!strcasecmp(v->name, "callevents")) {
23060          global_callevents = ast_true(v->value);
23061       } else if (!strcasecmp(v->name, "authfailureevents")) {
23062          global_authfailureevents = ast_true(v->value);
23063       } else if (!strcasecmp(v->name, "maxcallbitrate")) {
23064          default_maxcallbitrate = atoi(v->value);
23065          if (default_maxcallbitrate < 0)
23066             default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
23067       } else if (!strcasecmp(v->name, "matchexterniplocally")) {
23068          global_matchexterniplocally = ast_true(v->value);
23069       } else if (!strcasecmp(v->name, "session-timers")) {
23070          int i = (int) str2stmode(v->value); 
23071          if (i < 0) {
23072             ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
23073             global_st_mode = SESSION_TIMER_MODE_ACCEPT;
23074          } else {
23075             global_st_mode = i;
23076          }
23077       } else if (!strcasecmp(v->name, "session-expires")) {
23078          if (sscanf(v->value, "%30d", &global_max_se) != 1) {
23079             ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
23080             global_max_se = DEFAULT_MAX_SE;
23081          } 
23082       } else if (!strcasecmp(v->name, "session-minse")) {
23083          if (sscanf(v->value, "%30d", &global_min_se) != 1) {
23084             ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
23085             global_min_se = DEFAULT_MIN_SE;
23086          } 
23087          if (global_min_se < 90) {
23088             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);
23089             global_min_se = DEFAULT_MIN_SE;
23090          } 
23091       } else if (!strcasecmp(v->name, "session-refresher")) {
23092          int i = (int) str2strefresher(v->value); 
23093          if (i < 0) {
23094             ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
23095             global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
23096          } else {
23097             global_st_refresher = i;
23098          }
23099       }
23100    }
23101 
23102    if (!allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
23103       ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
23104       allow_external_domains = 1;
23105    }
23106    
23107    /* Build list of authentication to various SIP realms, i.e. service providers */
23108    for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
23109       /* Format for authentication is auth = username:password@realm */
23110       if (!strcasecmp(v->name, "auth"))
23111          authl = add_realm_authentication(authl, v->value, v->lineno);
23112    }
23113    
23114    if (ucfg) {
23115       struct ast_variable *gen;
23116       int genhassip, genregistersip;
23117       const char *hassip, *registersip;
23118       
23119       genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
23120       genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
23121       gen = ast_variable_browse(ucfg, "general");
23122       cat = ast_category_browse(ucfg, NULL);
23123       while (cat) {
23124          if (strcasecmp(cat, "general")) {
23125             hassip = ast_variable_retrieve(ucfg, cat, "hassip");
23126             registersip = ast_variable_retrieve(ucfg, cat, "registersip");
23127             if (ast_true(hassip) || (!hassip && genhassip)) {
23128                peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0);
23129                if (peer) {
23130                   ao2_t_link(peers, peer, "link peer into peer table");
23131                   if ((peer->type & SIP_TYPE_PEER) && peer->addr.sin_addr.s_addr) {
23132                      ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
23133                   }
23134                   
23135                   unref_peer(peer, "unref_peer: from reload_config");
23136                   peer_count++;
23137                }
23138             }
23139             if (ast_true(registersip) || (!registersip && genregistersip)) {
23140                char tmp[256];
23141                const char *host = ast_variable_retrieve(ucfg, cat, "host");
23142                const char *username = ast_variable_retrieve(ucfg, cat, "username");
23143                const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
23144                const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
23145                if (!host)
23146                   host = ast_variable_retrieve(ucfg, "general", "host");
23147                if (!username)
23148                   username = ast_variable_retrieve(ucfg, "general", "username");
23149                if (!secret)
23150                   secret = ast_variable_retrieve(ucfg, "general", "secret");
23151                if (!contact)
23152                   contact = "s";
23153                if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
23154                   if (!ast_strlen_zero(secret))
23155                      snprintf(tmp, sizeof(tmp), "%s:%s@%s/%s", username, secret, host, contact);
23156                   else
23157                      snprintf(tmp, sizeof(tmp), "%s@%s/%s", username, host, contact);
23158                   if (sip_register(tmp, 0) == 0)
23159                      registry_count++;
23160                }
23161             }
23162          }
23163          cat = ast_category_browse(ucfg, cat);
23164       }
23165       ast_config_destroy(ucfg);
23166    }
23167    
23168 
23169    /* Load peers, users and friends */
23170    cat = NULL;
23171    while ( (cat = ast_category_browse(cfg, cat)) ) {
23172       const char *utype;
23173       if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
23174          continue;
23175       utype = ast_variable_retrieve(cfg, cat, "type");
23176       if (!utype) {
23177          ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
23178          continue;
23179       } else {
23180          if (!strcasecmp(utype, "user")) {
23181             ;
23182          } else if (!strcasecmp(utype, "friend")) {
23183             ;
23184          } else if (!strcasecmp(utype, "peer")) {
23185             ;
23186          } else {
23187             ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
23188             continue;
23189          }
23190          peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0);
23191          if (peer) {
23192             ao2_t_link(peers, peer, "link peer into peers table");
23193             if ((peer->type & SIP_TYPE_PEER) && peer->addr.sin_addr.s_addr) {
23194                ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
23195             }
23196             unref_peer(peer, "unref the result of the build_peer call. Now, the links from the tables are the only ones left.");
23197             peer_count++;
23198          }
23199       }
23200    }
23201    
23202    /* Set UDP address and open socket */
23203    bindaddr.sin_family = AF_INET;
23204    internip = bindaddr;
23205    if (ast_find_ourip(&internip.sin_addr, bindaddr)) {
23206       ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
23207       ast_config_destroy(cfg);
23208       return 0;
23209    }
23210    ast_mutex_lock(&netlock);
23211    if ((sipsock > -1) && (memcmp(&old_bindaddr, &bindaddr, sizeof(struct sockaddr_in)))) {
23212       close(sipsock);
23213       sipsock = -1;
23214    }
23215    if (sipsock < 0) {
23216       sipsock = socket(AF_INET, SOCK_DGRAM, 0);
23217       if (sipsock < 0) {
23218          ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
23219          ast_config_destroy(cfg);
23220          return -1;
23221       } else {
23222          /* Allow SIP clients on the same host to access us: */
23223          const int reuseFlag = 1;
23224 
23225          setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
23226                (const char*)&reuseFlag,
23227                sizeof reuseFlag);
23228 
23229          ast_enable_packet_fragmentation(sipsock);
23230 
23231          if (bind(sipsock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
23232             ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
23233             ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
23234             strerror(errno));
23235             close(sipsock);
23236             sipsock = -1;
23237          } else {
23238             ast_verb(2, "SIP Listening on %s:%d\n",
23239                   ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
23240             ast_netsock_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
23241          }
23242       }
23243    }
23244    if (stunaddr.sin_addr.s_addr != 0) {
23245       ast_debug(1, "stun to %s:%d\n",
23246          ast_inet_ntoa(stunaddr.sin_addr) , ntohs(stunaddr.sin_port));
23247       ast_stun_request(sipsock, &stunaddr,
23248          NULL, &externip);
23249       ast_debug(1, "STUN sees us at %s:%d\n", 
23250          ast_inet_ntoa(externip.sin_addr) , ntohs(externip.sin_port));
23251    }
23252    ast_mutex_unlock(&netlock);
23253 
23254    /* Start TCP server */
23255    ast_tcptls_server_start(&sip_tcp_desc);
23256 
23257    /* Start TLS server if needed */
23258    memcpy(sip_tls_desc.tls_cfg, &default_tls_cfg, sizeof(default_tls_cfg));
23259 
23260    if (ast_ssl_setup(sip_tls_desc.tls_cfg))
23261       ast_tcptls_server_start(&sip_tls_desc);
23262    else if (sip_tls_desc.tls_cfg->enabled) {
23263       sip_tls_desc.tls_cfg = NULL;
23264       ast_log(LOG_WARNING, "SIP TLS server did not load because of errors.\n");
23265    }
23266 
23267 
23268    /* Add default domains - host name, IP address and IP:port
23269     * Only do this if user added any sip domain with "localdomains" 
23270     * In order to *not* break backwards compatibility 
23271     *    Some phones address us at IP only, some with additional port number 
23272     */
23273    if (auto_sip_domains) {
23274       char temp[MAXHOSTNAMELEN];
23275 
23276       /* First our default IP address */
23277       if (bindaddr.sin_addr.s_addr)
23278          add_sip_domain(ast_inet_ntoa(bindaddr.sin_addr), SIP_DOMAIN_AUTO, NULL);
23279       else
23280          ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
23281 
23282       /* If TCP is running on a different IP than UDP, then add it too */
23283       if (sip_tcp_desc.local_address.sin_addr.s_addr && !inaddrcmp(&bindaddr, &sip_tcp_desc.local_address))
23284          add_sip_domain(ast_inet_ntoa(sip_tcp_desc.local_address.sin_addr), SIP_DOMAIN_AUTO, NULL);
23285 
23286       /* If TLS is running on a differen IP than UDP and TCP, then add that too */
23287       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))
23288          add_sip_domain(ast_inet_ntoa(sip_tls_desc.local_address.sin_addr), SIP_DOMAIN_AUTO, NULL);
23289 
23290       /* Our extern IP address, if configured */
23291       if (externip.sin_addr.s_addr)
23292          add_sip_domain(ast_inet_ntoa(externip.sin_addr), SIP_DOMAIN_AUTO, NULL);
23293 
23294       /* Extern host name (NAT traversal support) */
23295       if (!ast_strlen_zero(externhost))
23296          add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
23297       
23298       /* Our host name */
23299       if (!gethostname(temp, sizeof(temp)))
23300          add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
23301    }
23302 
23303    /* Release configuration from memory */
23304    ast_config_destroy(cfg);
23305 
23306    /* Load the list of manual NOTIFY types to support */
23307    if (notify_types)
23308       ast_config_destroy(notify_types);
23309    notify_types = ast_config_load(notify_config, config_flags);
23310 
23311    /* Done, tell the manager */
23312    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);
23313    run_end = time(0);
23314    ast_debug(4, "SIP reload_config done...Runtime= %d sec\n", (int)(run_end-run_start));
23315 
23316    return 0;
23317 }
23318 
23319 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
23320 {
23321    struct sip_pvt *p;
23322    struct ast_udptl *udptl = NULL;
23323    
23324    p = chan->tech_pvt;
23325    if (!p)
23326       return NULL;
23327    
23328    sip_pvt_lock(p);
23329    if (p->udptl && ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
23330       udptl = p->udptl;
23331    sip_pvt_unlock(p);
23332    return udptl;
23333 }
23334 
23335 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
23336 {
23337    struct sip_pvt *p;
23338    
23339    p = chan->tech_pvt;
23340    if (!p)
23341       return -1;
23342    sip_pvt_lock(p);
23343    if (udptl)
23344       ast_udptl_get_peer(udptl, &p->udptlredirip);
23345    else
23346       memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
23347    if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
23348       if (!p->pendinginvite) {
23349          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);
23350          transmit_reinvite_with_sdp(p, TRUE, FALSE);
23351       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
23352          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);
23353          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
23354       }
23355    }
23356    /* Reset lastrtprx timer */
23357    p->lastrtprx = p->lastrtptx = time(NULL);
23358    sip_pvt_unlock(p);
23359    return 0;
23360 }
23361 
23362 /*! \brief Returns null if we can't reinvite audio (part of RTP interface) */
23363 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
23364 {
23365    struct sip_pvt *p = NULL;
23366    enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
23367 
23368    if (!(p = chan->tech_pvt))
23369       return AST_RTP_GET_FAILED;
23370 
23371    sip_pvt_lock(p);
23372    if (!(p->rtp)) {
23373       sip_pvt_unlock(p);
23374       return AST_RTP_GET_FAILED;
23375    }
23376 
23377    *rtp = p->rtp;
23378 
23379    if (ast_rtp_getnat(*rtp) && !ast_test_flag(&p->flags[0], SIP_CAN_REINVITE_NAT))
23380       res = AST_RTP_TRY_PARTIAL;
23381    else if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
23382       res = AST_RTP_TRY_NATIVE;
23383    else if (ast_test_flag(&global_jbconf, AST_JB_FORCED))
23384       res = AST_RTP_GET_FAILED;
23385 
23386    sip_pvt_unlock(p);
23387 
23388    return res;
23389 }
23390 
23391 /*! \brief Returns null if we can't reinvite video (part of RTP interface) */
23392 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
23393 {
23394    struct sip_pvt *p = NULL;
23395    enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
23396    
23397    if (!(p = chan->tech_pvt))
23398       return AST_RTP_GET_FAILED;
23399 
23400    sip_pvt_lock(p);
23401    if (!(p->vrtp)) {
23402       sip_pvt_unlock(p);
23403       return AST_RTP_GET_FAILED;
23404    }
23405 
23406    *rtp = p->vrtp;
23407 
23408    if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
23409       res = AST_RTP_TRY_NATIVE;
23410 
23411    sip_pvt_unlock(p);
23412 
23413    return res;
23414 }
23415 
23416 /*! \brief Returns null if we can't reinvite text (part of RTP interface) */
23417 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
23418 {
23419    struct sip_pvt *p = NULL;
23420    enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
23421    
23422    if (!(p = chan->tech_pvt))
23423       return AST_RTP_GET_FAILED;
23424 
23425    sip_pvt_lock(p);
23426    if (!(p->trtp)) {
23427       sip_pvt_unlock(p);
23428       return AST_RTP_GET_FAILED;
23429    }
23430 
23431    *rtp = p->trtp;
23432 
23433    if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
23434       res = AST_RTP_TRY_NATIVE;
23435 
23436    sip_pvt_unlock(p);
23437 
23438    return res;
23439 }
23440 
23441 /*! \brief Set the RTP peer for this call */
23442 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)
23443 {
23444    struct sip_pvt *p;
23445    int changed = 0;
23446 
23447    p = chan->tech_pvt;
23448    if (!p) 
23449       return -1;
23450 
23451    /* Disable early RTP bridge  */
23452    if (!ast_bridged_channel(chan) && !global_directrtpsetup)   /* We are in early state */
23453       return 0;
23454 
23455    sip_pvt_lock(p);
23456    if (p->alreadygone) {
23457       /* If we're destroyed, don't bother */
23458       sip_pvt_unlock(p);
23459       return 0;
23460    }
23461 
23462    /* if this peer cannot handle reinvites of the media stream to devices
23463       that are known to be behind a NAT, then stop the process now
23464    */
23465    if (nat_active && !ast_test_flag(&p->flags[0], SIP_CAN_REINVITE_NAT)) {
23466       sip_pvt_unlock(p);
23467       return 0;
23468    }
23469 
23470    if (rtp) {
23471       changed |= ast_rtp_get_peer(rtp, &p->redirip);
23472    } else if (p->redirip.sin_addr.s_addr || ntohs(p->redirip.sin_port) != 0) {
23473       memset(&p->redirip, 0, sizeof(p->redirip));
23474       changed = 1;
23475    }
23476    if (vrtp) {
23477       changed |= ast_rtp_get_peer(vrtp, &p->vredirip);
23478    } else if (p->vredirip.sin_addr.s_addr || ntohs(p->vredirip.sin_port) != 0) {
23479       memset(&p->vredirip, 0, sizeof(p->vredirip));
23480       changed = 1;
23481    }
23482    if (trtp) {
23483       changed |= ast_rtp_get_peer(trtp, &p->tredirip);
23484    } else if (p->tredirip.sin_addr.s_addr || ntohs(p->tredirip.sin_port) != 0) {
23485       memset(&p->tredirip, 0, sizeof(p->tredirip));
23486       changed = 1;
23487    }
23488    if (codecs && (p->redircodecs != codecs)) {
23489       p->redircodecs = codecs;
23490       changed = 1;
23491    }
23492    if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
23493       if (chan->_state != AST_STATE_UP) { /* We are in early state */
23494          if (p->do_history)
23495             append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
23496          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));
23497       } else if (!p->pendinginvite) {     /* We are up, and have no outstanding invite */
23498          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));
23499          transmit_reinvite_with_sdp(p, FALSE, FALSE);
23500       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
23501          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));
23502          /* We have a pending Invite. Send re-invite when we're done with the invite */
23503          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);   
23504       }
23505    }
23506    /* Reset lastrtprx timer */
23507    p->lastrtprx = p->lastrtptx = time(NULL);
23508    sip_pvt_unlock(p);
23509    return 0;
23510 }
23511 
23512 static char *synopsis_dtmfmode = "Change the dtmfmode for a SIP call";
23513 static char *descrip_dtmfmode = "  SIPDtmfMode(inband|info|rfc2833): Changes the dtmfmode for a SIP call\n";
23514 static char *app_dtmfmode = "SIPDtmfMode";
23515 
23516 static char *app_sipaddheader = "SIPAddHeader";
23517 static char *synopsis_sipaddheader = "Add a SIP header to the outbound call";
23518 
23519 static char *descrip_sipaddheader = ""
23520 "  SIPAddHeader(Header: Content):\n"
23521 "Adds a header to a SIP call placed with DIAL.\n"
23522 "Remember to user the X-header if you are adding non-standard SIP\n"
23523 "headers, like \"X-Asterisk-Accountcode:\". Use this with care.\n"
23524 "Adding the wrong headers may jeopardize the SIP dialog.\n"
23525 "Always returns 0\n";
23526 
23527 
23528 /*! \brief Set the DTMFmode for an outbound SIP call (application) */
23529 static int sip_dtmfmode(struct ast_channel *chan, void *data)
23530 {
23531    struct sip_pvt *p;
23532    char *mode = data;
23533 
23534    if (!data) {
23535       ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
23536       return 0;
23537    }
23538    ast_channel_lock(chan);
23539    if (!IS_SIP_TECH(chan->tech)) {
23540       ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
23541       ast_channel_unlock(chan);
23542       return 0;
23543    }
23544    p = chan->tech_pvt;
23545    if (!p) {
23546       ast_channel_unlock(chan);
23547       return 0;
23548    }
23549    sip_pvt_lock(p);
23550    if (!strcasecmp(mode, "info")) {
23551       ast_clear_flag(&p->flags[0], SIP_DTMF);
23552       ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
23553       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
23554    } else if (!strcasecmp(mode, "shortinfo")) {
23555       ast_clear_flag(&p->flags[0], SIP_DTMF);
23556       ast_set_flag(&p->flags[0], SIP_DTMF_SHORTINFO);
23557       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
23558    } else if (!strcasecmp(mode, "rfc2833")) {
23559       ast_clear_flag(&p->flags[0], SIP_DTMF);
23560       ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
23561       p->jointnoncodeccapability |= AST_RTP_DTMF;
23562    } else if (!strcasecmp(mode, "inband")) { 
23563       ast_clear_flag(&p->flags[0], SIP_DTMF);
23564       ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
23565       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
23566    } else
23567       ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n", mode);
23568    if (p->rtp)
23569       ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
23570    if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
23571       if (!p->vad) {
23572          p->vad = ast_dsp_new();
23573          ast_dsp_set_features(p->vad, DSP_FEATURE_DIGIT_DETECT);
23574       }
23575    } else {
23576       if (p->vad) {
23577          ast_dsp_free(p->vad);
23578          p->vad = NULL;
23579       }
23580    }
23581    sip_pvt_unlock(p);
23582    ast_channel_unlock(chan);
23583    return 0;
23584 }
23585 
23586 /*! \brief Add a SIP header to an outbound INVITE */
23587 static int sip_addheader(struct ast_channel *chan, void *data)
23588 {
23589    int no = 0;
23590    int ok = FALSE;
23591    char varbuf[30];
23592    char *inbuf = data, *subbuf;
23593    
23594    if (ast_strlen_zero(inbuf)) {
23595       ast_log(LOG_WARNING, "This application requires the argument: Header\n");
23596       return 0;
23597    }
23598    ast_channel_lock(chan);
23599 
23600    /* Check for headers */
23601    while (!ok && no <= 50) {
23602       no++;
23603       snprintf(varbuf, sizeof(varbuf), "__SIPADDHEADER%.2d", no);
23604 
23605       /* Compare without the leading underscores */
23606       if ((pbx_builtin_getvar_helper(chan, (const char *) varbuf + 2) == (const char *) NULL)) {
23607          ok = TRUE;
23608       }
23609    }
23610    if (ok) {
23611       size_t len = strlen(inbuf);
23612       subbuf = alloca(len + 1);
23613       ast_get_encoded_str(inbuf, subbuf, len + 1);
23614       pbx_builtin_setvar_helper(chan, varbuf, subbuf);
23615       if (sipdebug) {
23616          ast_debug(1, "SIP Header added \"%s\" as %s\n", inbuf, varbuf);
23617       }
23618    } else {
23619       ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
23620    }
23621    ast_channel_unlock(chan);
23622    return 0;
23623 }
23624 
23625 /*! \brief Transfer call before connect with a 302 redirect
23626 \note Called by the transfer() dialplan application through the sip_transfer()
23627    pbx interface function if the call is in ringing state 
23628 \todo Fix this function so that we wait for reply to the REFER and
23629    react to errors, denials or other issues the other end might have.
23630  */
23631 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
23632 {
23633    char *cdest;
23634    char *extension, *host, *port;
23635    char tmp[80];
23636 
23637    cdest = ast_strdupa(dest);
23638    
23639    extension = strsep(&cdest, "@");
23640    host = strsep(&cdest, ":");
23641    port = strsep(&cdest, ":");
23642    if (ast_strlen_zero(extension)) {
23643       ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
23644       return 0;
23645    }
23646 
23647    /* we'll issue the redirect message here */
23648    if (!host) {
23649       char *localtmp;
23650 
23651       ast_copy_string(tmp, get_header(&p->initreq, "To"), sizeof(tmp));
23652       if (ast_strlen_zero(tmp)) {
23653          ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
23654          return 0;
23655       }
23656       if ( ( (localtmp = strcasestr(tmp, "sip:")) || (localtmp = strcasestr(tmp, "sips:")) ) 
23657          && (localtmp = strchr(localtmp, '@'))) {
23658          char lhost[80], lport[80];
23659 
23660          memset(lhost, 0, sizeof(lhost));
23661          memset(lport, 0, sizeof(lport));
23662          localtmp++;
23663          /* This is okey because lhost and lport are as big as tmp */
23664          sscanf(localtmp, "%80[^<>:; ]:%80[^<>:; ]", lhost, lport);
23665          if (ast_strlen_zero(lhost)) {
23666             ast_log(LOG_ERROR, "Can't find the host address\n");
23667             return 0;
23668          }
23669          host = ast_strdupa(lhost);
23670          if (!ast_strlen_zero(lport)) {
23671             port = ast_strdupa(lport);
23672          }
23673       }
23674    }
23675 
23676    ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s%s%s>", extension, host, port ? ":" : "", port ? port : "");
23677    transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
23678 
23679    sip_scheddestroy(p, SIP_TRANS_TIMEOUT);   /* Make sure we stop send this reply. */
23680    sip_alreadygone(p);
23681    /* hangup here */
23682    return 0;
23683 }
23684 
23685 /*! \brief Return SIP UA's codec (part of the RTP interface) */
23686 static int sip_get_codec(struct ast_channel *chan)
23687 {
23688    struct sip_pvt *p = chan->tech_pvt;
23689    return p->jointcapability ? p->jointcapability : p->capability;   
23690 }
23691 
23692 /*! \brief Send a poke to all known peers 
23693    Space them out 100 ms apart
23694    XXX We might have a cool algorithm for this or use random - any suggestions?
23695 */
23696 static void sip_poke_all_peers(void)
23697 {
23698    int ms = 0;
23699    struct ao2_iterator i;
23700    struct sip_peer *peer;
23701 
23702    i = ao2_iterator_init(peers, 0);
23703    
23704    if (!speerobjs)   /* No peers, just give up */
23705       return;
23706 
23707    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
23708       ao2_lock(peer);
23709       ms += 100;
23710       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ms, sip_poke_peer_s, peer,
23711             unref_peer(_data, "removing poke peer ref"),
23712             unref_peer(peer, "removing poke peer ref"),
23713             ref_peer(peer, "adding poke peer ref"));
23714       ao2_unlock(peer);
23715       unref_peer(peer, "toss iterator peer ptr");
23716    }
23717 }
23718 
23719 /*! \brief Send all known registrations */
23720 static void sip_send_all_registers(void)
23721 {
23722    int ms;
23723    int regspacing;
23724    if (!regobjs)
23725       return;
23726    regspacing = default_expiry * 1000/regobjs;
23727    if (regspacing > 100)
23728       regspacing = 100;
23729    ms = regspacing;
23730    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
23731       ASTOBJ_WRLOCK(iterator);
23732       ms += regspacing;
23733       AST_SCHED_REPLACE_UNREF(iterator->expire, sched, ms, sip_reregister, iterator, 
23734                         registry_unref(_data, "REPLACE sched del decs the refcount"),
23735                         registry_unref(iterator, "REPLACE sched add failure decs the refcount"),
23736                         registry_addref(iterator, "REPLACE sched add incs the refcount"));
23737       ASTOBJ_UNLOCK(iterator);
23738    } while (0)
23739    );
23740 }
23741 
23742 /*! \brief Reload module */
23743 static int sip_do_reload(enum channelreloadreason reason)
23744 {
23745    time_t start_poke, end_poke;
23746    
23747    reload_config(reason);
23748    ast_sched_dump(sched);
23749 
23750    start_poke = time(0);
23751    /* Prune peers who still are supposed to be deleted */
23752    ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, 0, 
23753          "callback to remove marked peers");
23754    
23755    ast_debug(4, "--------------- Done destroying pruned peers\n");
23756 
23757    /* Send qualify (OPTIONS) to all peers */
23758    sip_poke_all_peers();
23759 
23760    /* Register with all services */
23761    sip_send_all_registers();
23762    end_poke = time(0);
23763    
23764    ast_debug(4, "do_reload finished. peer poke/prune reg contact time = %d sec.\n", (int)(end_poke-start_poke));
23765 
23766    ast_debug(4, "--------------- SIP reload done\n");
23767 
23768    return 0;
23769 }
23770 
23771 /*! \brief Force reload of module from cli */
23772 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
23773 {
23774    
23775    switch (cmd) {
23776    case CLI_INIT:
23777       e->command = "sip reload";
23778       e->usage =
23779          "Usage: sip reload\n"
23780          "       Reloads SIP configuration from sip.conf\n";
23781       return NULL;
23782    case CLI_GENERATE:
23783       return NULL;
23784    }
23785 
23786    ast_mutex_lock(&sip_reload_lock);
23787    if (sip_reloading) 
23788       ast_verbose("Previous SIP reload not yet done\n");
23789    else {
23790       sip_reloading = TRUE;
23791       sip_reloadreason = (a && a->fd) ? CHANNEL_CLI_RELOAD : CHANNEL_MODULE_RELOAD;
23792    }
23793    ast_mutex_unlock(&sip_reload_lock);
23794    restart_monitor();
23795 
23796    return CLI_SUCCESS;
23797 }
23798 
23799 /*! \brief  Part of Asterisk module interface */
23800 static int reload(void)
23801 {
23802    if (sip_reload(0, 0, NULL))
23803       return 0;
23804    return 1;
23805 }
23806 
23807 static struct ast_cli_entry cli_sip_do_history_deprecated = AST_CLI_DEFINE(sip_do_history_deprecated, "Enable/Disable SIP history");
23808 /*! \brief SIP Cli commands definition */
23809 static struct ast_cli_entry cli_sip[] = {
23810    AST_CLI_DEFINE(sip_show_channels, "List active SIP channels or subscriptions"),
23811    AST_CLI_DEFINE(sip_show_channelstats, "List statistics for active SIP channels"),
23812    AST_CLI_DEFINE(sip_show_domains, "List our local SIP domains"),
23813    AST_CLI_DEFINE(sip_show_inuse, "List all inuse/limits"),
23814    AST_CLI_DEFINE(sip_show_objects, "List all SIP object allocations"),
23815    AST_CLI_DEFINE(sip_show_peers, "List defined SIP peers"),
23816    AST_CLI_DEFINE(sip_show_registry, "List SIP registration status"),
23817    AST_CLI_DEFINE(sip_unregister, "Unregister (force expiration) a SIP peer from the registry"),
23818    AST_CLI_DEFINE(sip_show_settings, "Show SIP global settings"),
23819    AST_CLI_DEFINE(sip_cli_notify, "Send a notify packet to a SIP peer"),
23820    AST_CLI_DEFINE(sip_show_channel, "Show detailed SIP channel info"),
23821    AST_CLI_DEFINE(sip_show_history, "Show SIP dialog history"),
23822    AST_CLI_DEFINE(sip_show_peer, "Show details on specific SIP peer"),
23823    AST_CLI_DEFINE(sip_show_users, "List defined SIP users"),
23824    AST_CLI_DEFINE(sip_show_user, "Show details on specific SIP user"),
23825    AST_CLI_DEFINE(sip_qualify_peer, "Send an OPTIONS packet to a peer"),
23826    AST_CLI_DEFINE(sip_show_sched, "Present a report on the status of the sched queue"),
23827    AST_CLI_DEFINE(sip_prune_realtime, "Prune cached Realtime users/peers"),
23828    AST_CLI_DEFINE(sip_do_debug, "Enable/Disable SIP debugging"),
23829    AST_CLI_DEFINE(sip_set_history, "Enable/Disable SIP history", .deprecate_cmd = &cli_sip_do_history_deprecated),
23830    AST_CLI_DEFINE(sip_reload, "Reload SIP configuration"),
23831    AST_CLI_DEFINE(sip_show_tcp, "List TCP Connections")
23832 };
23833 
23834 /*! \brief PBX load module - initialization */
23835 static int load_module(void)
23836 {
23837    ast_verbose("SIP channel loading...\n");
23838    /* the fact that ao2_containers can't resize automatically is a major worry! */
23839    /* if the number of objects gets above MAX_XXX_BUCKETS, things will slow down */
23840    peers = ao2_t_container_alloc(hash_peer_size, peer_hash_cb, peer_cmp_cb, "allocate peers");
23841    peers_by_ip = ao2_t_container_alloc(hash_peer_size, peer_iphash_cb, peer_ipcmp_cb, "allocate peers_by_ip");
23842    dialogs = ao2_t_container_alloc(hash_dialog_size, dialog_hash_cb, dialog_cmp_cb, "allocate dialogs");
23843    
23844    ASTOBJ_CONTAINER_INIT(&regl); /* Registry object list -- not searched for anything */
23845 
23846    if (!(sched = sched_context_create())) {
23847       ast_log(LOG_ERROR, "Unable to create scheduler context\n");
23848       return AST_MODULE_LOAD_FAILURE;
23849    }
23850 
23851    if (!(io = io_context_create())) {
23852       ast_log(LOG_ERROR, "Unable to create I/O context\n");
23853       sched_context_destroy(sched);
23854       return AST_MODULE_LOAD_FAILURE;
23855    }
23856 
23857    sip_reloadreason = CHANNEL_MODULE_LOAD;
23858 
23859    if(reload_config(sip_reloadreason)) /* Load the configuration from sip.conf */
23860       return AST_MODULE_LOAD_DECLINE;
23861 
23862    /* Prepare the version that does not require DTMF BEGIN frames.
23863     * We need to use tricks such as memcpy and casts because the variable
23864     * has const fields.
23865     */
23866    memcpy(&sip_tech_info, &sip_tech, sizeof(sip_tech));
23867    memset((void *) &sip_tech_info.send_digit_begin, 0, sizeof(sip_tech_info.send_digit_begin));
23868 
23869    /* Make sure we can register our sip channel type */
23870    if (ast_channel_register(&sip_tech)) {
23871       ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
23872       io_context_destroy(io);
23873       sched_context_destroy(sched);
23874       return AST_MODULE_LOAD_FAILURE;
23875    }
23876 
23877    /* Register all CLI functions for SIP */
23878    ast_cli_register_multiple(cli_sip, sizeof(cli_sip)/ sizeof(struct ast_cli_entry));
23879 
23880    /* Tell the RTP subdriver that we're here */
23881    ast_rtp_proto_register(&sip_rtp);
23882 
23883    /* Tell the UDPTL subdriver that we're here */
23884    ast_udptl_proto_register(&sip_udptl);
23885 
23886    /* Register dialplan applications */
23887    ast_register_application(app_dtmfmode, sip_dtmfmode, synopsis_dtmfmode, descrip_dtmfmode);
23888    ast_register_application(app_sipaddheader, sip_addheader, synopsis_sipaddheader, descrip_sipaddheader);
23889 
23890    /* Register dialplan functions */
23891    ast_custom_function_register(&sip_header_function);
23892    ast_custom_function_register(&sippeer_function);
23893    ast_custom_function_register(&sipchaninfo_function);
23894    ast_custom_function_register(&checksipdomain_function);
23895 
23896    /* Register manager commands */
23897    ast_manager_register2("SIPpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peers,
23898          "List SIP peers (text format)", mandescr_show_peers);
23899    ast_manager_register2("SIPshowpeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peer,
23900          "Show SIP peer (text format)", mandescr_show_peer);
23901    ast_manager_register2("SIPqualifypeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_qualify_peer,
23902          "Show SIP peer (text format)", mandescr_show_peer);   /*! \todo Fix this XXX This must be all wrong XXXX */
23903    ast_manager_register2("SIPshowregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_show_registry,
23904          "Show SIP registrations (text format)", mandescr_show_registry);
23905    ast_manager_register2("SIPnotify", EVENT_FLAG_SYSTEM, manager_sipnotify,
23906          "Send a SIP notify", mandescr_sipnotify);
23907    sip_poke_all_peers();   
23908    sip_send_all_registers();
23909    
23910    /* And start the monitor for the first time */
23911    restart_monitor();
23912 
23913    ast_realtime_require_field(ast_check_realtime("sipregs") ? "sipregs" : "sippeers",
23914       "name", RQ_CHAR, 10,
23915       "ipaddr", RQ_CHAR, 15,
23916       "port", RQ_UINTEGER2, 5,
23917       "regseconds", RQ_INTEGER4, 11,
23918       "defaultuser", RQ_CHAR, 10,
23919       "fullcontact", RQ_CHAR, 35,
23920       "regserver", RQ_CHAR, 20,
23921       "useragent", RQ_CHAR, 20,
23922       "lastms", RQ_INTEGER4, 11,
23923       SENTINEL);
23924 
23925    return AST_MODULE_LOAD_SUCCESS;
23926 }
23927 
23928 /*! \brief PBX unload module API */
23929 static int unload_module(void)
23930 {
23931    struct sip_pvt *p;
23932    struct sip_threadinfo *th;
23933    struct ast_context *con;
23934    struct ao2_iterator i;
23935 
23936    ast_sched_dump(sched);
23937    
23938    /* First, take us out of the channel type list */
23939    ast_channel_unregister(&sip_tech);
23940 
23941    /* Unregister dial plan functions */
23942    ast_custom_function_unregister(&sipchaninfo_function);
23943    ast_custom_function_unregister(&sippeer_function);
23944    ast_custom_function_unregister(&sip_header_function);
23945    ast_custom_function_unregister(&checksipdomain_function);
23946 
23947    /* Unregister dial plan applications */
23948    ast_unregister_application(app_dtmfmode);
23949    ast_unregister_application(app_sipaddheader);
23950 
23951    /* Unregister CLI commands */
23952    ast_cli_unregister_multiple(cli_sip, sizeof(cli_sip) / sizeof(struct ast_cli_entry));
23953 
23954    /* Disconnect from the RTP subsystem */
23955    ast_rtp_proto_unregister(&sip_rtp);
23956 
23957    /* Disconnect from UDPTL */
23958    ast_udptl_proto_unregister(&sip_udptl);
23959 
23960    /* Unregister AMI actions */
23961    ast_manager_unregister("SIPpeers");
23962    ast_manager_unregister("SIPshowpeer");
23963    ast_manager_unregister("SIPqualifypeer");
23964    ast_manager_unregister("SIPshowregistry");
23965    ast_manager_unregister("SIPnotify");
23966    
23967    /* Kill TCP/TLS server threads */
23968    if (sip_tcp_desc.master)
23969       ast_tcptls_server_stop(&sip_tcp_desc);
23970    if (sip_tls_desc.master)
23971       ast_tcptls_server_stop(&sip_tls_desc);
23972 
23973    /* Kill all existing TCP/TLS threads */
23974    AST_LIST_LOCK(&threadl);
23975    AST_LIST_TRAVERSE_SAFE_BEGIN(&threadl, th, list) {
23976       pthread_t thread = th->threadid;
23977       th->stop = 1;
23978       AST_LIST_UNLOCK(&threadl);
23979       pthread_kill(thread, SIGURG);
23980       pthread_join(thread, NULL);
23981       AST_LIST_LOCK(&threadl);
23982    }
23983    AST_LIST_TRAVERSE_SAFE_END;
23984    AST_LIST_UNLOCK(&threadl);
23985 
23986    /* Hangup all dialogs if they have an owner */
23987    i = ao2_iterator_init(dialogs, 0);
23988    while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
23989       if (p->owner)
23990          ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
23991       ao2_t_ref(p, -1, "toss dialog ptr from iterator_next");
23992    }
23993 
23994    ast_mutex_lock(&monlock);
23995    if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
23996       pthread_cancel(monitor_thread);
23997       pthread_kill(monitor_thread, SIGURG);
23998       pthread_join(monitor_thread, NULL);
23999    }
24000    monitor_thread = AST_PTHREADT_STOP;
24001    ast_mutex_unlock(&monlock);
24002 
24003    /* Destroy all the dialogs and free their memory */
24004    i = ao2_iterator_init(dialogs, 0);
24005    while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
24006       dialog_unlink_all(p, TRUE, TRUE);
24007       ao2_t_ref(p, -1, "throw away iterator result"); 
24008    }
24009 
24010    /* Free memory for local network address mask */
24011    ast_free_ha(localaddr);
24012 
24013    clear_realm_authentication(authl);
24014 
24015 
24016    if (default_tls_cfg.certfile)
24017       ast_free(default_tls_cfg.certfile);
24018    if (default_tls_cfg.cipher)
24019       ast_free(default_tls_cfg.cipher);
24020    if (default_tls_cfg.cafile)
24021       ast_free(default_tls_cfg.cafile);
24022    if (default_tls_cfg.capath)
24023       ast_free(default_tls_cfg.capath);
24024 
24025    ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
24026    ASTOBJ_CONTAINER_DESTROY(&regl);
24027 
24028    ao2_t_ref(peers, -1, "unref the peers table");
24029    ao2_t_ref(peers_by_ip, -1, "unref the peers_by_ip table");
24030    ao2_t_ref(dialogs, -1, "unref the dialogs table");
24031 
24032    clear_sip_domains();
24033    close(sipsock);
24034    sched_context_destroy(sched);
24035    con = ast_context_find(used_context);
24036    if (con)
24037       ast_context_destroy(con, "SIP");
24038    ast_unload_realtime("sipregs");
24039    ast_unload_realtime("sippeers");
24040 
24041    return 0;
24042 }
24043 
24044 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Session Initiation Protocol (SIP)",
24045       .load = load_module,
24046       .unload = unload_module,
24047       .reload = reload,
24048           );

Generated on 3 Mar 2010 for Asterisk - the Open Source PBX by  doxygen 1.6.1